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