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