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