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