]> git.donarmstrong.com Git - roundcube.git/blob - program/include/main.inc
Imported Upstream version 0.1.1
[roundcube.git] / program / include / main.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/main.inc                                              |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005-2008, RoundCube Dev, - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Provide basic functions for the webmail package                     |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: main.inc 1255 2008-04-05 12:49:21Z thomasb $
19
20 */
21
22 /**
23  * RoundCube Webmail common functions
24  *
25  * @package Core
26  * @author Thomas Bruederli <roundcube@gmail.com>
27  */
28
29 require_once('lib/utf7.inc');
30 require_once('include/rcube_user.inc');
31 require_once('include/rcube_shared.inc');
32 require_once('include/rcmail_template.inc');
33
34 // define constannts for input reading
35 define('RCUBE_INPUT_GET', 0x0101);
36 define('RCUBE_INPUT_POST', 0x0102);
37 define('RCUBE_INPUT_GPC', 0x0103);
38
39
40 /**
41  * Initial startup function
42  * to register session, create database and imap connections
43  *
44  * @param string Current task
45  */
46 function rcmail_startup($task='mail')
47   {
48   global $sess_id, $sess_user_lang;
49   global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $USER;
50
51   // check client
52   $BROWSER = rcube_browser();
53
54   // load configuration
55   $CONFIG = rcmail_load_config();
56
57   // set session domain
58   if (isset($CONFIG['session_domain']) && !empty($CONFIG['session_domain'])) {
59     ini_set('session.cookie_domain', $CONFIG['session_domain']);
60   }
61
62   // set session garbage collecting time according to session_lifetime
63   if (!empty($CONFIG['session_lifetime']))
64     ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
65
66   // prepare DB connection
67   $dbwrapper = empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend'];
68   $dbclass = "rcube_" . $dbwrapper;
69   require_once("include/$dbclass.inc");
70   
71   $DB = new $dbclass($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
72   $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
73   $DB->set_debug((bool)$CONFIG['sql_debug']);
74   $DB->db_connect('w');
75
76   // use database for storing session data
77   include_once('include/session.inc');
78
79   // init session
80   session_start();
81   $sess_id = session_id();
82
83   // create session and set session vars
84   if (!isset($_SESSION['auth_time']))
85     {
86     $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
87     $_SESSION['auth_time'] = time();
88     $_SESSION['temp'] = true;
89     }
90
91   // set session vars global
92   $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
93
94   // create user object
95   $USER = new rcube_user($_SESSION['user_id']);
96
97   // overwrite config with user preferences
98   $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
99
100
101   // reset some session parameters when changing task
102   if ($_SESSION['task'] != $task)
103     unset($_SESSION['page']);
104
105   // set current task to session
106   $_SESSION['task'] = $task;
107
108   // create IMAP object
109   if ($task=='mail')
110     rcmail_imap_init();
111
112
113   // set localization
114   if ($CONFIG['locale_string'])
115     setlocale(LC_ALL, $CONFIG['locale_string']);
116   else if ($sess_user_lang)
117     setlocale(LC_ALL, $sess_user_lang);
118
119
120   register_shutdown_function('rcmail_shutdown');
121   }
122
123
124 /**
125  * Load roundcube configuration array
126  *
127  * @return array Named configuration parameters
128  */
129 function rcmail_load_config()
130   {
131   global $INSTALL_PATH;
132
133   // load config file
134   include_once('config/main.inc.php');
135   $conf = is_array($rcmail_config) ? $rcmail_config : array();
136
137   // load host-specific configuration
138   rcmail_load_host_config($conf);
139
140   $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
141
142   // load db conf
143   include_once('config/db.inc.php');
144   $conf = array_merge($conf, $rcmail_config);
145
146   if (empty($conf['log_dir']))
147     $conf['log_dir'] = $INSTALL_PATH.'logs';
148   else
149     $conf['log_dir'] = unslashify($conf['log_dir']);
150
151   // set PHP error logging according to config
152   if ($conf['debug_level'] & 1)
153     {
154     ini_set('log_errors', 1);
155     ini_set('error_log', $conf['log_dir'].'/errors');
156     }
157   if ($conf['debug_level'] & 4)
158     ini_set('display_errors', 1);
159   else
160     ini_set('display_errors', 0);
161
162   return $conf;
163   }
164
165
166 /**
167  * Load a host-specific config file if configured
168  * This will merge the host specific configuration with the given one
169  *
170  * @param array Global configuration parameters
171  */
172 function rcmail_load_host_config(&$config)
173   {
174   $fname = NULL;
175   
176   if (is_array($config['include_host_config']))
177     $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
178   else if (!empty($config['include_host_config']))
179     $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
180
181    if ($fname && is_file('config/'.$fname))
182      {
183      include('config/'.$fname);
184      $config = array_merge($config, $rcmail_config);
185      }
186   }
187
188
189 /**
190  * Create unique authorization hash
191  *
192  * @param string Session ID
193  * @param int Timestamp
194  * @return string The generated auth hash
195  */
196 function rcmail_auth_hash($sess_id, $ts)
197   {
198   global $CONFIG;
199   
200   $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
201                          $sess_id,
202                          $ts,
203                          $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
204                          $_SERVER['HTTP_USER_AGENT']);
205   
206   if (function_exists('sha1'))
207     return sha1($auth_string);
208   else
209     return md5($auth_string);
210   }
211
212
213 /**
214  * Check the auth hash sent by the client against the local session credentials
215  *
216  * @return boolean True if valid, False if not
217  */
218 function rcmail_authenticate_session()
219   {
220   global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
221   
222   // advanced session authentication
223   if ($CONFIG['double_auth'])
224   {
225     $now = time();
226     $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
227               $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
228
229     // renew auth cookie every 5 minutes (only for GET requests)
230     if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
231     {
232       $_SESSION['last_auth'] = $_SESSION['auth_time'];
233       $_SESSION['auth_time'] = $now;
234       setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
235     }
236   }
237   else
238     $valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
239   
240   // check session filetime
241   if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED)
242       && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < time())
243     $valid = false;
244   
245   return $valid;
246   }
247
248
249 /**
250  * Create global IMAP object and connect to server
251  *
252  * @param boolean True if connection should be established
253  */
254 function rcmail_imap_init($connect=FALSE)
255   {
256   global $CONFIG, $DB, $IMAP, $OUTPUT;
257
258   $IMAP = new rcube_imap($DB);
259   $IMAP->debug_level = $CONFIG['debug_level'];
260   $IMAP->skip_deleted = $CONFIG['skip_deleted'];
261
262
263   // connect with stored session data
264   if ($connect)
265     {
266     if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
267       $OUTPUT->show_message('imaperror', 'error');
268       
269     rcmail_set_imap_prop();
270     }
271
272   // enable caching of imap data
273   if ($CONFIG['enable_caching']===TRUE)
274     $IMAP->set_caching(TRUE);
275
276   // set pagesize from config
277   if (isset($CONFIG['pagesize']))
278     $IMAP->set_pagesize($CONFIG['pagesize']);
279   }
280
281
282 /**
283  * Set root dir and last stored mailbox
284  * This must be done AFTER connecting to the server!
285  */
286 function rcmail_set_imap_prop()
287   {
288   global $CONFIG, $IMAP;
289   
290   if (!empty($CONFIG['default_charset']))
291     $IMAP->set_charset($CONFIG['default_charset']);
292
293   // set root dir from config
294   if (!empty($CONFIG['imap_root']))
295     $IMAP->set_rootdir($CONFIG['imap_root']);
296
297   if (is_array($CONFIG['default_imap_folders']))
298     $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
299
300   if (!empty($_SESSION['mbox']))
301     $IMAP->set_mailbox($_SESSION['mbox']);
302   if (isset($_SESSION['page']))
303     $IMAP->set_page($_SESSION['page']);
304   }
305
306
307 /**
308  * Do these things on script shutdown
309  */
310 function rcmail_shutdown()
311   {
312   global $IMAP, $CONTACTS;
313   
314   if (is_object($IMAP))
315     {
316     $IMAP->close();
317     $IMAP->write_cache();
318     }
319     
320   if (is_object($CONTACTS))
321     $CONTACTS->close();
322     
323   // before closing the database connection, write session data
324   session_write_close();
325   }
326
327
328 /**
329  * Destroy session data and remove cookie
330  */
331 function rcmail_kill_session()
332   {
333   global $USER;
334   
335   if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
336       (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
337     {
338     $a_user_prefs = array('message_sort_col' => $_SESSION['sort_col'], 'message_sort_order' => $_SESSION['sort_order']);
339     $USER->save_prefs($a_user_prefs);
340     }
341
342   $_SESSION = array('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
343   setcookie('sessauth', '-del-', time()-60);
344   $USER->reset();
345   }
346
347
348 /**
349  * Return correct name for a specific database table
350  *
351  * @param string Table name
352  * @return string Translated table name
353  */
354 function get_table_name($table)
355   {
356   global $CONFIG;
357   
358   // return table name if configured
359   $config_key = 'db_table_'.$table;
360
361   if (strlen($CONFIG[$config_key]))
362     return $CONFIG[$config_key];
363   
364   return $table;
365   }
366
367
368 /**
369  * Return correct name for a specific database sequence
370  * (used for Postres only)
371  *
372  * @param string Secuence name
373  * @return string Translated sequence name
374  */
375 function get_sequence_name($sequence)
376   {
377   global $CONFIG;
378   
379   // return table name if configured
380   $config_key = 'db_sequence_'.$sequence;
381
382   if (strlen($CONFIG[$config_key]))
383     return $CONFIG[$config_key];
384   
385   return $sequence;
386   }
387
388
389 /**
390  * Check the given string and returns language properties
391  *
392  * @param string Language code
393  * @param string Peropert name
394  * @return string Property value
395  */
396 function rcube_language_prop($lang, $prop='lang')
397   {
398   global $INSTALL_PATH;
399   static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
400
401   if (empty($rcube_languages))
402     @include($INSTALL_PATH.'program/localization/index.inc');
403     
404   // check if we have an alias for that language
405   if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
406     $lang = $rcube_language_aliases[$lang];
407     
408   // try the first two chars
409   if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
410     {
411     $lang = substr($lang, 0, 2);
412     $lang = rcube_language_prop($lang);
413     }
414
415   if (!isset($rcube_languages[$lang]))
416     $lang = 'en_US';
417
418   // language has special charset configured
419   if (isset($rcube_charsets[$lang]))
420     $charset = $rcube_charsets[$lang];
421   else
422     $charset = 'UTF-8';    
423
424
425   if ($prop=='charset')
426     return $charset;
427   else
428     return $lang;
429   }
430   
431
432 /**
433  * Init output object for GUI and add common scripts.
434  * This will instantiate a rcmail_template object and set
435  * environment vars according to the current session and configuration
436  */
437 function rcmail_load_gui()
438   {
439   global $CONFIG, $OUTPUT, $sess_user_lang;
440
441   // init output page
442   $OUTPUT = new rcmail_template($CONFIG, $GLOBALS['_task']);
443   $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
444
445   if (is_array($CONFIG['javascript_config']))
446   {
447     foreach ($CONFIG['javascript_config'] as $js_config_var)
448       $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
449   }
450
451   if (!empty($GLOBALS['_framed']))
452     $OUTPUT->set_env('framed', true);
453
454   // set locale setting
455   rcmail_set_locale($sess_user_lang);
456
457   // set user-selected charset
458   if (!empty($CONFIG['charset']))
459     $OUTPUT->set_charset($CONFIG['charset']);
460     
461   // register common UI objects
462   $OUTPUT->add_handlers(array(
463     'loginform' => 'rcmail_login_form',
464     'username'  => 'rcmail_current_username',
465     'message' => 'rcmail_message_container',
466     'charsetselector' => 'rcmail_charset_selector',
467   ));
468
469   // add some basic label to client
470   if (!$OUTPUT->ajax_call)
471     rcube_add_label('loading', 'movingmessage');
472   }
473
474
475 /**
476  * Set localization charset based on the given language.
477  * This also creates a global property for mbstring usage.
478  */
479 function rcmail_set_locale($lang)
480   {
481   global $OUTPUT, $MBSTRING;
482   static $s_mbstring_loaded = NULL;
483   
484   // settings for mbstring module (by Tadashi Jokagi)
485   if (is_null($s_mbstring_loaded)) 
486     $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring"); 
487   else
488     $MBSTRING = $s_mbstring_loaded = FALSE;
489   
490   if ($MBSTRING)
491     mb_internal_encoding(RCMAIL_CHARSET);
492
493   $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
494   }
495
496
497 /**
498  * Auto-select IMAP host based on the posted login information
499  *
500  * @return string Selected IMAP host
501  */
502 function rcmail_autoselect_host()
503   {
504   global $CONFIG;
505   
506   $host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
507   if (is_array($host))
508     {
509     list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
510     if (!empty($domain))
511       {
512       foreach ($host as $imap_host => $mail_domains)
513         if (is_array($mail_domains) && in_array($domain, $mail_domains))
514           {
515           $host = $imap_host;
516           break;
517           }
518       }
519
520     // take the first entry if $host is still an array
521     if (is_array($host))
522       $host = array_shift($host);
523     }
524   
525   return $host;
526   }
527
528
529 /**
530  * Perfom login to the IMAP server and to the webmail service.
531  * This will also create a new user entry if auto_create_user is configured.
532  *
533  * @param string IMAP user name
534  * @param string IMAP password
535  * @param string IMAP host
536  * @return boolean True on success, False on failure
537  */
538 function rcmail_login($user, $pass, $host=NULL)
539   {
540   global $CONFIG, $IMAP, $DB, $USER, $sess_user_lang;
541   $user_id = NULL;
542   
543   if (!$host)
544     $host = $CONFIG['default_host'];
545
546   // Validate that selected host is in the list of configured hosts
547   if (is_array($CONFIG['default_host']))
548     {
549     $allowed = FALSE;
550     foreach ($CONFIG['default_host'] as $key => $host_allowed)
551       {
552       if (!is_numeric($key))
553         $host_allowed = $key;
554       if ($host == $host_allowed)
555         {
556         $allowed = TRUE;
557         break;
558         }
559       }
560     if (!$allowed)
561       return FALSE;
562     }
563   else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
564     return FALSE;
565
566   // parse $host URL
567   $a_host = parse_url($host);
568   if ($a_host['host'])
569     {
570     $host = $a_host['host'];
571     $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
572     $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
573     }
574   else
575     $imap_port = $CONFIG['default_port'];
576
577
578   /* Modify username with domain if required  
579      Inspired by Marco <P0L0_notspam_binware.org>
580   */
581   // Check if we need to add domain
582   if (!empty($CONFIG['username_domain']) && !strpos($user, '@'))
583     {
584     if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
585       $user .= '@'.$CONFIG['username_domain'][$host];
586     else if (is_string($CONFIG['username_domain']))
587       $user .= '@'.$CONFIG['username_domain'];
588     }
589
590   // try to resolve email address from virtuser table    
591   if (!empty($CONFIG['virtuser_file']) && strpos($user, '@'))
592     $user = rcube_user::email2user($user);
593
594   // lowercase username if it's an e-mail address (#1484473)
595   if (strpos($user, '@'))
596     $user = strtolower($user);
597
598   // query if user already registered
599   if ($existing = rcube_user::query($user, $host))
600     $USER = $existing;
601
602   // user already registered -> overwrite username
603   if ($USER->ID)
604     {
605     $user_id = $USER->ID;
606     $user = $USER->data['username'];
607     }
608
609   // exit if IMAP login failed
610   if (!($imap_login  = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
611     return false;
612
613   // user already registered
614   if ($USER->ID)
615     {
616     // get user prefs
617     $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
618
619     // set user specific language
620     if (!empty($USER->data['language']))
621       $sess_user_lang = $_SESSION['user_lang'] = $USER->data['language'];
622       
623     // update user's record
624     $USER->touch();
625     }
626   // create new system user
627   else if ($CONFIG['auto_create_user'])
628     {
629     if ($created = rcube_user::create($user, $host))
630     {
631       $USER = $created;
632       
633       // get existing mailboxes
634       $a_mailboxes = $IMAP->list_mailboxes();
635     }
636     }
637   else
638     {
639     raise_error(array(
640       'code' => 600,
641       'type' => 'php',
642       'file' => "config/main.inc.php",
643       'message' => "Acces denied for new user $user. 'auto_create_user' is disabled"
644       ), true, false);
645     }
646
647   if ($USER->ID)
648     {
649     $_SESSION['user_id']   = $USER->ID;
650     $_SESSION['username']  = $USER->data['username'];
651     $_SESSION['imap_host'] = $host;
652     $_SESSION['imap_port'] = $imap_port;
653     $_SESSION['imap_ssl']  = $imap_ssl;
654     $_SESSION['user_lang'] = $sess_user_lang;
655     $_SESSION['password']  = encrypt_passwd($pass);
656     $_SESSION['login_time'] = mktime();
657
658     // force reloading complete list of subscribed mailboxes
659     rcmail_set_imap_prop();
660     $IMAP->clear_cache('mailboxes');
661
662     if ($CONFIG['create_default_folders'])
663         $IMAP->create_default_folders();
664
665     return TRUE;
666     }
667
668   return FALSE;
669   }
670
671
672 /**
673  * Load virtuser table in array
674  *
675  * @return array Virtuser table entries
676  */
677 function rcmail_getvirtualfile()
678   {
679   global $CONFIG;
680   if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
681     return FALSE;
682   
683   // read file 
684   $a_lines = file($CONFIG['virtuser_file']);
685   return $a_lines;
686   }
687
688
689 /**
690  * Find matches of the given pattern in virtuser table
691  * 
692  * @param string Regular expression to search for
693  * @return array Matching entries
694  */
695 function rcmail_findinvirtual($pattern)
696   {
697   $result = array();
698   $virtual = rcmail_getvirtualfile();
699   if ($virtual==FALSE)
700     return $result;
701
702   // check each line for matches
703   foreach ($virtual as $line)
704     {
705     $line = trim($line);
706     if (empty($line) || $line{0}=='#')
707       continue;
708       
709     if (eregi($pattern, $line))
710       $result[] = $line;
711     }
712
713   return $result;
714   }
715
716
717 /**
718  * Overwrite action variable
719  *
720  * @param string New action value
721  */
722 function rcmail_overwrite_action($action)
723   {
724   global $OUTPUT;
725   $GLOBALS['_action'] = $action;
726   $OUTPUT->set_env('action', $action);
727   }
728
729
730 /**
731  * Compose an URL for a specific action
732  *
733  * @param string  Request action
734  * @param array   More URL parameters
735  * @param string  Request task (omit if the same)
736  * @return The application URL
737  */
738 function rcmail_url($action, $p=array(), $task=null)
739 {
740   global $MAIN_TASKS, $COMM_PATH;
741   $qstring = '';
742   $base = $COMM_PATH;
743   
744   if ($task && in_array($task, $MAIN_TASKS))
745     $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
746   
747   if (is_array($p))
748     foreach ($p as $key => $val)
749       $qstring .= '&'.urlencode($key).'='.urlencode($val);
750   
751   return $base . ($action ? '&_action='.$action : '') . $qstring;
752 }
753
754
755 // @deprecated
756 function show_message($message, $type='notice', $vars=NULL)
757   {
758   global $OUTPUT;
759   $OUTPUT->show_message($message, $type, $vars);
760   }
761
762
763 /**
764  * Encrypt IMAP password using DES encryption
765  *
766  * @param string Password to encrypt
767  * @return string Encryprted string
768  */
769 function encrypt_passwd($pass)
770 {
771   if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
772     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
773     mcrypt_generic_init($td, get_des_key(), $iv);
774     $cypher = mcrypt_generic($td, $pass);
775     mcrypt_generic_deinit($td);
776     mcrypt_module_close($td);
777   }
778   else if (function_exists('des')) {
779     $cypher = des(get_des_key(), $pass, 1, 0, NULL);
780   }
781   else {
782     $cypher = $pass;
783     
784     raise_error(array(
785       'code' => 500,
786       'type' => 'php',
787       'file' => __FILE__,
788       'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
789       ), true, false);
790   }
791   
792   return base64_encode($cypher);
793 }
794
795
796 /**
797  * Decrypt IMAP password using DES encryption
798  *
799  * @param string Encrypted password
800  * @return string Plain password
801  */
802 function decrypt_passwd($cypher)
803 {
804   if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
805     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
806     mcrypt_generic_init($td, get_des_key(), $iv);
807     $pass = mdecrypt_generic($td, base64_decode($cypher));
808     mcrypt_generic_deinit($td);
809     mcrypt_module_close($td);
810   }
811   else if (function_exists('des')) {
812     $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
813   }
814   else {
815     $pass = base64_decode($cypher);
816   }
817   
818   return preg_replace('/\x00/', '', $pass);
819   }
820
821
822 /**
823  * Return a 24 byte key for the DES encryption
824  *
825  * @return string DES encryption key
826  */
827 function get_des_key()
828   {
829   $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
830   $len = strlen($key);
831   
832   // make sure the key is exactly 24 chars long
833   if ($len<24)
834     $key .= str_repeat('_', 24-$len);
835   else if ($len>24)
836     substr($key, 0, 24);
837   
838   return $key;
839   }
840
841
842 /**
843  * Read directory program/localization and return a list of available languages
844  *
845  * @return array List of available localizations
846  */
847 function rcube_list_languages()
848   {
849   global $CONFIG, $INSTALL_PATH;
850   static $sa_languages = array();
851
852   if (!sizeof($sa_languages))
853     {
854     @include($INSTALL_PATH.'program/localization/index.inc');
855
856     if ($dh = @opendir($INSTALL_PATH.'program/localization'))
857       {
858       while (($name = readdir($dh)) !== false)
859         {
860         if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
861           continue;
862
863         if ($label = $rcube_languages[$name])
864           $sa_languages[$name] = $label ? $label : $name;
865         }
866       closedir($dh);
867       }
868     }
869   return $sa_languages;
870   }
871
872
873 /**
874  * Add a localized label to the client environment
875  */
876 function rcube_add_label()
877   {
878   global $OUTPUT;
879   
880   $arg_list = func_get_args();
881   foreach ($arg_list as $i => $name)
882     $OUTPUT->command('add_label', $name, rcube_label($name));
883   }
884
885
886 /**
887  * Garbage collector function for temp files.
888  * Remove temp files older than two days
889  */
890 function rcmail_temp_gc()
891   {
892   $tmp = unslashify($CONFIG['temp_dir']);
893   $expire = mktime() - 172800;  // expire in 48 hours
894
895   if ($dir = opendir($tmp))
896     {
897     while (($fname = readdir($dir)) !== false)
898       {
899       if ($fname{0} == '.')
900         continue;
901
902       if (filemtime($tmp.'/'.$fname) < $expire)
903         @unlink($tmp.'/'.$fname);
904       }
905
906     closedir($dir);
907     }
908   }
909
910
911 /**
912  * Garbage collector for cache entries.
913  * Remove all expired message cache records
914  */
915 function rcmail_message_cache_gc()
916   {
917   global $DB, $CONFIG;
918   
919   // no cache lifetime configured
920   if (empty($CONFIG['message_cache_lifetime']))
921     return;
922   
923   // get target timestamp
924   $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
925   
926   $DB->query("DELETE FROM ".get_table_name('messages')."
927              WHERE  created < ".$DB->fromunixtime($ts));
928   }
929
930
931 /**
932  * Convert a string from one charset to another.
933  * Uses mbstring and iconv functions if possible
934  *
935  * @param  string Input string
936  * @param  string Suspected charset of the input string
937  * @param  string Target charset to convert to; defaults to RCMAIL_CHARSET
938  * @return Converted string
939  */
940 function rcube_charset_convert($str, $from, $to=NULL)
941   {
942   global $MBSTRING;
943   static $convert_warning = false;
944
945   $from = strtoupper($from);
946   $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
947   $error = false; $conv = null;
948
949   if ($from==$to || $str=='' || empty($from))
950     return $str;
951     
952   $aliases = array(
953     'UNKNOWN-8BIT'   => 'ISO-8859-15',
954     'X-UNKNOWN'      => 'ISO-8859-15',
955     'X-USER-DEFINED' => 'ISO-8859-15',
956     'ISO-8859-8-I'   => 'ISO-8859-8',
957     'KS_C_5601-1987' => 'EUC-KR',
958   );
959
960   // convert charset using iconv module  
961   if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
962     {
963     $aliases['GB2312'] = 'GB18030';
964     return iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
965     }
966
967   // convert charset using mbstring module  
968   if ($MBSTRING)
969     {
970     $aliases['UTF-7'] = 'UTF7-IMAP';
971     $aliases['WINDOWS-1257'] = 'ISO-8859-13';
972     
973     // return if convert succeeded
974     if (($out = mb_convert_encoding($str, ($aliases[$to] ? $aliases[$to] : $to), ($aliases[$from] ? $aliases[$from] : $from))) != '')
975       return $out;
976     }
977     
978   
979   if (class_exists('utf8'))
980     $conv = new utf8();
981
982   // convert string to UTF-8
983   if ($from == 'UTF-7')
984     $str = utf7_to_utf8($str);
985   else if (($from == 'ISO-8859-1') && function_exists('utf8_encode'))
986     $str = utf8_encode($str);
987   else if ($from != 'UTF-8' && $conv)
988     {
989     $conv->loadCharset($from);
990     $str = $conv->strToUtf8($str);
991     }
992   else if ($from != 'UTF-8')
993     $error = true;
994
995   // encode string for output
996   if ($to == 'UTF-7')
997     return utf8_to_utf7($str);
998   else if ($to == 'ISO-8859-1' && function_exists('utf8_decode'))
999     return utf8_decode($str);
1000   else if ($to != 'UTF-8' && $conv)
1001     {
1002     $conv->loadCharset($to);
1003     return $conv->utf8ToStr($str);
1004     }
1005   else if ($to != 'UTF-8')
1006     $error = true;
1007
1008   // report error
1009   if ($error && !$convert_warning)
1010     {
1011     raise_error(array(
1012       'code' => 500,
1013       'type' => 'php',
1014       'file' => __FILE__,
1015       'message' => "Could not convert string charset. Make sure iconv is installed or lib/utf8.class is available"
1016       ), true, false);
1017     
1018     $convert_warning = true;
1019     }
1020   
1021   // return UTF-8 string
1022   return $str;
1023   }
1024
1025
1026 /**
1027  * Replacing specials characters to a specific encoding type
1028  *
1029  * @param  string  Input string
1030  * @param  string  Encoding type: text|html|xml|js|url
1031  * @param  string  Replace mode for tags: show|replace|remove
1032  * @param  boolean Convert newlines
1033  * @return The quoted string
1034  */
1035 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
1036   {
1037   global $OUTPUT_TYPE, $OUTPUT;
1038   static $html_encode_arr, $js_rep_table, $xml_rep_table;
1039
1040   if (!$enctype)
1041     $enctype = $GLOBALS['OUTPUT_TYPE'];
1042
1043   // encode for plaintext
1044   if ($enctype=='text')
1045     return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
1046
1047   // encode for HTML output
1048   if ($enctype=='html')
1049     {
1050     if (!$html_encode_arr)
1051       {
1052       $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);        
1053       unset($html_encode_arr['?']);
1054       }
1055
1056     $ltpos = strpos($str, '<');
1057     $encode_arr = $html_encode_arr;
1058
1059     // don't replace quotes and html tags
1060     if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1061       {
1062       unset($encode_arr['"']);
1063       unset($encode_arr['<']);
1064       unset($encode_arr['>']);
1065       unset($encode_arr['&']);
1066       }
1067     else if ($mode=='remove')
1068       $str = strip_tags($str);
1069     
1070     // avoid douple quotation of &
1071     $out = preg_replace('/&amp;([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1072       
1073     return $newlines ? nl2br($out) : $out;
1074     }
1075
1076   if ($enctype=='url')
1077     return rawurlencode($str);
1078
1079   // if the replace tables for XML and JS are not yet defined
1080   if (!$js_rep_table)
1081     {
1082     $js_rep_table = $xml_rep_table = array();
1083     $xml_rep_table['&'] = '&amp;';
1084
1085     for ($c=160; $c<256; $c++)  // can be increased to support more charsets
1086       {
1087       $xml_rep_table[Chr($c)] = "&#$c;";
1088       
1089       if ($OUTPUT->get_charset()=='ISO-8859-1')
1090         $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1091       }
1092
1093     $xml_rep_table['"'] = '&quot;';
1094     }
1095
1096   // encode for XML
1097   if ($enctype=='xml')
1098     return strtr($str, $xml_rep_table);
1099
1100   // encode for javascript use
1101   if ($enctype=='js')
1102     {
1103     if ($OUTPUT->get_charset()!='UTF-8')
1104       $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1105       
1106     return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1107     }
1108
1109   // no encoding given -> return original string
1110   return $str;
1111   }
1112   
1113 /**
1114  * Quote a given string.
1115  * Shortcut function for rep_specialchars_output
1116  *
1117  * @return string HTML-quoted string
1118  * @see rep_specialchars_output()
1119  */
1120 function Q($str, $mode='strict', $newlines=TRUE)
1121   {
1122   return rep_specialchars_output($str, 'html', $mode, $newlines);
1123   }
1124
1125 /**
1126  * Quote a given string for javascript output.
1127  * Shortcut function for rep_specialchars_output
1128  * 
1129  * @return string JS-quoted string
1130  * @see rep_specialchars_output()
1131  */
1132 function JQ($str)
1133   {
1134   return rep_specialchars_output($str, 'js');
1135   }
1136
1137
1138 /**
1139  * Read input value and convert it for internal use
1140  * Performs stripslashes() and charset conversion if necessary
1141  * 
1142  * @param  string   Field name to read
1143  * @param  int      Source to get value from (GPC)
1144  * @param  boolean  Allow HTML tags in field value
1145  * @param  string   Charset to convert into
1146  * @return string   Field value or NULL if not available
1147  */
1148 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1149   {
1150   global $OUTPUT;
1151   $value = NULL;
1152   
1153   if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1154     $value = $_GET[$fname];
1155   else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1156     $value = $_POST[$fname];
1157   else if ($source==RCUBE_INPUT_GPC)
1158     {
1159     if (isset($_POST[$fname]))
1160       $value = $_POST[$fname];
1161     else if (isset($_GET[$fname]))
1162       $value = $_GET[$fname];
1163     else if (isset($_COOKIE[$fname]))
1164       $value = $_COOKIE[$fname];
1165     }
1166   
1167   // strip slashes if magic_quotes enabled
1168   if ((bool)get_magic_quotes_gpc())
1169     $value = stripslashes($value);
1170
1171   // remove HTML tags if not allowed    
1172   if (!$allow_html)
1173     $value = strip_tags($value);
1174   
1175   // convert to internal charset
1176   if (is_object($OUTPUT))
1177     return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1178   else
1179     return $value;
1180   }
1181
1182 /**
1183  * Remove all non-ascii and non-word chars
1184  * except . and -
1185  */
1186 function asciiwords($str)
1187 {
1188   return preg_replace('/[^a-z0-9.-_]/i', '', $str);
1189 }
1190
1191 /**
1192  * Remove single and double quotes from given string
1193  *
1194  * @param string Input value
1195  * @return string Dequoted string
1196  */
1197 function strip_quotes($str)
1198 {
1199   return preg_replace('/[\'"]/', '', $str);
1200 }
1201
1202
1203 /**
1204  * Remove new lines characters from given string
1205  *
1206  * @param string Input value
1207  * @return string Stripped string
1208  */
1209 function strip_newlines($str)
1210 {
1211   return preg_replace('/[\r\n]/', '', $str);
1212 }
1213
1214
1215 /**
1216  * Check if a specific template exists
1217  *
1218  * @param string Template name
1219  * @return boolean True if template exists
1220  */
1221 function template_exists($name)
1222   {
1223   global $CONFIG;
1224   $skin_path = $CONFIG['skin_path'];
1225
1226   // check template file
1227   return is_file("$skin_path/templates/$name.html");
1228   }
1229
1230
1231 /**
1232  * Wrapper for rcmail_template::parse()
1233  * @deprecated
1234  */
1235 function parse_template($name='main', $exit=true)
1236   {
1237   $GLOBALS['OUTPUT']->parse($name, $exit);
1238   }
1239
1240
1241 /**
1242  * Create a HTML table based on the given data
1243  *
1244  * @param  array  Named table attributes
1245  * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
1246  * @param  array  List of cols to show
1247  * @param  string Name of the identifier col
1248  * @return string HTML table code
1249  */
1250 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1251   {
1252   global $DB;
1253   
1254   // allow the following attributes to be added to the <table> tag
1255   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1256   
1257   $table = '<table' . $attrib_str . ">\n";
1258     
1259   // add table title
1260   $table .= "<thead><tr>\n";
1261
1262   foreach ($a_show_cols as $col)
1263     $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1264
1265   $table .= "</tr></thead>\n<tbody>\n";
1266   
1267   $c = 0;
1268   if (!is_array($table_data)) 
1269     {
1270     while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1271       {
1272       $zebra_class = $c%2 ? 'even' : 'odd';
1273
1274       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1275
1276       // format each col
1277       foreach ($a_show_cols as $col)
1278         {
1279         $cont = Q($sql_arr[$col]);
1280         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1281         }
1282
1283       $table .= "</tr>\n";
1284       $c++;
1285       }
1286     }
1287   else 
1288     {
1289     foreach ($table_data as $row_data)
1290       {
1291       $zebra_class = $c%2 ? 'even' : 'odd';
1292
1293       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1294
1295       // format each col
1296       foreach ($a_show_cols as $col)
1297         {
1298         $cont = Q($row_data[$col]);
1299         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1300         }
1301
1302       $table .= "</tr>\n";
1303       $c++;
1304       }
1305     }
1306
1307   // complete message table
1308   $table .= "</tbody></table>\n";
1309   
1310   return $table;
1311   }
1312
1313
1314 /**
1315  * Create an edit field for inclusion on a form
1316  * 
1317  * @param string col field name
1318  * @param string value field value
1319  * @param array attrib HTML element attributes for field
1320  * @param string type HTML element type (default 'text')
1321  * @return string HTML field definition
1322  */
1323 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1324   {
1325   $fname = '_'.$col;
1326   $attrib['name'] = $fname;
1327   
1328   if ($type=='checkbox')
1329     {
1330     $attrib['value'] = '1';
1331     $input = new checkbox($attrib);
1332     }
1333   else if ($type=='textarea')
1334     {
1335     $attrib['cols'] = $attrib['size'];
1336     $input = new textarea($attrib);
1337     }
1338   else
1339     $input = new textfield($attrib);
1340
1341   // use value from post
1342   if (!empty($_POST[$fname]))
1343     $value = get_input_value($fname, RCUBE_INPUT_POST);
1344
1345   $out = $input->show($value);
1346          
1347   return $out;
1348   }
1349
1350
1351 /**
1352  * Return the mail domain configured for the given host
1353  *
1354  * @param string IMAP host
1355  * @return string Resolved SMTP host
1356  */
1357 function rcmail_mail_domain($host)
1358   {
1359   global $CONFIG;
1360
1361   $domain = $host;
1362   if (is_array($CONFIG['mail_domain']))
1363     {
1364     if (isset($CONFIG['mail_domain'][$host]))
1365       $domain = $CONFIG['mail_domain'][$host];
1366     }
1367   else if (!empty($CONFIG['mail_domain']))
1368     $domain = $CONFIG['mail_domain'];
1369
1370   return $domain;
1371   }
1372
1373
1374 /**
1375  * Replace all css definitions with #container [def]
1376  * and remove css-inlined scripting
1377  *
1378  * @param string CSS source code
1379  * @param string Container ID to use as prefix
1380  * @return string Modified CSS source
1381  */
1382 function rcmail_mod_css_styles($source, $container_id, $base_url = '')
1383   {
1384   $a_css_values = array();
1385   $last_pos = 0;
1386   
1387   // ignore the whole block if evil styles are detected
1388   if (stristr($source, 'expression') || stristr($source, 'behavior'))
1389     return '';
1390
1391   // cut out all contents between { and }
1392   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1393   {
1394     $key = sizeof($a_css_values);
1395     $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1396     $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1397     $last_pos = $pos+2;
1398   }
1399
1400   // remove html comments and add #container to each tag selector.
1401   // also replace body definition because we also stripped off the <body> tag
1402   $styles = preg_replace(
1403     array(
1404       '/(^\s*<!--)|(-->\s*$)/',
1405       '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1406       '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
1407       '/<<str_replacement\[([0-9]+)\]>>/e',
1408       "/$container_id\s+body/i"
1409     ),
1410     array(
1411       '',
1412       "\\1#$container_id \\2",
1413       "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
1414       "\$a_css_values[\\1]",
1415       "$container_id div.rcmBody"
1416     ),
1417     $source);
1418
1419   return $styles;
1420   }
1421
1422 /**
1423  * Try to autodetect operating system and find the correct line endings
1424  *
1425  * @return string The appropriate mail header delimiter
1426  */
1427 function rcmail_header_delm()
1428 {
1429   global $CONFIG;
1430   
1431   // use the configured delimiter for headers
1432   if (!empty($CONFIG['mail_header_delimiter']))
1433     return $CONFIG['mail_header_delimiter'];
1434   else if (strtolower(substr(PHP_OS, 0, 3)=='win')) 
1435     return "\r\n";
1436   else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
1437     return "\r\n";
1438   else    
1439     return "\n";
1440 }
1441
1442
1443 /**
1444  * Compose a valid attribute string for HTML tags
1445  *
1446  * @param array Named tag attributes
1447  * @param array List of allowed attributes
1448  * @return string HTML formatted attribute string
1449  */
1450 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1451   {
1452   // allow the following attributes to be added to the <iframe> tag
1453   $attrib_str = '';
1454   foreach ($allowed_attribs as $a)
1455     if (isset($attrib[$a]))
1456       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
1457
1458   return $attrib_str;
1459   }
1460
1461
1462 /**
1463  * Convert a HTML attribute string attributes to an associative array (name => value)
1464  *
1465  * @param string Input string
1466  * @return array Key-value pairs of parsed attributes
1467  */
1468 function parse_attrib_string($str)
1469   {
1470   $attrib = array();
1471   preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1472
1473   // convert attributes to an associative array (name => value)
1474   if ($regs)
1475     foreach ($regs as $attr)
1476       $attrib[strtolower($attr[1])] = $attr[3];
1477
1478   return $attrib;
1479   }
1480
1481
1482 /**
1483  * Convert the given date to a human readable form
1484  * This uses the date formatting properties from config
1485  *
1486  * @param mixed Date representation (string or timestamp)
1487  * @param string Date format to use
1488  * @return string Formatted date string
1489  */
1490 function format_date($date, $format=NULL)
1491   {
1492   global $CONFIG, $sess_user_lang;
1493   
1494   $ts = NULL;
1495   
1496   if (is_numeric($date))
1497     $ts = $date;
1498   else if (!empty($date))
1499     $ts = @strtotime($date);
1500     
1501   if (empty($ts))
1502     return '';
1503    
1504   // get user's timezone
1505   $tz = $CONFIG['timezone'];
1506   if ($CONFIG['dst_active'])
1507     $tz++;
1508
1509   // convert time to user's timezone
1510   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1511   
1512   // get current timestamp in user's timezone
1513   $now = time();  // local time
1514   $now -= (int)date('Z'); // make GMT time
1515   $now += ($tz * 3600); // user's time
1516   $now_date = getdate($now);
1517
1518   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1519   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1520
1521   // define date format depending on current time  
1522   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1523     return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1524   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1525     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1526   else if (!$format)
1527     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1528
1529
1530   // parse format string manually in order to provide localized weekday and month names
1531   // an alternative would be to convert the date() format string to fit with strftime()
1532   $out = '';
1533   for($i=0; $i<strlen($format); $i++)
1534     {
1535     if ($format{$i}=='\\')  // skip escape chars
1536       continue;
1537     
1538     // write char "as-is"
1539     if ($format{$i}==' ' || $format{$i-1}=='\\')
1540       $out .= $format{$i};
1541     // weekday (short)
1542     else if ($format{$i}=='D')
1543       $out .= rcube_label(strtolower(date('D', $timestamp)));
1544     // weekday long
1545     else if ($format{$i}=='l')
1546       $out .= rcube_label(strtolower(date('l', $timestamp)));
1547     // month name (short)
1548     else if ($format{$i}=='M')
1549       $out .= rcube_label(strtolower(date('M', $timestamp)));
1550     // month name (long)
1551     else if ($format{$i}=='F')
1552       $out .= rcube_label(strtolower(date('F', $timestamp)));
1553     else
1554       $out .= date($format{$i}, $timestamp);
1555     }
1556   
1557   return $out;
1558   }
1559
1560
1561 /**
1562  * Compose a valid representaion of name and e-mail address
1563  *
1564  * @param string E-mail address
1565  * @param string Person name
1566  * @return string Formatted string
1567  */
1568 function format_email_recipient($email, $name='')
1569   {
1570   if ($name && $name != $email)
1571     {
1572     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
1573     return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
1574     }
1575   else
1576     return $email;
1577   }
1578
1579
1580
1581 /****** debugging functions ********/
1582
1583
1584 /**
1585  * Print or write debug messages
1586  *
1587  * @param mixed Debug message or data
1588  */
1589 function console($msg)
1590   {
1591   if (!is_string($msg))
1592     $msg = var_export($msg, true);
1593
1594   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1595     write_log('console', $msg);
1596   else if ($GLOBALS['REMOTE_REQUEST'])
1597     print "/*\n $msg \n*/\n";
1598   else
1599     {
1600     print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1601     print $msg;
1602     print "</pre></div>\n";
1603     }
1604   }
1605
1606
1607 /**
1608  * Append a line to a logfile in the logs directory.
1609  * Date will be added automatically to the line.
1610  *
1611  * @param $name Name of logfile
1612  * @param $line Line to append
1613  */
1614 function write_log($name, $line)
1615   {
1616   global $CONFIG, $INSTALL_PATH;
1617
1618   if (!is_string($line))
1619     $line = var_export($line, true);
1620   
1621   $log_entry = sprintf("[%s]: %s\n",
1622                  date("d-M-Y H:i:s O", mktime()),
1623                  $line);
1624                  
1625   if (empty($CONFIG['log_dir']))
1626     $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1627       
1628   // try to open specific log file for writing
1629   if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))    
1630     {
1631     fwrite($fp, $log_entry);
1632     fclose($fp);
1633     }
1634   }
1635
1636
1637 /**
1638  * @access private
1639  */
1640 function rcube_timer()
1641   {
1642   list($usec, $sec) = explode(" ", microtime());
1643   return ((float)$usec + (float)$sec);
1644   }
1645   
1646
1647 /**
1648  * @access private
1649  */
1650 function rcube_print_time($timer, $label='Timer')
1651   {
1652   static $print_count = 0;
1653   
1654   $print_count++;
1655   $now = rcube_timer();
1656   $diff = $now-$timer;
1657   
1658   if (empty($label))
1659     $label = 'Timer '.$print_count;
1660   
1661   console(sprintf("%s: %0.4f sec", $label, $diff));
1662   }
1663
1664
1665 /**
1666  * Return the mailboxlist in HTML
1667  *
1668  * @param array Named parameters
1669  * @return string HTML code for the gui object
1670  */
1671 function rcmail_mailbox_list($attrib)
1672   {
1673   global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1674   static $s_added_script = FALSE;
1675   static $a_mailboxes;
1676
1677   // add some labels to client
1678   rcube_add_label('purgefolderconfirm');
1679   rcube_add_label('deletemessagesconfirm');
1680   
1681 // $mboxlist_start = rcube_timer();
1682   
1683   $type = $attrib['type'] ? $attrib['type'] : 'ul';
1684   $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1685                                   array('style', 'class', 'id');
1686                                   
1687   if ($type=='ul' && !$attrib['id'])
1688     $attrib['id'] = 'rcmboxlist';
1689
1690   // allow the following attributes to be added to the <ul> tag
1691   $attrib_str = create_attrib_string($attrib, $add_attrib);
1692  
1693   $out = '<' . $type . $attrib_str . ">\n";
1694   
1695   // add no-selection option
1696   if ($type=='select' && $attrib['noselection'])
1697     $out .= sprintf('<option value="0">%s</option>'."\n",
1698                     rcube_label($attrib['noselection']));
1699   
1700   // get mailbox list
1701   $mbox_name = $IMAP->get_mailbox_name();
1702   
1703   // build the folders tree
1704   if (empty($a_mailboxes))
1705     {
1706     // get mailbox list
1707     $a_folders = $IMAP->list_mailboxes();
1708     $delimiter = $IMAP->get_hierarchy_delimiter();
1709     $a_mailboxes = array();
1710
1711 // rcube_print_time($mboxlist_start, 'list_mailboxes()');
1712
1713     foreach ($a_folders as $folder)
1714       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1715     }
1716
1717 // var_dump($a_mailboxes);
1718
1719   if ($type=='select')
1720     $out .= rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength']);
1721    else
1722     $out .= rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $attrib['maxlength']);
1723
1724 // rcube_print_time($mboxlist_start, 'render_folder_tree()');
1725
1726
1727   if ($type=='ul')
1728     $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1729
1730   return $out . "</$type>";
1731   }
1732
1733
1734
1735
1736 /**
1737  * Create a hierarchical array of the mailbox list
1738  * @access private
1739  */
1740 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1741   {
1742   $pos = strpos($folder, $delm);
1743   if ($pos !== false)
1744     {
1745     $subFolders = substr($folder, $pos+1);
1746     $currentFolder = substr($folder, 0, $pos);
1747     }
1748   else
1749     {
1750     $subFolders = false;
1751     $currentFolder = $folder;
1752     }
1753
1754   $path .= $currentFolder;
1755
1756   if (!isset($arrFolders[$currentFolder]))
1757     {
1758     $arrFolders[$currentFolder] = array('id' => $path,
1759                                         'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1760                                         'folders' => array());
1761     }
1762
1763   if (!empty($subFolders))
1764     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1765   }
1766   
1767
1768 /**
1769  * Return html for a structured list &lt;ul&gt; for the mailbox tree
1770  * @access private
1771  */
1772 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1773   {
1774   global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1775
1776   $idx = 0;
1777   $out = '';
1778   foreach ($arrFolders as $key => $folder)
1779     {
1780     $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1781     $title = '';
1782
1783     if ($folder_class = rcmail_folder_classname($folder['id']))
1784       $foldername = rcube_label($folder_class);
1785     else
1786       {
1787       $foldername = $folder['name'];
1788
1789       // shorten the folder name to a given length
1790       if ($maxlength && $maxlength>1)
1791         {
1792         $fname = abbreviate_string($foldername, $maxlength);
1793         if ($fname != $foldername)
1794           $title = ' title="'.Q($foldername).'"';
1795         $foldername = $fname;
1796         }
1797       }
1798
1799     // make folder name safe for ids and class names
1800     $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1801     $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_class ? $folder_class : strtolower($folder['id']));
1802
1803     // set special class for Sent, Drafts, Trash and Junk
1804     if ($folder['id']==$CONFIG['sent_mbox'])
1805       $class_name = 'sent';
1806     else if ($folder['id']==$CONFIG['drafts_mbox'])
1807       $class_name = 'drafts';
1808     else if ($folder['id']==$CONFIG['trash_mbox'])
1809       $class_name = 'trash';
1810     else if ($folder['id']==$CONFIG['junk_mbox'])
1811       $class_name = 'junk';
1812
1813     $js_name = htmlspecialchars(JQ($folder['id']));
1814     $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1815                     ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1816                     ' onmouseover="return %s.focus_folder(\'%s\')"' .
1817                     ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1818                     ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1819                     $folder_id,
1820                     $class_name,
1821                     $zebra_class,
1822                     $unread_count ? ' unread' : '',
1823                     $folder['id']==$mbox_name ? ' selected' : '',
1824                     Q(rcmail_url('', array('_mbox' => $folder['id']))),
1825                     JS_OBJECT_NAME,
1826                     $js_name,
1827                     JS_OBJECT_NAME,
1828                     $js_name,
1829                     JS_OBJECT_NAME,
1830                     $js_name,
1831                     JS_OBJECT_NAME,
1832                     $js_name,
1833                     $title,
1834                     Q($foldername));
1835
1836     if (!empty($folder['folders']))
1837       $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1838
1839     $out .= "</li>\n";
1840     $idx++;
1841     }
1842
1843   return $out;
1844   }
1845
1846
1847 /**
1848  * Return html for a flat list <select> for the mailbox tree
1849  * @access private
1850  */
1851 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1852   {
1853   global $IMAP, $OUTPUT;
1854
1855   $idx = 0;
1856   $out = '';
1857   foreach ($arrFolders as $key=>$folder)
1858     {
1859     if ($folder_class = rcmail_folder_classname($folder['id']))
1860       $foldername = rcube_label($folder_class);
1861     else
1862       {
1863       $foldername = $folder['name'];
1864       
1865       // shorten the folder name to a given length
1866       if ($maxlength && $maxlength>1)
1867         $foldername = abbreviate_string($foldername, $maxlength);
1868       }
1869
1870     $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1871                     htmlspecialchars($folder['id']),
1872                     str_repeat('&nbsp;', $nestLevel*4),
1873                     Q($foldername));
1874
1875     if (!empty($folder['folders']))
1876       $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $nestLevel+1);
1877
1878     $idx++;
1879     }
1880
1881   return $out;
1882   }
1883
1884
1885 /**
1886  * Return internal name for the given folder if it matches the configured special folders
1887  * @access private
1888  */
1889 function rcmail_folder_classname($folder_id)
1890 {
1891   global $CONFIG;
1892
1893   $cname = null;
1894   $folder_lc = strtolower($folder_id);
1895   
1896   // for these mailboxes we have localized labels and css classes
1897   foreach (array('inbox', 'sent', 'drafts', 'trash', 'junk') as $smbx)
1898   {
1899     if ($folder_lc == $smbx || $folder_id == $CONFIG[$smbx.'_mbox'])
1900       $cname = $smbx;
1901   }
1902   
1903   return $cname;
1904 }
1905
1906
1907 /**
1908  * Try to localize the given IMAP folder name.
1909  * UTF-7 decode it in case no localized text was found
1910  *
1911  * @param string Folder name
1912  * @return string Localized folder name in UTF-8 encoding
1913  */
1914 function rcmail_localize_foldername($name)
1915 {
1916   if ($folder_class = rcmail_folder_classname($name))
1917     return rcube_label($folder_class);
1918   else
1919     return rcube_charset_convert($name, 'UTF-7');
1920 }
1921
1922
1923 ?>