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