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