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