yllar
2006-12-11 df8e8ec9eee72743d0f14a8409aacf66c4a80d89
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/main.inc                                              |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005, RoundCube Dev, - Switzerland                      |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 11  | PURPOSE:                                                              |
12  |   Provide basic functions for the webmail package                     |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id$
19
20 */
21
22 require_once('lib/des.inc');
0af7e8 23 require_once('lib/utf7.inc');
83dbb7 24 require_once('lib/utf8.class.php');
4e17e6 25
T 26
ea7c46 27 // define constannts for input reading
T 28 define('RCUBE_INPUT_GET', 0x0101);
29 define('RCUBE_INPUT_POST', 0x0102);
30 define('RCUBE_INPUT_GPC', 0x0103);
31
32
4e17e6 33 // register session and connect to server
T 34 function rcmail_startup($task='mail')
35   {
36   global $sess_id, $sess_auth, $sess_user_lang;
37   global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
38
39   // check client
40   $BROWSER = rcube_browser();
de2e1e 41
e170b4 42   // load configuration
T 43   $CONFIG = rcmail_load_config();
bac7d1 44
7902df 45   // set session garbage collecting time according to session_lifetime
T 46   if (!empty($CONFIG['session_lifetime']))
e170b4 47     ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
4e17e6 48
T 49   // prepare DB connection
f45ec7 50   require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
S 51   
8c2e58 52   $DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
42b113 53   $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
8affba 54   $DB->db_connect('w');
e170b4 55
4e17e6 56   // we can use the database for storing session data
d2a9db 57   if (!$DB->is_error())
4e17e6 58     include_once('include/session.inc');
T 59
60   // init session
61   session_start();
62   $sess_id = session_id();
de8c61 63
4e17e6 64   // create session and set session vars
bac7d1 65   if (!isset($_SESSION['auth_time']))
4e17e6 66     {
0af7e8 67     $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
4e17e6 68     $_SESSION['auth_time'] = mktime();
bac7d1 69     setcookie('sessauth', rcmail_auth_hash($sess_id, $_SESSION['auth_time']));
4e17e6 70     }
T 71
72   // set session vars global
0af7e8 73   $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
4e17e6 74
T 75
76   // overwrite config with user preferences
77   if (is_array($_SESSION['user_prefs']))
78     $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
79
80
81   // reset some session parameters when changing task
82   if ($_SESSION['task'] != $task)
83     unset($_SESSION['page']);
84
85   // set current task to session
86   $_SESSION['task'] = $task;
87
88   // create IMAP object
89   if ($task=='mail')
90     rcmail_imap_init();
91
92
93   // set localization
94   if ($CONFIG['locale_string'])
95     setlocale(LC_ALL, $CONFIG['locale_string']);
96   else if ($sess_user_lang)
97     setlocale(LC_ALL, $sess_user_lang);
98
99
100   register_shutdown_function('rcmail_shutdown');
101   }
9606ff 102
T 103
e170b4 104 // load roundcube configuration into global var
T 105 function rcmail_load_config()
106   {
107     global $INSTALL_PATH;
108
109   // load config file
110     include_once('config/main.inc.php');
111     $conf = is_array($rcmail_config) ? $rcmail_config : array();
112
113   // load host-specific configuration
114   rcmail_load_host_config($conf);
115
116   $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
117
118   // load db conf
119   include_once('config/db.inc.php');
120   $conf = array_merge($conf, $rcmail_config);
121
122   if (empty($conf['log_dir']))
123     $conf['log_dir'] = $INSTALL_PATH.'logs';
124   else
125     $conf['log_dir'] = unslashify($conf['log_dir']);
126
127   // set PHP error logging according to config
128   if ($conf['debug_level'] & 1)
129     {
130     ini_set('log_errors', 1);
131     ini_set('error_log', $conf['log_dir'].'/errors');
132     }
133   if ($conf['debug_level'] & 4)
134     ini_set('display_errors', 1);
135   else
136     ini_set('display_errors', 0);
137
138   return $conf;
139   }
140
141
9606ff 142 // load a host-specific config file if configured
T 143 function rcmail_load_host_config(&$config)
144   {
145   $fname = NULL;
146   
147   if (is_array($config['include_host_config']))
148     $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
149   else if (!empty($config['include_host_config']))
150     $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
151
152    if ($fname && is_file('config/'.$fname))
153      {
154      include('config/'.$fname);
155      $config = array_merge($config, $rcmail_config);
156      }
157   }
bac7d1 158
4e17e6 159
T 160 // create authorization hash
161 function rcmail_auth_hash($sess_id, $ts)
162   {
163   global $CONFIG;
164   
165   $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
166                          $sess_id,
167                          $ts,
168                          $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
169                          $_SERVER['HTTP_USER_AGENT']);
170   
171   if (function_exists('sha1'))
172     return sha1($auth_string);
173   else
174     return md5($auth_string);
175   }
176
bac7d1 177
T 178 // compare the auth hash sent by the client with the local session credentials
179 function rcmail_authenticate_session()
180   {
181   $now = mktime();
e170b4 182   $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
T 183                         $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
aade7b 184
T 185   // renew auth cookie every 5 minutes (only for GET requests)
186   if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
bac7d1 187     {
7139e3 188     $_SESSION['last_auth'] = $_SESSION['auth_time'];
bac7d1 189     $_SESSION['auth_time'] = $now;
T 190     setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
191     }
e170b4 192
T 193   if (!$valid)
194     write_log('timeouts',
195       "REQUEST: " . var_export($_REQUEST, true) .
196       "\nEXPECTED: " . rcmail_auth_hash(session_id(), $_SESSION['auth_time']) .
197       "\nOR LAST: " . rcmail_auth_hash(session_id(), $_SESSION['last_auth']) .
198       "\nSESSION: " . var_export($_SESSION, true));
199
bac7d1 200   return $valid;
T 201   }
4e17e6 202
T 203
204 // create IMAP object and connect to server
205 function rcmail_imap_init($connect=FALSE)
206   {
1cded8 207   global $CONFIG, $DB, $IMAP;
6dc026 208
1cded8 209   $IMAP = new rcube_imap($DB);
15a9d1 210   $IMAP->debug_level = $CONFIG['debug_level'];
T 211   $IMAP->skip_deleted = $CONFIG['skip_deleted'];
212
4e17e6 213
7902df 214   // connect with stored session data
T 215   if ($connect)
216     {
217     if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
218       show_message('imaperror', 'error');
219       
220     rcmail_set_imap_prop();
221     }
222
6dc026 223   // enable caching of imap data
T 224   if ($CONFIG['enable_caching']===TRUE)
225     $IMAP->set_caching(TRUE);
226
4e17e6 227   // set pagesize from config
T 228   if (isset($CONFIG['pagesize']))
229     $IMAP->set_pagesize($CONFIG['pagesize']);
7902df 230   }
4e17e6 231
T 232
7902df 233 // set root dir and last stored mailbox
T 234 // this must be done AFTER connecting to the server
235 function rcmail_set_imap_prop()
236   {
237   global $CONFIG, $IMAP;
238
239   // set root dir from config
620439 240   if (!empty($CONFIG['imap_root']))
7902df 241     $IMAP->set_rootdir($CONFIG['imap_root']);
fa4cd2 242
T 243   if (is_array($CONFIG['default_imap_folders']))
244     $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
7902df 245
620439 246   if (!empty($_SESSION['mbox']))
7902df 247     $IMAP->set_mailbox($_SESSION['mbox']);
T 248   if (isset($_SESSION['page']))
249     $IMAP->set_page($_SESSION['page']);
4e17e6 250   }
T 251
252
253 // do these things on script shutdown
254 function rcmail_shutdown()
255   {
256   global $IMAP;
257   
258   if (is_object($IMAP))
259     {
260     $IMAP->close();
261     $IMAP->write_cache();
262     }
0af7e8 263     
T 264   // before closing the database connection, write session data
265   session_write_close();
4e17e6 266   }
T 267
268
269 // destroy session data and remove cookie
270 function rcmail_kill_session()
271   {
86f172 272   // save user preferences
T 273   $a_user_prefs = $_SESSION['user_prefs'];
274   if (!is_array($a_user_prefs))
275     $a_user_prefs = array();
276     
277   if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
278       (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
279     {
280     $a_user_prefs['message_sort_col'] = $_SESSION['sort_col'];
281     $a_user_prefs['message_sort_order'] = $_SESSION['sort_order'];
282     rcmail_save_user_prefs($a_user_prefs);
283     }
284
4e17e6 285   $_SESSION = array();
T 286   session_destroy();
287   }
288
289
290 // return correct name for a specific database table
291 function get_table_name($table)
292   {
293   global $CONFIG;
294   
295   // return table name if configured
296   $config_key = 'db_table_'.$table;
297
298   if (strlen($CONFIG[$config_key]))
299     return $CONFIG[$config_key];
300   
301   return $table;
302   }
303
304
1cded8 305 // return correct name for a specific database sequence
T 306 // (used for Postres only)
307 function get_sequence_name($sequence)
308   {
309   global $CONFIG;
310   
311   // return table name if configured
312   $config_key = 'db_sequence_'.$sequence;
313
314   if (strlen($CONFIG[$config_key]))
315     return $CONFIG[$config_key];
316   
317   return $table;
318   }
0af7e8 319
T 320
321 // check the given string and returns language properties
322 function rcube_language_prop($lang, $prop='lang')
323   {
c8c1e0 324   global $INSTALL_PATH;
0af7e8 325   static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
T 326
327   if (empty($rcube_languages))
c8c1e0 328     @include($INSTALL_PATH.'program/localization/index.inc');
0af7e8 329     
T 330   // check if we have an alias for that language
331   if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
332     $lang = $rcube_language_aliases[$lang];
333     
334   // try the first two chars
f88d41 335   if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
0af7e8 336     {
T 337     $lang = substr($lang, 0, 2);
338     $lang = rcube_language_prop($lang);
339     }
340
341   if (!isset($rcube_languages[$lang]))
342     $lang = 'en_US';
343
344   // language has special charset configured
345   if (isset($rcube_charsets[$lang]))
346     $charset = $rcube_charsets[$lang];
347   else
348     $charset = 'UTF-8';    
f88d41 349
0af7e8 350
T 351   if ($prop=='charset')
352     return $charset;
353   else
354     return $lang;
355   }
1cded8 356   
4e17e6 357
T 358 // init output object for GUI and add common scripts
359 function load_gui()
360   {
3f9edb 361   global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
4e17e6 362
T 363   // init output page
364   $OUTPUT = new rcube_html_page();
365   
366   // add common javascripts
367   $javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
6b47de 368   $javascript .= sprintf("%s.set_env('comm_path', '%s');\n", $JS_OBJECT_NAME, str_replace('&amp;', '&', $COMM_PATH));
4e17e6 369
97a915 370   if (isset($CONFIG['javascript_config'] )){
S 371     foreach ($CONFIG['javascript_config'] as $js_config_var){
372       $javascript .= "$JS_OBJECT_NAME.set_env('$js_config_var', '" . $CONFIG[$js_config_var] . "');\n";
373     }
de8c61 374   }
e170b4 375
T 376   // don't wait for page onload. Call init at the bottom of the page (delayed)
377   $javascript_foot = "if (window.call_init)\n call_init('$JS_OBJECT_NAME');";
a0109c 378
597170 379   if (!empty($GLOBALS['_framed']))
4e17e6 380     $javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
7cc38e 381     
e170b4 382   $OUTPUT->add_script($javascript, 'head');
T 383   $OUTPUT->add_script($javascript_foot, 'foot');
dd53e2 384   $OUTPUT->include_script('common.js');
T 385   $OUTPUT->include_script('app.js');
386   $OUTPUT->scripts_path = 'program/js/';
7cc38e 387
13c1af 388   // set locale setting
T 389   rcmail_set_locale($sess_user_lang);
390
7cc38e 391   // set user-selected charset
5bc8cb 392   if (!empty($CONFIG['charset']))
7cc38e 393     $OUTPUT->set_charset($CONFIG['charset']);
0af7e8 394
10a699 395   // add some basic label to client
c8c1e0 396   rcube_add_label('loading','checkingmail');
0af7e8 397   }
7cc38e 398
T 399
400 // set localization charset based on the given language
401 function rcmail_set_locale($lang)
402   {
5f56a5 403   global $OUTPUT, $MBSTRING;
f88d41 404   static $s_mbstring_loaded = NULL;
T 405   
406   // settings for mbstring module (by Tadashi Jokagi)
5f56a5 407   if (is_null($s_mbstring_loaded))
T 408     $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring");
409   else
410     $MBSTRING = $s_mbstring_loaded = FALSE;
f88d41 411
3f9edb 412   $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
7cc38e 413   }
4e17e6 414
T 415
0a020c 416 // auto-select IMAP host based on the posted login information
T 417 function rcmail_autoselect_host()
418   {
419   global $CONFIG;
420   
421   $host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
422   if (is_array($host))
423     {
424     list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
425     if (!empty($domain))
426       {
427       foreach ($host as $imap_host => $mail_domains)
428         if (is_array($mail_domains) && in_array($domain, $mail_domains))
429           {
430           $host = $imap_host;
431           break;
432           }
433       }
434
435     // take the first entry if $host is still an array
436     if (is_array($host))
437       $host = array_shift($host);
438     }
439   
440   return $host;
441   }
442
443
4e17e6 444 // perfom login to the IMAP server and to the webmail service
T 445 function rcmail_login($user, $pass, $host=NULL)
446   {
447   global $CONFIG, $IMAP, $DB, $sess_user_lang;
42b113 448   $user_id = NULL;
4e17e6 449   
T 450   if (!$host)
451     $host = $CONFIG['default_host'];
452
f619de 453   // parse $host URL
T 454   $a_host = parse_url($host);
455   if ($a_host['host'])
456     {
457     $host = $a_host['host'];
458     $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
459     $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
460     }
ea7c46 461   else
T 462     $imap_port = $CONFIG['default_port'];
f619de 463
026d68 464
T 465   /* Modify username with domain if required  
466      Inspired by Marco <P0L0_notspam_binware.org>
467   */
468   // Check if we need to add domain
996066 469   if (!empty($CONFIG['username_domain']) && !strstr($user, '@'))
026d68 470     {
T 471     if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
472       $user .= '@'.$CONFIG['username_domain'][$host];
996066 473     else if (is_string($CONFIG['username_domain']))
T 474       $user .= '@'.$CONFIG['username_domain'];
026d68 475     }
T 476
477
4e17e6 478   // query if user already registered
d7cb77 479   $sql_result = $DB->query("SELECT user_id, username, language, preferences
S 480                             FROM ".get_table_name('users')."
481                             WHERE  mail_host=? AND (username=? OR alias=?)",
482                             $host,
483                             $user,
484                             $user);
4e17e6 485
42b113 486   // user already registered -> overwrite username
4e17e6 487   if ($sql_arr = $DB->fetch_assoc($sql_result))
T 488     {
489     $user_id = $sql_arr['user_id'];
42b113 490     $user = $sql_arr['username'];
T 491     }
492
977a29 493   // try to resolve email address from virtuser table    
T 494   if (!empty($CONFIG['virtuser_file']) && strstr($user, '@'))
495     $user = rcmail_email2user($user);
496
497
42b113 498   // exit if IMAP login failed
T 499   if (!($imap_login  = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
500     return FALSE;
501
502   // user already registered
503   if ($user_id && !empty($sql_arr))
504     {
4e17e6 505     // get user prefs
T 506     if (strlen($sql_arr['preferences']))
507       {
508       $user_prefs = unserialize($sql_arr['preferences']);
509       $_SESSION['user_prefs'] = $user_prefs;
510       array_merge($CONFIG, $user_prefs);
511       }
512
f3b659 513
4e17e6 514     // set user specific language
T 515     if (strlen($sql_arr['language']))
516       $sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
f3b659 517       
4e17e6 518     // update user's record
d7cb77 519     $DB->query("UPDATE ".get_table_name('users')."
107bde 520                 SET    last_login=".$DB->now()."
d7cb77 521                 WHERE  user_id=?",
S 522                 $user_id);
4e17e6 523     }
T 524   // create new system user
525   else if ($CONFIG['auto_create_user'])
526     {
527     $user_id = rcmail_create_user($user, $host);
528     }
529
530   if ($user_id)
531     {
532     $_SESSION['user_id']   = $user_id;
533     $_SESSION['imap_host'] = $host;
7902df 534     $_SESSION['imap_port'] = $imap_port;
T 535     $_SESSION['imap_ssl']  = $imap_ssl;
4e17e6 536     $_SESSION['username']  = $user;
f3b659 537     $_SESSION['user_lang'] = $sess_user_lang;
4e17e6 538     $_SESSION['password']  = encrypt_passwd($pass);
T 539
fa4cd2 540     // force reloading complete list of subscribed mailboxes
T 541     rcmail_set_imap_prop();
4e17e6 542     $IMAP->clear_cache('mailboxes');
fa4cd2 543     $IMAP->create_default_folders();
4e17e6 544
T 545     return TRUE;
546     }
547
548   return FALSE;
549   }
550
551
552 // create new entry in users and identities table
553 function rcmail_create_user($user, $host)
554   {
555   global $DB, $CONFIG, $IMAP;
977a29 556
T 557   $user_email = '';
558
559   // try to resolve user in virtusertable
560   if (!empty($CONFIG['virtuser_file']) && strstr($user, '@')==FALSE)
561     $user_email = rcmail_user2email($user);
562
d7cb77 563   $DB->query("INSERT INTO ".get_table_name('users')."
977a29 564               (created, last_login, username, mail_host, alias, language)
107bde 565               VALUES (".$DB->now().", ".$DB->now().", ?, ?, ?, ?)",
d7cb77 566               $user,
S 567               $host,
977a29 568               $user_email,
d7cb77 569               $_SESSION['user_lang']);
4e17e6 570
1cded8 571   if ($user_id = $DB->insert_id(get_sequence_name('users')))
4e17e6 572     {
8cb245 573     $mail_domain = rcmail_mail_domain($host);
977a29 574    
T 575     if ($user_email=='')
576       $user_email = strstr($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
577
52c1f2 578     $user_name = $user!=$user_email ? $user : '';
977a29 579
f88d41 580     // try to resolve the e-mail address from the virtuser table
e61145 581     if (!empty($CONFIG['virtuser_query']) &&
S 582         ($sql_result = $DB->query(preg_replace('/%u/', $user, $CONFIG['virtuser_query']))) &&
583         ($DB->num_rows()>0))
584       while ($sql_arr = $DB->fetch_array($sql_result))
585         {
586         $DB->query("INSERT INTO ".get_table_name('identities')."
587                    (user_id, del, standard, name, email)
588                    VALUES (?, 0, 1, ?, ?)",
589                    $user_id,
590                    $user_name,
591                    preg_replace('/^@/', $user . '@', $sql_arr[0]));
592         }
593     else
594       {
595       // also create new identity records
596       $DB->query("INSERT INTO ".get_table_name('identities')."
597                   (user_id, del, standard, name, email)
598                   VALUES (?, 0, 1, ?, ?)",
599                   $user_id,
600                   $user_name,
601                   $user_email);
f88d41 602       }
4e17e6 603                        
T 604     // get existing mailboxes
605     $a_mailboxes = $IMAP->list_mailboxes();
42b113 606     }
T 607   else
608     {
609     raise_error(array('code' => 500,
610                       'type' => 'php',
611                       'line' => __LINE__,
612                       'file' => __FILE__,
613                       'message' => "Failed to create new user"), TRUE, FALSE);
4e17e6 614     }
T 615     
616   return $user_id;
617   }
618
619
977a29 620 // load virtuser table in array
T 621 function rcmail_getvirtualfile()
622   {
623   global $CONFIG;
624   if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
625     return FALSE;
626   
627   // read file 
628   $a_lines = file($CONFIG['virtuser_file']);
629   return $a_lines;
630   }
631
632
633 // find matches of the given pattern in virtuser table
634 function rcmail_findinvirtual($pattern)
635   {
636   $result = array();
637   $virtual = rcmail_getvirtualfile();
638   if ($virtual==FALSE)
639     return $result;
640
641   // check each line for matches
642   foreach ($virtual as $line)
643     {
644     $line = trim($line);
645     if (empty($line) || $line{0}=='#')
646       continue;
647       
648     if (eregi($pattern, $line))
649       $result[] = $line;
650     }
651
652   return $result;
653   }
654
655
656 // resolve username with virtuser table
657 function rcmail_email2user($email)
658   {
659   $user = $email;
660   $r = rcmail_findinvirtual("^$email");
661
662   for ($i=0; $i<count($r); $i++)
663     {
664     $data = $r[$i];
665     $arr = preg_split('/\s+/', $data);
666     if(count($arr)>0)
667       {
668       $user = trim($arr[count($arr)-1]);
669       break;
670       }
671     }
672
673   return $user;
674   }
675
676
677 // resolve e-mail address with virtuser table
678 function rcmail_user2email($user)
679   {
680   $email = "";
681   $r = rcmail_findinvirtual("$user$");
682
683   for ($i=0; $i<count($r); $i++)
684     {
685     $data=$r[$i];
686     $arr = preg_split('/\s+/', $data);
687     if (count($arr)>0)
688       {
689       $email = trim($arr[0]);
690       break;
691       }
692     }
693
694   return $email;
695   } 
696
697
86f172 698 function rcmail_save_user_prefs($a_user_prefs)
T 699   {
700   global $DB, $CONFIG, $sess_user_lang;
701   
702   $DB->query("UPDATE ".get_table_name('users')."
703               SET    preferences=?,
704                      language=?
705               WHERE  user_id=?",
706               serialize($a_user_prefs),
707               $sess_user_lang,
708               $_SESSION['user_id']);
709
710   if ($DB->affected_rows())
711     {
712     $_SESSION['user_prefs'] = $a_user_prefs;  
713     $CONFIG = array_merge($CONFIG, $a_user_prefs);
714     return TRUE;
715     }
716     
717   return FALSE;
718   }
719
720
10a699 721 // overwrite action variable  
T 722 function rcmail_overwrite_action($action)
723   {
724   global $OUTPUT, $JS_OBJECT_NAME;
725   $GLOBALS['_action'] = $action;
726
727   $OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $action));  
728   }
729
730
4647e1 731 function show_message($message, $type='notice', $vars=NULL)
4e17e6 732   {
T 733   global $OUTPUT, $JS_OBJECT_NAME, $REMOTE_REQUEST;
4647e1 734   
597170 735   $framed = $GLOBALS['_framed'];
4e17e6 736   $command = sprintf("display_message('%s', '%s');",
c39957 737                      rep_specialchars_output(rcube_label(array('name' => $message, 'vars' => $vars)), 'js'),
4e17e6 738                      $type);
T 739                      
740   if ($REMOTE_REQUEST)
741     return 'this.'.$command;
742   
743   else
41fa0b 744     $OUTPUT->add_script(sprintf("%s%s.%s\n",
4e17e6 745                                 $framed ? sprintf('if(parent.%s)parent.', $JS_OBJECT_NAME) : '',
T 746                                 $JS_OBJECT_NAME,
747                                 $command));
748   }
749
750
bac7d1 751 // encrypt IMAP password using DES encryption
4e17e6 752 function encrypt_passwd($pass)
T 753   {
bac7d1 754   $cypher = des(get_des_key(), $pass, 1, 0, NULL);
4e17e6 755   return base64_encode($cypher);
T 756   }
757
758
bac7d1 759 // decrypt IMAP password using DES encryption
4e17e6 760 function decrypt_passwd($cypher)
T 761   {
bac7d1 762   $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
T 763   return preg_replace('/\x00/', '', $pass);
764   }
765
766
767 // return a 24 byte key for the DES encryption
768 function get_des_key()
769   {
770   $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
771   $len = strlen($key);
772   
773   // make sure the key is exactly 24 chars long
774   if ($len<24)
775     $key .= str_repeat('_', 24-$len);
776   else if ($len>24)
777     substr($key, 0, 24);
778   
779   return $key;
4e17e6 780   }
T 781
782
783 // send correct response on a remote request
15a9d1 784 function rcube_remote_response($js_code, $flush=FALSE)
4e17e6 785   {
13c1af 786   global $OUTPUT, $CHARSET;
15a9d1 787   static $s_header_sent = FALSE;
T 788   
789   if (!$s_header_sent)
790     {
791     $s_header_sent = TRUE;
792     send_nocacheing_headers();
ded2b7 793     header('Content-Type: application/x-javascript; charset='.$CHARSET);
15a9d1 794     print '/** remote response ['.date('d/M/Y h:i:s O')."] **/\n";
T 795     }
4e17e6 796
15a9d1 797   // send response code
13c1af 798   print rcube_charset_convert($js_code, $CHARSET, $OUTPUT->get_charset());
15a9d1 799
T 800   if ($flush)  // flush the output buffer
801     flush();
802   else         // terminate script
803     exit;
4e17e6 804   }
T 805
806
41fa0b 807 // send correctly formatted response for a request posted to an iframe
T 808 function rcube_iframe_response($js_code='')
809   {
810   global $OUTPUT, $JS_OBJECT_NAME;
811
812   if (!empty($js_code))
813     $OUTPUT->add_script("if(parent.$JS_OBJECT_NAME){\n" . $js_code . "\n}");
814
815   $OUTPUT->write();
816   exit;
817   }
818
819
9fee0e 820 // read directory program/localization/ and return a list of available languages
T 821 function rcube_list_languages()
822   {
823   global $CONFIG, $INSTALL_PATH;
824   static $sa_languages = array();
825
826   if (!sizeof($sa_languages))
827     {
c8c1e0 828     @include($INSTALL_PATH.'program/localization/index.inc');
9fee0e 829
c8c1e0 830     if ($dh = @opendir($INSTALL_PATH.'program/localization'))
9fee0e 831       {
T 832       while (($name = readdir($dh)) !== false)
833         {
c8c1e0 834         if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
9fee0e 835           continue;
T 836
837         if ($label = $rcube_languages[$name])
838           $sa_languages[$name] = $label ? $label : $name;
839         }
840       closedir($dh);
841       }
842     }
843   return $sa_languages;
844   }
845
4e17e6 846
10a699 847 // add a localized label to the client environment
T 848 function rcube_add_label()
849   {
850   global $OUTPUT, $JS_OBJECT_NAME;
851   
852   $arg_list = func_get_args();
853   foreach ($arg_list as $i => $name)
854     $OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
855                                 $JS_OBJECT_NAME,
856                                 $name,
857                                 rep_specialchars_output(rcube_label($name), 'js')));  
1cded8 858   }
T 859
860
70d4b9 861 // remove temp files older than two day
T 862 function rcmail_temp_gc()
1cded8 863   {
70d4b9 864   $tmp = unslashify($CONFIG['temp_dir']);
T 865   $expire = mktime() - 172800;  // expire in 48 hours
1cded8 866
70d4b9 867   if ($dir = opendir($tmp))
1cded8 868     {
70d4b9 869     while (($fname = readdir($dir)) !== false)
T 870       {
871       if ($fname{0} == '.')
872         continue;
873
874       if (filemtime($tmp.'/'.$fname) < $expire)
875         @unlink($tmp.'/'.$fname);
876       }
877
878     closedir($dir);
879     }
1cded8 880   }
T 881
882
cc9570 883 // remove all expired message cache records
T 884 function rcmail_message_cache_gc()
885   {
886   global $DB, $CONFIG;
887   
888   // no cache lifetime configured
889   if (empty($CONFIG['message_cache_lifetime']))
890     return;
891   
892   // get target timestamp
893   $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
894   
895   $DB->query("DELETE FROM ".get_table_name('messages')."
896              WHERE  created < ".$DB->fromunixtime($ts));
897   }
898
1cded8 899
3f9edb 900 // convert a string from one charset to another
T 901 // this function is not complete and not tested well
902 function rcube_charset_convert($str, $from, $to=NULL)
0af7e8 903   {
5f56a5 904   global $MBSTRING;
f88d41 905
83dbb7 906   $from = strtoupper($from);
T 907   $to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
f88d41 908
2f2f15 909   if ($from==$to || $str=='' || empty($from))
3f9edb 910     return $str;
5f56a5 911
f88d41 912   // convert charset using mbstring module  
T 913   if ($MBSTRING)
914     {
915     $to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
916     $from = $from=="UTF-7" ? "UTF7-IMAP": $from;
5f56a5 917
T 918     // return if convert succeeded
919     if (($out = mb_convert_encoding($str, $to, $from)) != '')
920       return $out;
83dbb7 921     }
f88d41 922
T 923   // convert charset using iconv module  
924   if (function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7')
925     return iconv($from, $to, $str);
58e360 926
T 927   $conv = new utf8();
928
83dbb7 929   // convert string to UTF-8
T 930   if ($from=='UTF-7')
c8c1a3 931     $str = utf7_to_utf8($str);
4d4264 932   else if (($from=='ISO-8859-1') && function_exists('utf8_encode'))
83dbb7 933     $str = utf8_encode($str);
T 934   else if ($from!='UTF-8')
935     {
58e360 936     $conv->loadCharset($from);
83dbb7 937     $str = $conv->strToUtf8($str);
T 938     }
0af7e8 939
3f9edb 940   // encode string for output
83dbb7 941   if ($to=='UTF-7')
c8c1a3 942     return utf8_to_utf7($str);
83dbb7 943   else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
T 944     return utf8_decode($str);
945   else if ($to!='UTF-8')
946     {
58e360 947     $conv->loadCharset($to);
83dbb7 948     return $conv->utf8ToStr($str);
T 949     }
3f9edb 950
83dbb7 951   // return UTF-8 string
3f9edb 952   return $str;
0af7e8 953   }
3f9edb 954
0af7e8 955
T 956
1cded8 957 // replace specials characters to a specific encoding type
T 958 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
959   {
3f9edb 960   global $OUTPUT_TYPE, $OUTPUT;
1cded8 961   static $html_encode_arr, $js_rep_table, $rtf_rep_table, $xml_rep_table;
T 962
963   if (!$enctype)
964     $enctype = $GLOBALS['OUTPUT_TYPE'];
965
966   // convert nbsps back to normal spaces if not html
967   if ($enctype!='html')
968     $str = str_replace(chr(160), ' ', $str);
969
970   // encode for plaintext
971   if ($enctype=='text')
972     return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
973
974   // encode for HTML output
975   if ($enctype=='html')
976     {
977     if (!$html_encode_arr)
978       {
0af7e8 979       $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);        
1cded8 980       unset($html_encode_arr['?']);
T 981       }
982
983     $ltpos = strpos($str, '<');
984     $encode_arr = $html_encode_arr;
985
986     // don't replace quotes and html tags
987     if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
988       {
989       unset($encode_arr['"']);
990       unset($encode_arr['<']);
991       unset($encode_arr['>']);
10c92b 992       unset($encode_arr['&']);
1cded8 993       }
T 994     else if ($mode=='remove')
995       $str = strip_tags($str);
674a0f 996     
T 997     // avoid douple quotation of &
998     $out = preg_replace('/&amp;([a-z]{2,5});/', '&\\1;', strtr($str, $encode_arr));
0af7e8 999       
1cded8 1000     return $newlines ? nl2br($out) : $out;
T 1001     }
1002
1003
1004   if ($enctype=='url')
1005     return rawurlencode($str);
1006
1007
1008   // if the replace tables for RTF, XML and JS are not yet defined
1009   if (!$js_rep_table)
1010     {
1011     $js_rep_table = $rtf_rep_table = $xml_rep_table = array();
88375f 1012     $xml_rep_table['&'] = '&amp;';
1cded8 1013
T 1014     for ($c=160; $c<256; $c++)  // can be increased to support more charsets
1015       {
1016       $hex = dechex($c);
1017       $rtf_rep_table[Chr($c)] = "\\'$hex";
1018       $xml_rep_table[Chr($c)] = "&#$c;";
1019       
3f9edb 1020       if ($OUTPUT->get_charset()=='ISO-8859-1')
1cded8 1021         $js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
T 1022       }
1023
1024     $js_rep_table['"'] = sprintf("\u%s%s", str_repeat('0', 4-strlen(dechex(34))), dechex(34));
1025     $xml_rep_table['"'] = '&quot;';
1026     }
1027
1028   // encode for RTF
1029   if ($enctype=='xml')
1030     return strtr($str, $xml_rep_table);
1031
1032   // encode for javascript use
1033   if ($enctype=='js')
13c1af 1034     {
T 1035     if ($OUTPUT->get_charset()!='UTF-8')
1036       $str = rcube_charset_convert($str, $GLOBALS['CHARSET'], $OUTPUT->get_charset());
1037       
c39957 1038     return addslashes(preg_replace(array("/\r\n/", "/\r/"), array('\n', '\n'), strtr($str, $js_rep_table)));
13c1af 1039     }
1cded8 1040
T 1041   // encode for RTF
1042   if ($enctype=='rtf')
1043     return preg_replace("/\r\n/", "\par ", strtr($str, $rtf_rep_table));
1044
1045   // no encoding given -> return original string
1046   return $str;
10a699 1047   }
ea7c46 1048
T 1049
1050 /**
1051  * Read input value and convert it for internal use
1052  * Performs stripslashes() and charset conversion if necessary
1053  * 
1054  * @param  string   Field name to read
1055  * @param  int      Source to get value from (GPC)
1056  * @param  boolean  Allow HTML tags in field value
1057  * @param  string   Charset to convert into
1058  * @return string   Field value or NULL if not available
1059  */
1060 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1061   {
1062   global $OUTPUT;
1063   $value = NULL;
1064   
1065   if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1066     $value = $_GET[$fname];
1067   else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1068     $value = $_POST[$fname];
1069   else if ($source==RCUBE_INPUT_GPC)
1070     {
026d68 1071     if (isset($_POST[$fname]))
ea7c46 1072       $value = $_POST[$fname];
026d68 1073     else if (isset($_GET[$fname]))
T 1074       $value = $_GET[$fname];
ea7c46 1075     else if (isset($_COOKIE[$fname]))
T 1076       $value = $_COOKIE[$fname];
1077     }
1078   
1079   // strip slashes if magic_quotes enabled
1080   if ((bool)get_magic_quotes_gpc())
1081     $value = stripslashes($value);
1082
1083   // remove HTML tags if not allowed    
1084   if (!$allow_html)
1085     $value = strip_tags($value);
1086   
1087   // convert to internal charset
026d68 1088   if (is_object($OUTPUT))
T 1089     return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1090   else
1091     return $value;
ea7c46 1092   }
T 1093
e34ae1 1094 /**
T 1095  * Remove single and double quotes from given string
1096  */
1097 function strip_quotes($str)
1098 {
1099   return preg_replace('/[\'"]/', '', $str);
1100 }
10a699 1101
4e17e6 1102
T 1103 // ************** template parsing and gui functions **************
1104
1105
1106 // return boolean if a specific template exists
1107 function template_exists($name)
1108   {
1109   global $CONFIG, $OUTPUT;
1110   $skin_path = $CONFIG['skin_path'];
1111
1112   // check template file
1113   return is_file("$skin_path/templates/$name.html");
1114   }
1115
1116
1117 // get page template an replace variable
1118 // similar function as used in nexImage
1119 function parse_template($name='main', $exit=TRUE)
1120   {
1121   global $CONFIG, $OUTPUT;
1122   $skin_path = $CONFIG['skin_path'];
1123
1124   // read template file
1125   $templ = '';
1126   $path = "$skin_path/templates/$name.html";
1127
1128   if($fp = @fopen($path, 'r'))
1129     {
1130     $templ = fread($fp, filesize($path));
1131     fclose($fp);
1132     }
1133   else
1134     {
1135     raise_error(array('code' => 500,
1136                       'type' => 'php',
1137                       'line' => __LINE__,
1138                       'file' => __FILE__,
1139                       'message' => "Error loading template for '$name'"), TRUE, TRUE);
1140     return FALSE;
1141     }
1142
1143
1144   // parse for specialtags
b19097 1145   $output = parse_rcube_xml(parse_rcube_conditions($templ));
4e17e6 1146   
b19097 1147   // add debug console
T 1148   if ($CONFIG['debug_level'] & 8)
1149     $OUTPUT->footer = '<div style="position:absolute;top:5px;left:5px;width:400px;opacity:0.8;z-index:9000;"><form name="debugform"><textarea name="console" rows="15" cols="40" style="width:400px;border:none;font-size:x-small"></textarea></form>';
1150
4e17e6 1151   $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
T 1152
1153   if ($exit)
1154     exit;
1155   }
1156
1157
1158
1159 // replace all strings ($varname) with the content of the according global variable
1160 function parse_with_globals($input)
1161   {
b595c9 1162   $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
4e17e6 1163   $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
T 1164   return $output;
1165   }
1166
1167
b19097 1168 // parse conditional code
T 1169 function parse_rcube_conditions($input)
1170   {
1171   if (($matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE)) && count($matches)==4)
1172     {
1173     if (preg_match('/^(else|endif)$/i', $matches[1]))
1174       return $matches[0] . parse_rcube_conditions($matches[3]);
1175     else
1176       {
1177       $attrib = parse_attrib_string($matches[2]);
1178       if (isset($attrib['condition']))
1179         {
1180         $condmet = rcube_xml_condition($attrib['condition']);
1181         $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
1182
1183             if ($condmet)
1184                 $result = $submatches[0] . preg_replace('/.*<roundcube:endif\s+[^>]+>/is', '', $submatches[3]);
1185         else
1186           $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
1187           
1188         return $matches[0] . parse_rcube_conditions($result);
1189         }
1190       else
1191         {
1192         raise_error(array('code' => 500, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__,
1193                           'message' => "Unable to parse conditional tag " . $matches[2]), TRUE, FALSE);
1194         }
1195       }
1196     }
1197
1198   return $input;
1199   }
1200
1201  
1202 /**
1203  * Determines if a given condition is met
1204  *
1205  * @return True if condition is valid, False is not
1206  */
1207 function rcube_xml_condition($condition)
1208   {
1209   $condition = preg_replace(
1210       array('/session:([a-z0-9_]+)/i', '/config:([a-z0-9_]+)/i', '/request:([a-z0-9_]+)/ie'),
1211       array("\$_SESSION['\\1']", "\$GLOBALS['CONFIG']['\\1']", "get_input_value('\\1', RCUBE_INPUT_GPC)"),
1212       $condition);
1213
1214   return @eval("return (".$condition.");");
1215   }
1216
4e17e6 1217
T 1218 function parse_rcube_xml($input)
1219   {
1220   $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
1221   return $output;
1222   }
1223
1224
b19097 1225 /**
T 1226  * Convert a xml command tag into real content
1227  */
fe79b1 1228 function rcube_xml_command($command, $str_attrib, $add_attrib=array())
4e17e6 1229   {
0af7e8 1230   global $IMAP, $CONFIG, $OUTPUT;
4e17e6 1231   
T 1232   $command = strtolower($command);
fe79b1 1233   $attrib = parse_attrib_string($str_attrib) + $add_attrib;
b19097 1234   
T 1235   // empty output if required condition is not met
1236   if (!empty($attrib['condition']) && !rcube_xml_condition($attrib['condition']))
1237     return '';
4e17e6 1238
T 1239   // execute command
1240   switch ($command)
1241     {
1242     // return a button
1243     case 'button':
1244       if ($attrib['command'])
1245         return rcube_button($attrib);
1246       break;
1247
1248     // show a label
1249     case 'label':
1250       if ($attrib['name'] || $attrib['command'])
7dd801 1251         return rep_specialchars_output(rcube_label($attrib));
4e17e6 1252       break;
T 1253
1254     // create a menu item
1255     case 'menu':
1256       if ($attrib['command'] && $attrib['group'])
1257         rcube_menu($attrib);
1258       break;
1259
1260     // include a file 
1261     case 'include':
1262       $path = realpath($CONFIG['skin_path'].$attrib['file']);
1263       
1264       if($fp = @fopen($path, 'r'))
1265         {
1266         $incl = fread($fp, filesize($path));
1267         fclose($fp);        
1268         return parse_rcube_xml($incl);
1269         }
1270       break;
1271
1272     // return code for a specific application object
1273     case 'object':
1274       $object = strtolower($attrib['name']);
1275
1cded8 1276       $object_handlers = array(
15a9d1 1277         // GENERAL
T 1278         'loginform' => 'rcmail_login_form',
1279         'username'  => 'rcmail_current_username',
1280         
1cded8 1281         // MAIL
T 1282         'mailboxlist' => 'rcmail_mailbox_list',
15a9d1 1283         'message' => 'rcmail_message_container',
1cded8 1284         'messages' => 'rcmail_message_list',
T 1285         'messagecountdisplay' => 'rcmail_messagecount_display',
58e360 1286         'quotadisplay' => 'rcmail_quota_display',
1cded8 1287         'messageheaders' => 'rcmail_message_headers',
T 1288         'messagebody' => 'rcmail_message_body',
1289         'messageattachments' => 'rcmail_message_attachments',
1290         'blockedobjects' => 'rcmail_remote_objects_msg',
1291         'messagecontentframe' => 'rcmail_messagecontent_frame',
1292         'messagepartframe' => 'rcmail_message_part_frame',
1293         'messagepartcontrols' => 'rcmail_message_part_controls',
1294         'composeheaders' => 'rcmail_compose_headers',
1295         'composesubject' => 'rcmail_compose_subject',
1296         'composebody' => 'rcmail_compose_body',
1297         'composeattachmentlist' => 'rcmail_compose_attachment_list',
1298         'composeattachmentform' => 'rcmail_compose_attachment_form',
1299         'composeattachment' => 'rcmail_compose_attachment_field',
1300         'priorityselector' => 'rcmail_priority_selector',
1301         'charsetselector' => 'rcmail_charset_selector',
a0109c 1302         'editorselector' => 'rcmail_editor_selector',
4647e1 1303         'searchform' => 'rcmail_search_form',
620439 1304         'receiptcheckbox' => 'rcmail_receipt_checkbox',
1cded8 1305         
T 1306         // ADDRESS BOOK
1307         'addresslist' => 'rcmail_contacts_list',
1308         'addressframe' => 'rcmail_contact_frame',
1309         'recordscountdisplay' => 'rcmail_rowcount_display',
1310         'contactdetails' => 'rcmail_contact_details',
1311         'contacteditform' => 'rcmail_contact_editform',
d1d2c4 1312         'ldappublicsearch' => 'rcmail_ldap_public_search_form',
S 1313         'ldappublicaddresslist' => 'rcmail_ldap_public_list',
1cded8 1314
T 1315         // USER SETTINGS
1316         'userprefs' => 'rcmail_user_prefs_form',
1317         'itentitieslist' => 'rcmail_identities_list',
1318         'identityframe' => 'rcmail_identity_frame',
1319         'identityform' => 'rcube_identity_form',
1320         'foldersubscription' => 'rcube_subscription_form',
1321         'createfolder' => 'rcube_create_folder_form',
fe79b1 1322         'renamefolder' => 'rcube_rename_folder_form',
1cded8 1323         'composebody' => 'rcmail_compose_body'
T 1324       );
1325
1326       
1327       // execute object handler function
15a9d1 1328       if ($object_handlers[$object] && function_exists($object_handlers[$object]))
1cded8 1329         return call_user_func($object_handlers[$object], $attrib);
8c2e58 1330         
T 1331       else if ($object=='productname')
1332         {
1333         $name = !empty($CONFIG['product_name']) ? $CONFIG['product_name'] : 'RoundCube Webmail';
1334         return rep_specialchars_output($name, 'html', 'all');
1335         }
026d68 1336       else if ($object=='version')
T 1337         {
1338         return (string)RCMAIL_VERSION;
1339         }
4e17e6 1340       else if ($object=='pagetitle')
T 1341         {
1342         $task = $GLOBALS['_task'];
15a9d1 1343         $title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
T 1344         
ded2b7 1345         if ($task=='login')
T 1346           $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $CONFIG['product_name'])));
1347         else if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
15a9d1 1348           $title .= $GLOBALS['MESSAGE']['subject'];
4e17e6 1349         else if (isset($GLOBALS['PAGE_TITLE']))
15a9d1 1350           $title .= $GLOBALS['PAGE_TITLE'];
4e17e6 1351         else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
3f9edb 1352           $title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
4e17e6 1353         else
ded2b7 1354           $title .= ucfirst($task);
15a9d1 1355           
T 1356         return rep_specialchars_output($title, 'html', 'all');
4e17e6 1357         }
T 1358
1359       break;
1360     }
1361
1362   return '';
1363   }
1364
1365
1366 // create and register a button
1367 function rcube_button($attrib)
1368   {
8c2e58 1369   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER, $COMM_PATH, $MAIN_TASKS;
4e17e6 1370   static $sa_buttons = array();
T 1371   static $s_button_count = 100;
1372   
078adf 1373   // these commands can be called directly via url
T 1374   $a_static_commands = array('compose', 'list');
1375   
4e17e6 1376   $skin_path = $CONFIG['skin_path'];
T 1377   
1378   if (!($attrib['command'] || $attrib['name']))
1379     return '';
1380
1381   // try to find out the button type
1382   if ($attrib['type'])
1383     $attrib['type'] = strtolower($attrib['type']);
1384   else
a0109c 1385     $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
4e17e6 1386   
T 1387   $command = $attrib['command'];
1388   
1389   // take the button from the stack
1390   if($attrib['name'] && $sa_buttons[$attrib['name']])
1391     $attrib = $sa_buttons[$attrib['name']];
1392
1393   // add button to button stack
a0109c 1394   else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class'])
4e17e6 1395     {
T 1396     if(!$attrib['name'])
1397       $attrib['name'] = $command;
1398
1399     if (!$attrib['image'])
1400       $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1401
1402     $sa_buttons[$attrib['name']] = $attrib;
1403     }
1404
1405   // get saved button for this command/name
1406   else if ($command && $sa_buttons[$command])
1407     $attrib = $sa_buttons[$command];
1408
1409   //else
1410   //  return '';
1411
1412
1413   // set border to 0 because of the link arround the button
1414   if ($attrib['type']=='image' && !isset($attrib['border']))
1415     $attrib['border'] = 0;
1416     
1417   if (!$attrib['id'])
1418     $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
1419
1420   // get localized text for labels and titles
1421   if ($attrib['title'])
1422     $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
1423   if ($attrib['label'])
1424     $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
1425
1426   if ($attrib['alt'])
1427     $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
14eafe 1428
T 1429   // set title to alt attribute for IE browsers
1430   if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
1431     {
1432     $attrib['alt'] = $attrib['title'];
1433     unset($attrib['title']);
1434     }
1435
4e17e6 1436   // add empty alt attribute for XHTML compatibility
T 1437   if (!isset($attrib['alt']))
1438     $attrib['alt'] = '';
1439
1440
1441   // register button in the system
1442   if ($attrib['command'])
8c2e58 1443     {
4e17e6 1444     $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
T 1445                                 $JS_OBJECT_NAME,
1446                                 $command,
1447                                 $attrib['id'],
1448                                 $attrib['type'],
1449                                 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
c8c1e0 1450                                 $attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
4e17e6 1451                                 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
T 1452
078adf 1453     // make valid href to specific buttons
8c2e58 1454     if (in_array($attrib['command'], $MAIN_TASKS))
078adf 1455       $attrib['href'] = htmlentities(ereg_replace('_task=[a-z]+', '_task='.$attrib['command'], $COMM_PATH));
T 1456     else if (in_array($attrib['command'], $a_static_commands))
1457       $attrib['href'] = htmlentities($COMM_PATH.'&_action='.$attrib['command']);
8c2e58 1458     }
T 1459
4e17e6 1460   // overwrite attributes
T 1461   if (!$attrib['href'])
1462     $attrib['href'] = '#';
1463
1464   if ($command)
1465     $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
1466     
1467   if ($command && $attrib['imageover'])
1468     {
1469     $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1470     $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1471     }
1472
c8c1e0 1473   if ($command && $attrib['imagesel'])
S 1474     {
1475     $attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1476     $attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1477     }
4e17e6 1478
T 1479   $out = '';
1480
1481   // generate image tag
1482   if ($attrib['type']=='image')
1483     {
1cded8 1484     $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
4e17e6 1485     $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
T 1486     $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
1487     if ($attrib['label'])
1488       $btn_content .= ' '.$attrib['label'];
1489     
c8c1e0 1490     $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
4e17e6 1491     }
T 1492   else if ($attrib['type']=='link')
1493     {
1494     $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
1495     $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
1496     }
1497   else if ($attrib['type']=='input')
1498     {
1499     $attrib['type'] = 'button';
1500     
1501     if ($attrib['label'])
1502       $attrib['value'] = $attrib['label'];
1503       
1504     $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
1505     $out = sprintf('<input%s disabled />', $attrib_str);
1506     }
1507
1508   // generate html code for button
1509   if ($btn_content)
1510     {
1511     $attrib_str = create_attrib_string($attrib, $link_attrib);
1512     $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1513     }
1514
1515   return $out;
1516   }
1517
1518
1519 function rcube_menu($attrib)
1520   {
1521   
1522   return '';
1523   }
1524
1525
1526
d1d2c4 1527 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
4e17e6 1528   {
T 1529   global $DB;
1530   
1531   // allow the following attributes to be added to the <table> tag
1532   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1533   
1534   $table = '<table' . $attrib_str . ">\n";
1535     
1536   // add table title
1537   $table .= "<thead><tr>\n";
1538
1539   foreach ($a_show_cols as $col)
1038d5 1540     $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
4e17e6 1541
T 1542   $table .= "</tr></thead>\n<tbody>\n";
1543   
1544   $c = 0;
d1d2c4 1545
S 1546   if (!is_array($table_data)) 
4e17e6 1547     {
d1d2c4 1548     while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
4e17e6 1549       {
d1d2c4 1550       $zebra_class = $c%2 ? 'even' : 'odd';
4e17e6 1551
d1d2c4 1552       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
S 1553
1554       // format each col
1555       foreach ($a_show_cols as $col)
1556         {
1557         $cont = rep_specialchars_output($sql_arr[$col]);
1558         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1559         }
1560
1561       $table .= "</tr>\n";
1562       $c++;
1563       }
1564     }
1565   else 
1566     {
1567     foreach ($table_data as $row_data)
1568       {
1569       $zebra_class = $c%2 ? 'even' : 'odd';
1570
1571       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1572
1573       // format each col
1574       foreach ($a_show_cols as $col)
1575         {
1576         $cont = rep_specialchars_output($row_data[$col]);
1577         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1578         }
1579
1580       $table .= "</tr>\n";
1581       $c++;
1582       }
4e17e6 1583     }
T 1584
1585   // complete message table
1586   $table .= "</tbody></table>\n";
1587   
1588   return $table;
1589   }
1590
1591
a0109c 1592 /**
S 1593  * Create an edit field for inclusion on a form
1594  * 
1595  * @param string col field name
1596  * @param string value field value
1597  * @param array attrib HTML element attributes for field
1598  * @param string type HTML element type (default 'text')
1599  * @return string HTML field definition
1600  */
4e17e6 1601 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
T 1602   {
1603   $fname = '_'.$col;
1604   $attrib['name'] = $fname;
1605   
1606   if ($type=='checkbox')
1607     {
1608     $attrib['value'] = '1';
1609     $input = new checkbox($attrib);
1610     }
1611   else if ($type=='textarea')
1612     {
1613     $attrib['cols'] = $attrib['size'];
1614     $input = new textarea($attrib);
1615     }
1616   else
1617     $input = new textfield($attrib);
1618
1619   // use value from post
597170 1620   if (!empty($_POST[$fname]))
4e17e6 1621     $value = $_POST[$fname];
T 1622
1623   $out = $input->show($value);
1624          
1625   return $out;
1626   }
1627
1628
fe79b1 1629 // compose a valid attribute string for HTML tags
4e17e6 1630 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
T 1631   {
1632   // allow the following attributes to be added to the <iframe> tag
1633   $attrib_str = '';
1634   foreach ($allowed_attribs as $a)
1635     if (isset($attrib[$a]))
fe79b1 1636       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
4e17e6 1637
T 1638   return $attrib_str;
1639   }
1640
1641
fe79b1 1642 // convert a HTML attribute string attributes to an associative array (name => value)
T 1643 function parse_attrib_string($str)
1644   {
1645   $attrib = array();
1646   preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str), $regs, PREG_SET_ORDER);
1647
1648   // convert attributes to an associative array (name => value)
1649   if ($regs)
1650     foreach ($regs as $attr)
1651       $attrib[strtolower($attr[1])] = $attr[2];
1652
1653   return $attrib;
1654   }
1655
4e17e6 1656
T 1657 function format_date($date, $format=NULL)
1658   {
1659   global $CONFIG, $sess_user_lang;
1660   
4647e1 1661   $ts = NULL;
T 1662   
4e17e6 1663   if (is_numeric($date))
T 1664     $ts = $date;
b076a4 1665   else if (!empty($date))
4647e1 1666     $ts = @strtotime($date);
T 1667     
1668   if (empty($ts))
b076a4 1669     return '';
4647e1 1670    
T 1671   // get user's timezone
1672   $tz = $CONFIG['timezone'];
1673   if ($CONFIG['dst_active'])
1674     $tz++;
4e17e6 1675
T 1676   // convert time to user's timezone
4647e1 1677   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
4e17e6 1678   
T 1679   // get current timestamp in user's timezone
1680   $now = time();  // local time
1681   $now -= (int)date('Z'); // make GMT time
4647e1 1682   $now += ($tz * 3600); // user's time
749b07 1683   $now_date = getdate();
4e17e6 1684
749b07 1685   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
T 1686   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 1687
30233b 1688   // define date format depending on current time  
749b07 1689   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
4e17e6 1690     return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
749b07 1691   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
4e17e6 1692     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 1693   else if (!$format)
1694     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1695
1696
1697   // parse format string manually in order to provide localized weekday and month names
1698   // an alternative would be to convert the date() format string to fit with strftime()
1699   $out = '';
1700   for($i=0; $i<strlen($format); $i++)
1701     {
1702     if ($format{$i}=='\\')  // skip escape chars
1703       continue;
1704     
1705     // write char "as-is"
1706     if ($format{$i}==' ' || $format{$i-1}=='\\')
1707       $out .= $format{$i};
1708     // weekday (short)
1709     else if ($format{$i}=='D')
1710       $out .= rcube_label(strtolower(date('D', $timestamp)));
1711     // weekday long
1712     else if ($format{$i}=='l')
1713       $out .= rcube_label(strtolower(date('l', $timestamp)));
1714     // month name (short)
1715     else if ($format{$i}=='M')
1716       $out .= rcube_label(strtolower(date('M', $timestamp)));
1717     // month name (long)
1718     else if ($format{$i}=='F')
1719       $out .= rcube_label(strtolower(date('F', $timestamp)));
1720     else
1721       $out .= date($format{$i}, $timestamp);
1722     }
1723   
1724   return $out;
1725   }
1726
1727
1728 // ************** functions delivering gui objects **************
1729
1730
1731
1732 function rcmail_message_container($attrib)
1733   {
1734   global $OUTPUT, $JS_OBJECT_NAME;
1735
1736   if (!$attrib['id'])
1737     $attrib['id'] = 'rcmMessageContainer';
1738
1739   // allow the following attributes to be added to the <table> tag
1740   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1741   $out = '<div' . $attrib_str . "></div>";
1742   
1743   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1744   
1745   return $out;
1746   }
1747
1748
15a9d1 1749 // return the IMAP username of the current session
T 1750 function rcmail_current_username($attrib)
1751   {
1752   global $DB;
1753   static $s_username;
1754
1755   // alread fetched  
1756   if (!empty($s_username))
1757     return $s_username;
1758
1759   // get e-mail address form default identity
1760   $sql_result = $DB->query("SELECT email AS mailto
1761                             FROM ".get_table_name('identities')."
1762                             WHERE  user_id=?
1763                             AND    standard=1
1764                             AND    del<>1",
1765                             $_SESSION['user_id']);
1766                                    
1767   if ($DB->num_rows($sql_result))
1768     {
1769     $sql_arr = $DB->fetch_assoc($sql_result);
1770     $s_username = $sql_arr['mailto'];
1771     }
1772   else if (strstr($_SESSION['username'], '@'))
1773     $s_username = $_SESSION['username'];
1774   else
1775     $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1776
1777   return $s_username;
1778   }
1779
1780
8cb245 1781 // return the mail domain configured for the given host
T 1782 function rcmail_mail_domain($host)
1783   {
1784   global $CONFIG;
1785
1786   $domain = $host;
1787   if (is_array($CONFIG['mail_domain']))
1788     {
1789     if (isset($CONFIG['mail_domain'][$host]))
1790       $domain = $CONFIG['mail_domain'][$host];
1791     }
1792   else if (!empty($CONFIG['mail_domain']))
1793     $domain = $CONFIG['mail_domain'];
1794
1795   return $domain;
1796   }
1797
1798
4e17e6 1799 // return code for the webmail login form
T 1800 function rcmail_login_form($attrib)
1801   {
1802   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1803   
1804   $labels = array();
1805   $labels['user'] = rcube_label('username');
1806   $labels['pass'] = rcube_label('password');
1807   $labels['host'] = rcube_label('server');
1808   
66e2bf 1809   $input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30));
T 1810   $input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
4e17e6 1811   $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
T 1812     
1813   $fields = array();
ea7c46 1814   $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
4e17e6 1815   $fields['pass'] = $input_pass->show();
T 1816   $fields['action'] = $input_action->show();
1817   
1818   if (is_array($CONFIG['default_host']))
1819     {
66e2bf 1820     $select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
42b113 1821     
T 1822     foreach ($CONFIG['default_host'] as $key => $value)
0a020c 1823     {
T 1824       if (!is_array($value))
1825         $select_host->add($value, (is_numeric($key) ? $value : $key));
1826       else
1827         {
1828         unset($select_host);
1829         break;
1830         }
1831     }
42b113 1832       
0a020c 1833     $fields['host'] = isset($select_host) ? $select_host->show($_POST['_host']) : null;
4e17e6 1834     }
T 1835   else if (!strlen($CONFIG['default_host']))
1836     {
0a020c 1837     $input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
T 1838     $fields['host'] = $input_host->show($_POST['_host']);
4e17e6 1839     }
T 1840
1841   $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1842   $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1843   $form_end = !strlen($attrib['form']) ? '</form>' : '';
1844   
1845   if ($fields['host'])
1846     $form_host = <<<EOF
1847     
1848 </tr><tr>
1849
66e2bf 1850 <td class="title"><label for="rcmloginhost">$labels[host]</label></td>
4e17e6 1851 <td>$fields[host]</td>
T 1852
1853 EOF;
1854
1855   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1856   
1857   $out = <<<EOF
1858 $form_start
1859 $SESS_HIDDEN_FIELD
1860 $fields[action]
1861 <table><tr>
1862
66e2bf 1863 <td class="title"><label for="rcmloginuser">$labels[user]</label></td>
4e17e6 1864 <td>$fields[user]</td>
T 1865
1866 </tr><tr>
1867
66e2bf 1868 <td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
4e17e6 1869 <td>$fields[pass]</td>
T 1870 $form_host
1871 </tr></table>
1872 $form_end
1873 EOF;
1874
1875   return $out;
1876   }
1877
1878
1cded8 1879 function rcmail_charset_selector($attrib)
T 1880   {
13c1af 1881   global $OUTPUT;
T 1882   
1cded8 1883   // pass the following attributes to the form class
T 1884   $field_attrib = array('name' => '_charset');
1885   foreach ($attrib as $attr => $value)
1886     if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1887       $field_attrib[$attr] = $value;
1888       
1889   $charsets = array(
1890     'US-ASCII'     => 'ASCII (English)',
f88d41 1891     'EUC-JP'       => 'EUC-JP (Japanese)',
1cded8 1892     'EUC-KR'       => 'EUC-KR (Korean)',
T 1893     'BIG5'         => 'BIG5 (Chinese)',
1894     'GB2312'       => 'GB2312 (Chinese)',
f88d41 1895     'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1cded8 1896     'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
T 1897     'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1898     'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1899     'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1900     'Windows-1251' => 'Windows-1251 (Cyrillic)',
1901     'Windows-1252' => 'Windows-1252 (Western)',
1902     'Windows-1255' => 'Windows-1255 (Hebrew)',
1903     'Windows-1256' => 'Windows-1256 (Arabic)',
1904     'Windows-1257' => 'Windows-1257 (Baltic)',
1905     'UTF-8'        => 'UTF-8'
1906     );
1907
1908   $select = new select($field_attrib);
1909   $select->add(array_values($charsets), array_keys($charsets));
1910   
13c1af 1911   $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
1cded8 1912   return $select->show($set);
T 1913   }
1914
1915
c39957 1916 /****** debugging functions ********/
T 1917
1918
1919 /**
1920  * Print or write debug messages
1921  *
1922  * @param mixed Debug message or data
1923  */
1924 function console($msg)
1925   {
8d4bcd 1926   if (!is_string($msg))
c39957 1927     $msg = var_export($msg, true);
T 1928
1929   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1930     write_log('console', $msg);
1931   else if ($GLOBALS['REMOTE_REQUEST'])
1932     print "/*\n $msg \n*/\n";
1933   else
1934     {
1935     print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1936     print $msg;
1937     print "</pre></div>\n";
1938     }
1939   }
1940
1941
1942 /**
1943  * Append a line to a logfile in the logs directory.
1944  * Date will be added automatically to the line.
1945  *
1946  * @param $name Name of logfile
1947  * @param $line Line to append
1948  */
1949 function write_log($name, $line)
1950   {
1951   global $CONFIG;
e170b4 1952
T 1953   if (!is_string($line))
1954     $line = var_export($line, true);
c39957 1955   
T 1956   $log_entry = sprintf("[%s]: %s\n",
1957                  date("d-M-Y H:i:s O", mktime()),
1958                  $line);
1959                  
1960   if (empty($CONFIG['log_dir']))
1961     $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1962       
1963   // try to open specific log file for writing
1964   if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))    
1965     {
1966     fwrite($fp, $log_entry);
1967     fclose($fp);
1968     }
1969   }
1970
cc9570 1971
15a9d1 1972 function rcube_timer()
T 1973   {
1974   list($usec, $sec) = explode(" ", microtime());
1975   return ((float)$usec + (float)$sec);
1976   }
1977   
1978
1979 function rcube_print_time($timer, $label='Timer')
1980   {
1981   static $print_count = 0;
1982   
1983   $print_count++;
1984   $now = rcube_timer();
1985   $diff = $now-$timer;
1986   
1987   if (empty($label))
1988     $label = 'Timer '.$print_count;
1989   
1990   console(sprintf("%s: %0.4f sec", $label, $diff));
1991   }
1992
d1d2c4 1993 ?>