svncommit
2006-11-21 84f9312e1d17725db6040554a993db38292d46bd
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
10a699 1066
T 1067
4e17e6 1068
T 1069 // ************** template parsing and gui functions **************
1070
1071
1072 // return boolean if a specific template exists
1073 function template_exists($name)
1074   {
1075   global $CONFIG, $OUTPUT;
1076   $skin_path = $CONFIG['skin_path'];
1077
1078   // check template file
1079   return is_file("$skin_path/templates/$name.html");
1080   }
1081
1082
1083 // get page template an replace variable
1084 // similar function as used in nexImage
1085 function parse_template($name='main', $exit=TRUE)
1086   {
1087   global $CONFIG, $OUTPUT;
1088   $skin_path = $CONFIG['skin_path'];
1089
1090   // read template file
1091   $templ = '';
1092   $path = "$skin_path/templates/$name.html";
1093
1094   if($fp = @fopen($path, 'r'))
1095     {
1096     $templ = fread($fp, filesize($path));
1097     fclose($fp);
1098     }
1099   else
1100     {
1101     raise_error(array('code' => 500,
1102                       'type' => 'php',
1103                       'line' => __LINE__,
1104                       'file' => __FILE__,
1105                       'message' => "Error loading template for '$name'"), TRUE, TRUE);
1106     return FALSE;
1107     }
1108
1109
1110   // parse for specialtags
1111   $output = parse_rcube_xml($templ);
1112   
1113   $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
1114
1115   if ($exit)
1116     exit;
1117   }
1118
1119
1120
1121 // replace all strings ($varname) with the content of the according global variable
1122 function parse_with_globals($input)
1123   {
b595c9 1124   $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
4e17e6 1125   $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
T 1126   return $output;
1127   }
1128
1129
1130
1131 function parse_rcube_xml($input)
1132   {
1133   $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
1134   return $output;
1135   }
1136
1137
fe79b1 1138 function rcube_xml_command($command, $str_attrib, $add_attrib=array())
4e17e6 1139   {
0af7e8 1140   global $IMAP, $CONFIG, $OUTPUT;
4e17e6 1141   
T 1142   $command = strtolower($command);
fe79b1 1143   $attrib = parse_attrib_string($str_attrib) + $add_attrib;
4e17e6 1144
T 1145   // execute command
1146   switch ($command)
1147     {
1148     // return a button
1149     case 'button':
1150       if ($attrib['command'])
1151         return rcube_button($attrib);
1152       break;
1153
1154     // show a label
1155     case 'label':
1156       if ($attrib['name'] || $attrib['command'])
7dd801 1157         return rep_specialchars_output(rcube_label($attrib));
4e17e6 1158       break;
T 1159
1160     // create a menu item
1161     case 'menu':
1162       if ($attrib['command'] && $attrib['group'])
1163         rcube_menu($attrib);
1164       break;
1165
1166     // include a file 
1167     case 'include':
1168       $path = realpath($CONFIG['skin_path'].$attrib['file']);
1169       
1170       if($fp = @fopen($path, 'r'))
1171         {
1172         $incl = fread($fp, filesize($path));
1173         fclose($fp);        
1174         return parse_rcube_xml($incl);
1175         }
1176       break;
1177
1178     // return code for a specific application object
1179     case 'object':
1180       $object = strtolower($attrib['name']);
1181
1cded8 1182       $object_handlers = array(
15a9d1 1183         // GENERAL
T 1184         'loginform' => 'rcmail_login_form',
1185         'username'  => 'rcmail_current_username',
1186         
1cded8 1187         // MAIL
T 1188         'mailboxlist' => 'rcmail_mailbox_list',
15a9d1 1189         'message' => 'rcmail_message_container',
1cded8 1190         'messages' => 'rcmail_message_list',
T 1191         'messagecountdisplay' => 'rcmail_messagecount_display',
58e360 1192         'quotadisplay' => 'rcmail_quota_display',
1cded8 1193         'messageheaders' => 'rcmail_message_headers',
T 1194         'messagebody' => 'rcmail_message_body',
1195         'messageattachments' => 'rcmail_message_attachments',
1196         'blockedobjects' => 'rcmail_remote_objects_msg',
1197         'messagecontentframe' => 'rcmail_messagecontent_frame',
1198         'messagepartframe' => 'rcmail_message_part_frame',
1199         'messagepartcontrols' => 'rcmail_message_part_controls',
1200         'composeheaders' => 'rcmail_compose_headers',
1201         'composesubject' => 'rcmail_compose_subject',
1202         'composebody' => 'rcmail_compose_body',
1203         'composeattachmentlist' => 'rcmail_compose_attachment_list',
1204         'composeattachmentform' => 'rcmail_compose_attachment_form',
1205         'composeattachment' => 'rcmail_compose_attachment_field',
1206         'priorityselector' => 'rcmail_priority_selector',
1207         'charsetselector' => 'rcmail_charset_selector',
a0109c 1208         'editorselector' => 'rcmail_editor_selector',
4647e1 1209         'searchform' => 'rcmail_search_form',
620439 1210         'receiptcheckbox' => 'rcmail_receipt_checkbox',
1cded8 1211         
T 1212         // ADDRESS BOOK
1213         'addresslist' => 'rcmail_contacts_list',
1214         'addressframe' => 'rcmail_contact_frame',
1215         'recordscountdisplay' => 'rcmail_rowcount_display',
1216         'contactdetails' => 'rcmail_contact_details',
1217         'contacteditform' => 'rcmail_contact_editform',
d1d2c4 1218         'ldappublicsearch' => 'rcmail_ldap_public_search_form',
S 1219         'ldappublicaddresslist' => 'rcmail_ldap_public_list',
1cded8 1220
T 1221         // USER SETTINGS
1222         'userprefs' => 'rcmail_user_prefs_form',
1223         'itentitieslist' => 'rcmail_identities_list',
1224         'identityframe' => 'rcmail_identity_frame',
1225         'identityform' => 'rcube_identity_form',
1226         'foldersubscription' => 'rcube_subscription_form',
1227         'createfolder' => 'rcube_create_folder_form',
fe79b1 1228         'renamefolder' => 'rcube_rename_folder_form',
1cded8 1229         'composebody' => 'rcmail_compose_body'
T 1230       );
1231
1232       
1233       // execute object handler function
15a9d1 1234       if ($object_handlers[$object] && function_exists($object_handlers[$object]))
1cded8 1235         return call_user_func($object_handlers[$object], $attrib);
8c2e58 1236         
T 1237       else if ($object=='productname')
1238         {
1239         $name = !empty($CONFIG['product_name']) ? $CONFIG['product_name'] : 'RoundCube Webmail';
1240         return rep_specialchars_output($name, 'html', 'all');
1241         }
026d68 1242       else if ($object=='version')
T 1243         {
1244         return (string)RCMAIL_VERSION;
1245         }
4e17e6 1246       else if ($object=='pagetitle')
T 1247         {
1248         $task = $GLOBALS['_task'];
15a9d1 1249         $title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
T 1250         
ded2b7 1251         if ($task=='login')
T 1252           $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $CONFIG['product_name'])));
1253         else if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
15a9d1 1254           $title .= $GLOBALS['MESSAGE']['subject'];
4e17e6 1255         else if (isset($GLOBALS['PAGE_TITLE']))
15a9d1 1256           $title .= $GLOBALS['PAGE_TITLE'];
4e17e6 1257         else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
3f9edb 1258           $title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
4e17e6 1259         else
ded2b7 1260           $title .= ucfirst($task);
15a9d1 1261           
T 1262         return rep_specialchars_output($title, 'html', 'all');
4e17e6 1263         }
T 1264
1265       break;
1266     }
1267
1268   return '';
1269   }
1270
1271
1272 // create and register a button
1273 function rcube_button($attrib)
1274   {
8c2e58 1275   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER, $COMM_PATH, $MAIN_TASKS;
4e17e6 1276   static $sa_buttons = array();
T 1277   static $s_button_count = 100;
1278   
078adf 1279   // these commands can be called directly via url
T 1280   $a_static_commands = array('compose', 'list');
1281   
4e17e6 1282   $skin_path = $CONFIG['skin_path'];
T 1283   
1284   if (!($attrib['command'] || $attrib['name']))
1285     return '';
1286
1287   // try to find out the button type
1288   if ($attrib['type'])
1289     $attrib['type'] = strtolower($attrib['type']);
1290   else
a0109c 1291     $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
4e17e6 1292   
T 1293   $command = $attrib['command'];
1294   
1295   // take the button from the stack
1296   if($attrib['name'] && $sa_buttons[$attrib['name']])
1297     $attrib = $sa_buttons[$attrib['name']];
1298
1299   // add button to button stack
a0109c 1300   else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class'])
4e17e6 1301     {
T 1302     if(!$attrib['name'])
1303       $attrib['name'] = $command;
1304
1305     if (!$attrib['image'])
1306       $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1307
1308     $sa_buttons[$attrib['name']] = $attrib;
1309     }
1310
1311   // get saved button for this command/name
1312   else if ($command && $sa_buttons[$command])
1313     $attrib = $sa_buttons[$command];
1314
1315   //else
1316   //  return '';
1317
1318
1319   // set border to 0 because of the link arround the button
1320   if ($attrib['type']=='image' && !isset($attrib['border']))
1321     $attrib['border'] = 0;
1322     
1323   if (!$attrib['id'])
1324     $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
1325
1326   // get localized text for labels and titles
1327   if ($attrib['title'])
1328     $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
1329   if ($attrib['label'])
1330     $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
1331
1332   if ($attrib['alt'])
1333     $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
14eafe 1334
T 1335   // set title to alt attribute for IE browsers
1336   if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
1337     {
1338     $attrib['alt'] = $attrib['title'];
1339     unset($attrib['title']);
1340     }
1341
4e17e6 1342   // add empty alt attribute for XHTML compatibility
T 1343   if (!isset($attrib['alt']))
1344     $attrib['alt'] = '';
1345
1346
1347   // register button in the system
1348   if ($attrib['command'])
8c2e58 1349     {
4e17e6 1350     $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
T 1351                                 $JS_OBJECT_NAME,
1352                                 $command,
1353                                 $attrib['id'],
1354                                 $attrib['type'],
1355                                 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
c8c1e0 1356                                 $attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
4e17e6 1357                                 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
T 1358
078adf 1359     // make valid href to specific buttons
8c2e58 1360     if (in_array($attrib['command'], $MAIN_TASKS))
078adf 1361       $attrib['href'] = htmlentities(ereg_replace('_task=[a-z]+', '_task='.$attrib['command'], $COMM_PATH));
T 1362     else if (in_array($attrib['command'], $a_static_commands))
1363       $attrib['href'] = htmlentities($COMM_PATH.'&_action='.$attrib['command']);
8c2e58 1364     }
T 1365
4e17e6 1366   // overwrite attributes
T 1367   if (!$attrib['href'])
1368     $attrib['href'] = '#';
1369
1370   if ($command)
1371     $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
1372     
1373   if ($command && $attrib['imageover'])
1374     {
1375     $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1376     $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1377     }
1378
c8c1e0 1379   if ($command && $attrib['imagesel'])
S 1380     {
1381     $attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1382     $attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1383     }
4e17e6 1384
T 1385   $out = '';
1386
1387   // generate image tag
1388   if ($attrib['type']=='image')
1389     {
1cded8 1390     $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
4e17e6 1391     $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
T 1392     $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
1393     if ($attrib['label'])
1394       $btn_content .= ' '.$attrib['label'];
1395     
c8c1e0 1396     $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
4e17e6 1397     }
T 1398   else if ($attrib['type']=='link')
1399     {
1400     $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
1401     $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
1402     }
1403   else if ($attrib['type']=='input')
1404     {
1405     $attrib['type'] = 'button';
1406     
1407     if ($attrib['label'])
1408       $attrib['value'] = $attrib['label'];
1409       
1410     $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
1411     $out = sprintf('<input%s disabled />', $attrib_str);
1412     }
1413
1414   // generate html code for button
1415   if ($btn_content)
1416     {
1417     $attrib_str = create_attrib_string($attrib, $link_attrib);
1418     $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1419     }
1420
1421   return $out;
1422   }
1423
1424
1425 function rcube_menu($attrib)
1426   {
1427   
1428   return '';
1429   }
1430
1431
1432
d1d2c4 1433 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
4e17e6 1434   {
T 1435   global $DB;
1436   
1437   // allow the following attributes to be added to the <table> tag
1438   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1439   
1440   $table = '<table' . $attrib_str . ">\n";
1441     
1442   // add table title
1443   $table .= "<thead><tr>\n";
1444
1445   foreach ($a_show_cols as $col)
1038d5 1446     $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
4e17e6 1447
T 1448   $table .= "</tr></thead>\n<tbody>\n";
1449   
1450   $c = 0;
d1d2c4 1451
S 1452   if (!is_array($table_data)) 
4e17e6 1453     {
d1d2c4 1454     while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
4e17e6 1455       {
d1d2c4 1456       $zebra_class = $c%2 ? 'even' : 'odd';
4e17e6 1457
d1d2c4 1458       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
S 1459
1460       // format each col
1461       foreach ($a_show_cols as $col)
1462         {
1463         $cont = rep_specialchars_output($sql_arr[$col]);
1464         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1465         }
1466
1467       $table .= "</tr>\n";
1468       $c++;
1469       }
1470     }
1471   else 
1472     {
1473     foreach ($table_data as $row_data)
1474       {
1475       $zebra_class = $c%2 ? 'even' : 'odd';
1476
1477       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1478
1479       // format each col
1480       foreach ($a_show_cols as $col)
1481         {
1482         $cont = rep_specialchars_output($row_data[$col]);
1483         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1484         }
1485
1486       $table .= "</tr>\n";
1487       $c++;
1488       }
4e17e6 1489     }
T 1490
1491   // complete message table
1492   $table .= "</tbody></table>\n";
1493   
1494   return $table;
1495   }
1496
1497
a0109c 1498 /**
S 1499  * Create an edit field for inclusion on a form
1500  * 
1501  * @param string col field name
1502  * @param string value field value
1503  * @param array attrib HTML element attributes for field
1504  * @param string type HTML element type (default 'text')
1505  * @return string HTML field definition
1506  */
4e17e6 1507 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
T 1508   {
1509   $fname = '_'.$col;
1510   $attrib['name'] = $fname;
1511   
1512   if ($type=='checkbox')
1513     {
1514     $attrib['value'] = '1';
1515     $input = new checkbox($attrib);
1516     }
1517   else if ($type=='textarea')
1518     {
1519     $attrib['cols'] = $attrib['size'];
1520     $input = new textarea($attrib);
1521     }
1522   else
1523     $input = new textfield($attrib);
1524
1525   // use value from post
597170 1526   if (!empty($_POST[$fname]))
4e17e6 1527     $value = $_POST[$fname];
T 1528
1529   $out = $input->show($value);
1530          
1531   return $out;
1532   }
1533
1534
fe79b1 1535 // compose a valid attribute string for HTML tags
4e17e6 1536 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
T 1537   {
1538   // allow the following attributes to be added to the <iframe> tag
1539   $attrib_str = '';
1540   foreach ($allowed_attribs as $a)
1541     if (isset($attrib[$a]))
fe79b1 1542       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
4e17e6 1543
T 1544   return $attrib_str;
1545   }
1546
1547
fe79b1 1548 // convert a HTML attribute string attributes to an associative array (name => value)
T 1549 function parse_attrib_string($str)
1550   {
1551   $attrib = array();
1552   preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str), $regs, PREG_SET_ORDER);
1553
1554   // convert attributes to an associative array (name => value)
1555   if ($regs)
1556     foreach ($regs as $attr)
1557       $attrib[strtolower($attr[1])] = $attr[2];
1558
1559   return $attrib;
1560   }
1561
4e17e6 1562
T 1563 function format_date($date, $format=NULL)
1564   {
1565   global $CONFIG, $sess_user_lang;
1566   
4647e1 1567   $ts = NULL;
T 1568   
4e17e6 1569   if (is_numeric($date))
T 1570     $ts = $date;
b076a4 1571   else if (!empty($date))
4647e1 1572     $ts = @strtotime($date);
T 1573     
1574   if (empty($ts))
b076a4 1575     return '';
4647e1 1576    
T 1577   // get user's timezone
1578   $tz = $CONFIG['timezone'];
1579   if ($CONFIG['dst_active'])
1580     $tz++;
4e17e6 1581
T 1582   // convert time to user's timezone
4647e1 1583   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
4e17e6 1584   
T 1585   // get current timestamp in user's timezone
1586   $now = time();  // local time
1587   $now -= (int)date('Z'); // make GMT time
4647e1 1588   $now += ($tz * 3600); // user's time
749b07 1589   $now_date = getdate();
4e17e6 1590
749b07 1591   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
T 1592   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 1593
30233b 1594   // define date format depending on current time  
749b07 1595   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
4e17e6 1596     return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
749b07 1597   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
4e17e6 1598     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 1599   else if (!$format)
1600     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1601
1602
1603   // parse format string manually in order to provide localized weekday and month names
1604   // an alternative would be to convert the date() format string to fit with strftime()
1605   $out = '';
1606   for($i=0; $i<strlen($format); $i++)
1607     {
1608     if ($format{$i}=='\\')  // skip escape chars
1609       continue;
1610     
1611     // write char "as-is"
1612     if ($format{$i}==' ' || $format{$i-1}=='\\')
1613       $out .= $format{$i};
1614     // weekday (short)
1615     else if ($format{$i}=='D')
1616       $out .= rcube_label(strtolower(date('D', $timestamp)));
1617     // weekday long
1618     else if ($format{$i}=='l')
1619       $out .= rcube_label(strtolower(date('l', $timestamp)));
1620     // month name (short)
1621     else if ($format{$i}=='M')
1622       $out .= rcube_label(strtolower(date('M', $timestamp)));
1623     // month name (long)
1624     else if ($format{$i}=='F')
1625       $out .= rcube_label(strtolower(date('F', $timestamp)));
1626     else
1627       $out .= date($format{$i}, $timestamp);
1628     }
1629   
1630   return $out;
1631   }
1632
1633
1634 // ************** functions delivering gui objects **************
1635
1636
1637
1638 function rcmail_message_container($attrib)
1639   {
1640   global $OUTPUT, $JS_OBJECT_NAME;
1641
1642   if (!$attrib['id'])
1643     $attrib['id'] = 'rcmMessageContainer';
1644
1645   // allow the following attributes to be added to the <table> tag
1646   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1647   $out = '<div' . $attrib_str . "></div>";
1648   
1649   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1650   
1651   return $out;
1652   }
1653
1654
15a9d1 1655 // return the IMAP username of the current session
T 1656 function rcmail_current_username($attrib)
1657   {
1658   global $DB;
1659   static $s_username;
1660
1661   // alread fetched  
1662   if (!empty($s_username))
1663     return $s_username;
1664
1665   // get e-mail address form default identity
1666   $sql_result = $DB->query("SELECT email AS mailto
1667                             FROM ".get_table_name('identities')."
1668                             WHERE  user_id=?
1669                             AND    standard=1
1670                             AND    del<>1",
1671                             $_SESSION['user_id']);
1672                                    
1673   if ($DB->num_rows($sql_result))
1674     {
1675     $sql_arr = $DB->fetch_assoc($sql_result);
1676     $s_username = $sql_arr['mailto'];
1677     }
1678   else if (strstr($_SESSION['username'], '@'))
1679     $s_username = $_SESSION['username'];
1680   else
1681     $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1682
1683   return $s_username;
1684   }
1685
1686
8cb245 1687 // return the mail domain configured for the given host
T 1688 function rcmail_mail_domain($host)
1689   {
1690   global $CONFIG;
1691
1692   $domain = $host;
1693   if (is_array($CONFIG['mail_domain']))
1694     {
1695     if (isset($CONFIG['mail_domain'][$host]))
1696       $domain = $CONFIG['mail_domain'][$host];
1697     }
1698   else if (!empty($CONFIG['mail_domain']))
1699     $domain = $CONFIG['mail_domain'];
1700
1701   return $domain;
1702   }
1703
1704
4e17e6 1705 // return code for the webmail login form
T 1706 function rcmail_login_form($attrib)
1707   {
1708   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1709   
1710   $labels = array();
1711   $labels['user'] = rcube_label('username');
1712   $labels['pass'] = rcube_label('password');
1713   $labels['host'] = rcube_label('server');
1714   
66e2bf 1715   $input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30));
T 1716   $input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
4e17e6 1717   $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
T 1718     
1719   $fields = array();
ea7c46 1720   $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
4e17e6 1721   $fields['pass'] = $input_pass->show();
T 1722   $fields['action'] = $input_action->show();
1723   
1724   if (is_array($CONFIG['default_host']))
1725     {
66e2bf 1726     $select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
42b113 1727     
T 1728     foreach ($CONFIG['default_host'] as $key => $value)
1729       $select_host->add($value, (is_numeric($key) ? $value : $key));
1730       
4e17e6 1731     $fields['host'] = $select_host->show($_POST['_host']);
T 1732     }
1733   else if (!strlen($CONFIG['default_host']))
1734     {
66e2bf 1735     $input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
4e17e6 1736     $fields['host'] = $input_host->show($_POST['_host']);
T 1737     }
1738
1739   $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1740   $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1741   $form_end = !strlen($attrib['form']) ? '</form>' : '';
1742   
1743   if ($fields['host'])
1744     $form_host = <<<EOF
1745     
1746 </tr><tr>
1747
66e2bf 1748 <td class="title"><label for="rcmloginhost">$labels[host]</label></td>
4e17e6 1749 <td>$fields[host]</td>
T 1750
1751 EOF;
1752
1753   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1754   
1755   $out = <<<EOF
1756 $form_start
1757 $SESS_HIDDEN_FIELD
1758 $fields[action]
1759 <table><tr>
1760
66e2bf 1761 <td class="title"><label for="rcmloginuser">$labels[user]</label></td>
4e17e6 1762 <td>$fields[user]</td>
T 1763
1764 </tr><tr>
1765
66e2bf 1766 <td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
4e17e6 1767 <td>$fields[pass]</td>
T 1768 $form_host
1769 </tr></table>
1770 $form_end
1771 EOF;
1772
1773   return $out;
1774   }
1775
1776
1cded8 1777 function rcmail_charset_selector($attrib)
T 1778   {
13c1af 1779   global $OUTPUT;
T 1780   
1cded8 1781   // pass the following attributes to the form class
T 1782   $field_attrib = array('name' => '_charset');
1783   foreach ($attrib as $attr => $value)
1784     if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1785       $field_attrib[$attr] = $value;
1786       
1787   $charsets = array(
1788     'US-ASCII'     => 'ASCII (English)',
f88d41 1789     'EUC-JP'       => 'EUC-JP (Japanese)',
1cded8 1790     'EUC-KR'       => 'EUC-KR (Korean)',
T 1791     'BIG5'         => 'BIG5 (Chinese)',
1792     'GB2312'       => 'GB2312 (Chinese)',
f88d41 1793     'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1cded8 1794     'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
T 1795     'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1796     'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1797     'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1798     'Windows-1251' => 'Windows-1251 (Cyrillic)',
1799     'Windows-1252' => 'Windows-1252 (Western)',
1800     'Windows-1255' => 'Windows-1255 (Hebrew)',
1801     'Windows-1256' => 'Windows-1256 (Arabic)',
1802     'Windows-1257' => 'Windows-1257 (Baltic)',
1803     'UTF-8'        => 'UTF-8'
1804     );
1805
1806   $select = new select($field_attrib);
1807   $select->add(array_values($charsets), array_keys($charsets));
1808   
13c1af 1809   $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
1cded8 1810   return $select->show($set);
T 1811   }
1812
1813
c39957 1814 /****** debugging functions ********/
T 1815
1816
1817 /**
1818  * Print or write debug messages
1819  *
1820  * @param mixed Debug message or data
1821  */
1822 function console($msg)
1823   {
8d4bcd 1824   if (!is_string($msg))
c39957 1825     $msg = var_export($msg, true);
T 1826
1827   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1828     write_log('console', $msg);
1829   else if ($GLOBALS['REMOTE_REQUEST'])
1830     print "/*\n $msg \n*/\n";
1831   else
1832     {
1833     print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1834     print $msg;
1835     print "</pre></div>\n";
1836     }
1837   }
1838
1839
1840 /**
1841  * Append a line to a logfile in the logs directory.
1842  * Date will be added automatically to the line.
1843  *
1844  * @param $name Name of logfile
1845  * @param $line Line to append
1846  */
1847 function write_log($name, $line)
1848   {
1849   global $CONFIG;
e170b4 1850
T 1851   if (!is_string($line))
1852     $line = var_export($line, true);
c39957 1853   
T 1854   $log_entry = sprintf("[%s]: %s\n",
1855                  date("d-M-Y H:i:s O", mktime()),
1856                  $line);
1857                  
1858   if (empty($CONFIG['log_dir']))
1859     $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1860       
1861   // try to open specific log file for writing
1862   if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))    
1863     {
1864     fwrite($fp, $log_entry);
1865     fclose($fp);
1866     }
1867   }
1868
cc9570 1869
15a9d1 1870 function rcube_timer()
T 1871   {
1872   list($usec, $sec) = explode(" ", microtime());
1873   return ((float)$usec + (float)$sec);
1874   }
1875   
1876
1877 function rcube_print_time($timer, $label='Timer')
1878   {
1879   static $print_count = 0;
1880   
1881   $print_count++;
1882   $now = rcube_timer();
1883   $diff = $now-$timer;
1884   
1885   if (empty($label))
1886     $label = 'Timer '.$print_count;
1887   
1888   console(sprintf("%s: %0.4f sec", $label, $diff));
1889   }
1890
d1d2c4 1891 ?>