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