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