thomascube
2006-02-19 f88d417c96119b8e50297b930b14fe6ff9a1c5ed
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   
f88d41 82     $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
4e17e6 83   // create session and set session vars
T 84   if (!$_SESSION['client_id'])
85     {
86     $_SESSION['client_id'] = $sess_id;
0af7e8 87     $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
4e17e6 88     $_SESSION['auth_time'] = mktime();
T 89     $_SESSION['auth'] = rcmail_auth_hash($sess_id, $_SESSION['auth_time']);
90     unset($GLOBALS['_auth']);
91     }
92
93   // set session vars global
94   $sess_auth = $_SESSION['auth'];
0af7e8 95   $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
4e17e6 96
T 97
98   // overwrite config with user preferences
99   if (is_array($_SESSION['user_prefs']))
100     $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
101
102
103   // reset some session parameters when changing task
104   if ($_SESSION['task'] != $task)
105     unset($_SESSION['page']);
106
107   // set current task to session
108   $_SESSION['task'] = $task;
109
110
111   // create IMAP object
112   if ($task=='mail')
113     rcmail_imap_init();
114
115
116   // set localization
117   if ($CONFIG['locale_string'])
118     setlocale(LC_ALL, $CONFIG['locale_string']);
119   else if ($sess_user_lang)
120     setlocale(LC_ALL, $sess_user_lang);
121
122
123   register_shutdown_function('rcmail_shutdown');
124   }
125   
126
127 // create authorization hash
128 function rcmail_auth_hash($sess_id, $ts)
129   {
130   global $CONFIG;
131   
132   $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
133                          $sess_id,
134                          $ts,
135                          $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
136                          $_SERVER['HTTP_USER_AGENT']);
137   
138   if (function_exists('sha1'))
139     return sha1($auth_string);
140   else
141     return md5($auth_string);
142   }
143
144
145
146 // create IMAP object and connect to server
147 function rcmail_imap_init($connect=FALSE)
148   {
1cded8 149   global $CONFIG, $DB, $IMAP;
6dc026 150
1cded8 151   $IMAP = new rcube_imap($DB);
15a9d1 152   $IMAP->debug_level = $CONFIG['debug_level'];
T 153   $IMAP->skip_deleted = $CONFIG['skip_deleted'];
154
4e17e6 155
7902df 156   // connect with stored session data
T 157   if ($connect)
158     {
159     if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
160       show_message('imaperror', 'error');
161       
162     rcmail_set_imap_prop();
163     }
164
6dc026 165   // enable caching of imap data
T 166   if ($CONFIG['enable_caching']===TRUE)
167     $IMAP->set_caching(TRUE);
168
4e17e6 169   if (is_array($CONFIG['default_imap_folders']))
T 170     $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
171
172   // set pagesize from config
173   if (isset($CONFIG['pagesize']))
174     $IMAP->set_pagesize($CONFIG['pagesize']);
7902df 175   }
4e17e6 176
T 177
7902df 178 // set root dir and last stored mailbox
T 179 // this must be done AFTER connecting to the server
180 function rcmail_set_imap_prop()
181   {
182   global $CONFIG, $IMAP;
183
184   // set root dir from config
185   if (strlen($CONFIG['imap_root']))
186     $IMAP->set_rootdir($CONFIG['imap_root']);
187
188   if (strlen($_SESSION['mbox']))
189     $IMAP->set_mailbox($_SESSION['mbox']);
190     
191   if (isset($_SESSION['page']))
192     $IMAP->set_page($_SESSION['page']);
4e17e6 193   }
T 194
195
196 // do these things on script shutdown
197 function rcmail_shutdown()
198   {
199   global $IMAP;
200   
201   if (is_object($IMAP))
202     {
203     $IMAP->close();
204     $IMAP->write_cache();
205     }
0af7e8 206     
T 207   // before closing the database connection, write session data
208   session_write_close();
4e17e6 209   }
T 210
211
212 // destroy session data and remove cookie
213 function rcmail_kill_session()
214   {
215 /* $sess_name = session_name();
216   if (isset($_COOKIE[$sess_name]))
217    setcookie($sess_name, '', time()-42000, '/');
218 */
219   $_SESSION = array();
220   session_destroy();
221   }
222
223
224 // return correct name for a specific database table
225 function get_table_name($table)
226   {
227   global $CONFIG;
228   
229   // return table name if configured
230   $config_key = 'db_table_'.$table;
231
232   if (strlen($CONFIG[$config_key]))
233     return $CONFIG[$config_key];
234   
235   return $table;
236   }
237
238
1cded8 239 // return correct name for a specific database sequence
T 240 // (used for Postres only)
241 function get_sequence_name($sequence)
242   {
243   global $CONFIG;
244   
245   // return table name if configured
246   $config_key = 'db_sequence_'.$sequence;
247
248   if (strlen($CONFIG[$config_key]))
249     return $CONFIG[$config_key];
250   
251   return $table;
252   }
0af7e8 253
T 254
255 // check the given string and returns language properties
256 function rcube_language_prop($lang, $prop='lang')
257   {
258   global $INSTLL_PATH;
259   static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
260
261   if (empty($rcube_languages))
262     @include($INSTLL_PATH.'program/localization/index.inc');
263     
264   // check if we have an alias for that language
265   if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
266     $lang = $rcube_language_aliases[$lang];
267     
268   // try the first two chars
f88d41 269   if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
0af7e8 270     {
T 271     $lang = substr($lang, 0, 2);
272     $lang = rcube_language_prop($lang);
273     }
274
275   if (!isset($rcube_languages[$lang]))
276     $lang = 'en_US';
277
278   // language has special charset configured
279   if (isset($rcube_charsets[$lang]))
280     $charset = $rcube_charsets[$lang];
281   else
282     $charset = 'UTF-8';    
f88d41 283
0af7e8 284
T 285   if ($prop=='charset')
286     return $charset;
287   else
288     return $lang;
289   }
1cded8 290   
4e17e6 291
T 292 // init output object for GUI and add common scripts
293 function load_gui()
294   {
3f9edb 295   global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
4e17e6 296
T 297   // init output page
298   $OUTPUT = new rcube_html_page();
299   
300   // add common javascripts
301   $javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
302   $javascript .= "$JS_OBJECT_NAME.set_env('comm_path', '$COMM_PATH');\n";
303
597170 304   if (!empty($GLOBALS['_framed']))
4e17e6 305     $javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
7cc38e 306     
4e17e6 307   $OUTPUT->add_script($javascript);
T 308   $OUTPUT->include_script('program/js/common.js');
7cc38e 309   $OUTPUT->include_script('program/js/app.js');
T 310
311   // set user-selected charset
5bc8cb 312   if (!empty($CONFIG['charset']))
7cc38e 313     $OUTPUT->set_charset($CONFIG['charset']);
T 314   else
315     rcmail_set_locale($sess_user_lang);
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     {
354     if (!mb_language(strtok($lang, "_")))
355       $MBSTRING = FALSE;   //  unsupport language
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   {
15a9d1 665   static $s_header_sent = FALSE;
T 666   
667   if (!$s_header_sent)
668     {
669     $s_header_sent = TRUE;
670     send_nocacheing_headers();
671     header('Content-Type: application/x-javascript');
672     print '/** remote response ['.date('d/M/Y h:i:s O')."] **/\n";
673     }
4e17e6 674
15a9d1 675   // send response code
2a20b0 676   print rcube_charset_convert($js_code, 'UTF-8', $GLOBALS['CHARSET']);
15a9d1 677
T 678   if ($flush)  // flush the output buffer
679     flush();
680   else         // terminate script
681     exit;
4e17e6 682   }
T 683
684
9fee0e 685 // read directory program/localization/ and return a list of available languages
T 686 function rcube_list_languages()
687   {
688   global $CONFIG, $INSTALL_PATH;
689   static $sa_languages = array();
690
691   if (!sizeof($sa_languages))
692     {
7cc38e 693     @include($INSTLL_PATH.'program/localization/index.inc');
9fee0e 694
T 695     if ($dh = @opendir($INSTLL_PATH.'program/localization'))
696       {
697       while (($name = readdir($dh)) !== false)
698         {
699         if ($name{0}=='.' || !is_dir($INSTLL_PATH.'program/localization/'.$name))
700           continue;
701
702         if ($label = $rcube_languages[$name])
703           $sa_languages[$name] = $label ? $label : $name;
704         }
705       closedir($dh);
706       }
707     }
708   return $sa_languages;
709   }
710
4e17e6 711
10a699 712 // add a localized label to the client environment
T 713 function rcube_add_label()
714   {
715   global $OUTPUT, $JS_OBJECT_NAME;
716   
717   $arg_list = func_get_args();
718   foreach ($arg_list as $i => $name)
719     $OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
720                                 $JS_OBJECT_NAME,
721                                 $name,
722                                 rep_specialchars_output(rcube_label($name), 'js')));  
1cded8 723   }
T 724
725
726 // remove temp files of a session
727 function rcmail_clear_session_temp($sess_id)
728   {
729   global $CONFIG;
730
731   $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '');
732   $cache_dir = $temp_dir.$sess_id;
733
734   if (is_dir($cache_dir))
735     {
736     clear_directory($cache_dir);
737     rmdir($cache_dir);
738     }  
739   }
740
741
cc9570 742 // remove all expired message cache records
T 743 function rcmail_message_cache_gc()
744   {
745   global $DB, $CONFIG;
746   
747   // no cache lifetime configured
748   if (empty($CONFIG['message_cache_lifetime']))
749     return;
750   
751   // get target timestamp
752   $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
753   
754   $DB->query("DELETE FROM ".get_table_name('messages')."
755              WHERE  created < ".$DB->fromunixtime($ts));
756   }
757
1cded8 758
3f9edb 759 // convert a string from one charset to another
T 760 // this function is not complete and not tested well
761 function rcube_charset_convert($str, $from, $to=NULL)
0af7e8 762   {
f88d41 763   global $MBSTRING, $MBSTRING_ENCODING;
T 764
83dbb7 765   $from = strtoupper($from);
T 766   $to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
f88d41 767
3f9edb 768   if ($from==$to)
T 769     return $str;
83dbb7 770     
f88d41 771   // convert charset using mbstring module  
T 772   if ($MBSTRING)
773     {
774     $to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
775     $from = $from=="UTF-7" ? "UTF7-IMAP": $from;
776     
777     if (in_array($to, $MBSTRING_ENCODING) && in_array($from, $MBSTRING_ENCODING))
778       return mb_convert_encoding($str, $to, $from);
83dbb7 779     }
f88d41 780
T 781   // convert charset using iconv module  
782   if (function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7')
783     return iconv($from, $to, $str);
58e360 784
T 785   $conv = new utf8();
786
83dbb7 787   // convert string to UTF-8
T 788   if ($from=='UTF-7')
789     $str = rcube_charset_convert(UTF7DecodeString($str), 'ISO-8859-1');
790   else if ($from=='ISO-8859-1' && function_exists('utf8_encode'))
791     $str = utf8_encode($str);
792   else if ($from!='UTF-8')
793     {
58e360 794     $conv->loadCharset($from);
83dbb7 795     $str = $conv->strToUtf8($str);
T 796     }
0af7e8 797
3f9edb 798   // encode string for output
83dbb7 799   if ($to=='UTF-7')
3f9edb 800     return UTF7EncodeString($str);
83dbb7 801   else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
T 802     return utf8_decode($str);
803   else if ($to!='UTF-8')
804     {
58e360 805     $conv->loadCharset($to);
83dbb7 806     return $conv->utf8ToStr($str);
T 807     }
3f9edb 808
83dbb7 809   // return UTF-8 string
3f9edb 810   return $str;
0af7e8 811   }
3f9edb 812
0af7e8 813
T 814
1cded8 815 // replace specials characters to a specific encoding type
T 816 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
817   {
3f9edb 818   global $OUTPUT_TYPE, $OUTPUT;
1cded8 819   static $html_encode_arr, $js_rep_table, $rtf_rep_table, $xml_rep_table;
T 820
821   if (!$enctype)
822     $enctype = $GLOBALS['OUTPUT_TYPE'];
823
824   // convert nbsps back to normal spaces if not html
825   if ($enctype!='html')
826     $str = str_replace(chr(160), ' ', $str);
827
828   // encode for plaintext
829   if ($enctype=='text')
830     return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
831
832   // encode for HTML output
833   if ($enctype=='html')
834     {
835     if (!$html_encode_arr)
836       {
0af7e8 837       $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);        
1cded8 838       unset($html_encode_arr['?']);
T 839       unset($html_encode_arr['&']);
840       }
841
842     $ltpos = strpos($str, '<');
843     $encode_arr = $html_encode_arr;
844
845     // don't replace quotes and html tags
846     if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
847       {
848       unset($encode_arr['"']);
849       unset($encode_arr['<']);
850       unset($encode_arr['>']);
851       }
852     else if ($mode=='remove')
853       $str = strip_tags($str);
854       
855     $out = strtr($str, $encode_arr);
0af7e8 856       
1cded8 857     return $newlines ? nl2br($out) : $out;
T 858     }
859
860
861   if ($enctype=='url')
862     return rawurlencode($str);
863
864
865   // if the replace tables for RTF, XML and JS are not yet defined
866   if (!$js_rep_table)
867     {
868     $js_rep_table = $rtf_rep_table = $xml_rep_table = array();
88375f 869     $xml_rep_table['&'] = '&amp;';
1cded8 870
T 871     for ($c=160; $c<256; $c++)  // can be increased to support more charsets
872       {
873       $hex = dechex($c);
874       $rtf_rep_table[Chr($c)] = "\\'$hex";
875       $xml_rep_table[Chr($c)] = "&#$c;";
876       
3f9edb 877       if ($OUTPUT->get_charset()=='ISO-8859-1')
1cded8 878         $js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
T 879       }
880
881     $js_rep_table['"'] = sprintf("\u%s%s", str_repeat('0', 4-strlen(dechex(34))), dechex(34));
882     $xml_rep_table['"'] = '&quot;';
883     }
884
885   // encode for RTF
886   if ($enctype=='xml')
887     return strtr($str, $xml_rep_table);
888
889   // encode for javascript use
890   if ($enctype=='js')
891     return preg_replace(array("/\r\n/", '/"/', "/([^\\\])'/"), array('\n', '\"', "$1\'"), strtr($str, $js_rep_table));
892
893   // encode for RTF
894   if ($enctype=='rtf')
895     return preg_replace("/\r\n/", "\par ", strtr($str, $rtf_rep_table));
896
897   // no encoding given -> return original string
898   return $str;
10a699 899   }
T 900
901
4e17e6 902
T 903 // ************** template parsing and gui functions **************
904
905
906 // return boolean if a specific template exists
907 function template_exists($name)
908   {
909   global $CONFIG, $OUTPUT;
910   $skin_path = $CONFIG['skin_path'];
911
912   // check template file
913   return is_file("$skin_path/templates/$name.html");
914   }
915
916
917 // get page template an replace variable
918 // similar function as used in nexImage
919 function parse_template($name='main', $exit=TRUE)
920   {
921   global $CONFIG, $OUTPUT;
922   $skin_path = $CONFIG['skin_path'];
923
924   // read template file
925   $templ = '';
926   $path = "$skin_path/templates/$name.html";
927
928   if($fp = @fopen($path, 'r'))
929     {
930     $templ = fread($fp, filesize($path));
931     fclose($fp);
932     }
933   else
934     {
935     raise_error(array('code' => 500,
936                       'type' => 'php',
937                       'line' => __LINE__,
938                       'file' => __FILE__,
939                       'message' => "Error loading template for '$name'"), TRUE, TRUE);
940     return FALSE;
941     }
942
943
944   // parse for specialtags
945   $output = parse_rcube_xml($templ);
946   
947   $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
948
949   if ($exit)
950     exit;
951   }
952
953
954
955 // replace all strings ($varname) with the content of the according global variable
956 function parse_with_globals($input)
957   {
b595c9 958   $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
4e17e6 959   $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
T 960   return $output;
961   }
962
963
964
965 function parse_rcube_xml($input)
966   {
967   $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
968   return $output;
969   }
970
971
972 function rcube_xml_command($command, $str_attrib, $a_attrib=NULL)
973   {
0af7e8 974   global $IMAP, $CONFIG, $OUTPUT;
4e17e6 975   
T 976   $attrib = array();
977   $command = strtolower($command);
978
979   preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str_attrib), $regs, PREG_SET_ORDER);
980
981   // convert attributes to an associative array (name => value)
982   if ($regs)
983     foreach ($regs as $attr)
984       $attrib[strtolower($attr[1])] = $attr[2];
985   else if ($a_attrib)
986     $attrib = $a_attrib;
987
988   // execute command
989   switch ($command)
990     {
991     // return a button
992     case 'button':
993       if ($attrib['command'])
994         return rcube_button($attrib);
995       break;
996
997     // show a label
998     case 'label':
999       if ($attrib['name'] || $attrib['command'])
7dd801 1000         return rep_specialchars_output(rcube_label($attrib));
4e17e6 1001       break;
T 1002
1003     // create a menu item
1004     case 'menu':
1005       if ($attrib['command'] && $attrib['group'])
1006         rcube_menu($attrib);
1007       break;
1008
1009     // include a file 
1010     case 'include':
1011       $path = realpath($CONFIG['skin_path'].$attrib['file']);
1012       
1013       if($fp = @fopen($path, 'r'))
1014         {
1015         $incl = fread($fp, filesize($path));
1016         fclose($fp);        
1017         return parse_rcube_xml($incl);
1018         }
1019       break;
1020
1021     // return code for a specific application object
1022     case 'object':
1023       $object = strtolower($attrib['name']);
1024
1cded8 1025       $object_handlers = array(
15a9d1 1026         // GENERAL
T 1027         'loginform' => 'rcmail_login_form',
1028         'username'  => 'rcmail_current_username',
1029         
1cded8 1030         // MAIL
T 1031         'mailboxlist' => 'rcmail_mailbox_list',
15a9d1 1032         'message' => 'rcmail_message_container',
1cded8 1033         'messages' => 'rcmail_message_list',
T 1034         'messagecountdisplay' => 'rcmail_messagecount_display',
58e360 1035         'quotadisplay' => 'rcmail_quota_display',
1cded8 1036         'messageheaders' => 'rcmail_message_headers',
T 1037         'messagebody' => 'rcmail_message_body',
1038         'messageattachments' => 'rcmail_message_attachments',
1039         'blockedobjects' => 'rcmail_remote_objects_msg',
1040         'messagecontentframe' => 'rcmail_messagecontent_frame',
1041         'messagepartframe' => 'rcmail_message_part_frame',
1042         'messagepartcontrols' => 'rcmail_message_part_controls',
1043         'composeheaders' => 'rcmail_compose_headers',
1044         'composesubject' => 'rcmail_compose_subject',
1045         'composebody' => 'rcmail_compose_body',
1046         'composeattachmentlist' => 'rcmail_compose_attachment_list',
1047         'composeattachmentform' => 'rcmail_compose_attachment_form',
1048         'composeattachment' => 'rcmail_compose_attachment_field',
1049         'priorityselector' => 'rcmail_priority_selector',
1050         'charsetselector' => 'rcmail_charset_selector',
1051         
1052         // ADDRESS BOOK
1053         'addresslist' => 'rcmail_contacts_list',
1054         'addressframe' => 'rcmail_contact_frame',
1055         'recordscountdisplay' => 'rcmail_rowcount_display',
1056         'contactdetails' => 'rcmail_contact_details',
1057         'contacteditform' => 'rcmail_contact_editform',
d1d2c4 1058         'ldappublicsearch' => 'rcmail_ldap_public_search_form',
S 1059         'ldappublicaddresslist' => 'rcmail_ldap_public_list',
1cded8 1060
T 1061         // USER SETTINGS
1062         'userprefs' => 'rcmail_user_prefs_form',
1063         'itentitieslist' => 'rcmail_identities_list',
1064         'identityframe' => 'rcmail_identity_frame',
1065         'identityform' => 'rcube_identity_form',
1066         'foldersubscription' => 'rcube_subscription_form',
1067         'createfolder' => 'rcube_create_folder_form',
1068         'composebody' => 'rcmail_compose_body'
1069       );
1070
1071       
1072       // execute object handler function
15a9d1 1073       if ($object_handlers[$object] && function_exists($object_handlers[$object]))
1cded8 1074         return call_user_func($object_handlers[$object], $attrib);
4e17e6 1075
T 1076       else if ($object=='pagetitle')
1077         {
1078         $task = $GLOBALS['_task'];
15a9d1 1079         $title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
T 1080         
4e17e6 1081         if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
15a9d1 1082           $title .= $GLOBALS['MESSAGE']['subject'];
4e17e6 1083         else if (isset($GLOBALS['PAGE_TITLE']))
15a9d1 1084           $title .= $GLOBALS['PAGE_TITLE'];
4e17e6 1085         else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
3f9edb 1086           $title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
4e17e6 1087         else
15a9d1 1088           $title .= $task;
T 1089           
1090         return rep_specialchars_output($title, 'html', 'all');
4e17e6 1091         }
T 1092
1093       break;
1094     }
1095
1096   return '';
1097   }
1098
1099
1100 // create and register a button
1101 function rcube_button($attrib)
1102   {
14eafe 1103   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER;
4e17e6 1104   static $sa_buttons = array();
T 1105   static $s_button_count = 100;
1106   
1107   $skin_path = $CONFIG['skin_path'];
1108   
1109   if (!($attrib['command'] || $attrib['name']))
1110     return '';
1111
1112   // try to find out the button type
1113   if ($attrib['type'])
1114     $attrib['type'] = strtolower($attrib['type']);
1115   else
1116     $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imagect']) ? 'image' : 'link';
1117   
1118   
1119   $command = $attrib['command'];
1120   
1121   // take the button from the stack
1122   if($attrib['name'] && $sa_buttons[$attrib['name']])
1123     $attrib = $sa_buttons[$attrib['name']];
1124
1125   // add button to button stack
1126   else if($attrib['image'] || $arg['imagect'] || $attrib['imagepas'] || $attrib['class'])
1127     {
1128     if(!$attrib['name'])
1129       $attrib['name'] = $command;
1130
1131     if (!$attrib['image'])
1132       $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1133
1134     $sa_buttons[$attrib['name']] = $attrib;
1135     }
1136
1137   // get saved button for this command/name
1138   else if ($command && $sa_buttons[$command])
1139     $attrib = $sa_buttons[$command];
1140
1141   //else
1142   //  return '';
1143
1144
1145   // set border to 0 because of the link arround the button
1146   if ($attrib['type']=='image' && !isset($attrib['border']))
1147     $attrib['border'] = 0;
1148     
1149   if (!$attrib['id'])
1150     $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
1151
1152   // get localized text for labels and titles
1153   if ($attrib['title'])
1154     $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
1155   if ($attrib['label'])
1156     $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
1157
1158   if ($attrib['alt'])
1159     $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
14eafe 1160
T 1161   // set title to alt attribute for IE browsers
1162   if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
1163     {
1164     $attrib['alt'] = $attrib['title'];
1165     unset($attrib['title']);
1166     }
1167
4e17e6 1168   // add empty alt attribute for XHTML compatibility
T 1169   if (!isset($attrib['alt']))
1170     $attrib['alt'] = '';
1171
1172
1173   // register button in the system
1174   if ($attrib['command'])
1175     $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
1176                                 $JS_OBJECT_NAME,
1177                                 $command,
1178                                 $attrib['id'],
1179                                 $attrib['type'],
1180                                 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
1181                                 $attirb['imagesel'] ? $skin_path.$attirb['imagesel'] : $attrib['classsel'],
1182                                 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
1183
1184   // overwrite attributes
1185   if (!$attrib['href'])
1186     $attrib['href'] = '#';
1187
1188   if ($command)
1189     $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
1190     
1191   if ($command && $attrib['imageover'])
1192     {
1193     $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1194     $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1195     }
1196
1197
1198   $out = '';
1199
1200   // generate image tag
1201   if ($attrib['type']=='image')
1202     {
1cded8 1203     $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
4e17e6 1204     $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
T 1205     $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
1206     if ($attrib['label'])
1207       $btn_content .= ' '.$attrib['label'];
1208     
1209     $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'title');
1210     }
1211   else if ($attrib['type']=='link')
1212     {
1213     $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
1214     $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
1215     }
1216   else if ($attrib['type']=='input')
1217     {
1218     $attrib['type'] = 'button';
1219     
1220     if ($attrib['label'])
1221       $attrib['value'] = $attrib['label'];
1222       
1223     $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
1224     $out = sprintf('<input%s disabled />', $attrib_str);
1225     }
1226
1227   // generate html code for button
1228   if ($btn_content)
1229     {
1230     $attrib_str = create_attrib_string($attrib, $link_attrib);
1231     $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1232     }
1233
1234   return $out;
1235   }
1236
1237
1238 function rcube_menu($attrib)
1239   {
1240   
1241   return '';
1242   }
1243
1244
1245
d1d2c4 1246 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
4e17e6 1247   {
T 1248   global $DB;
1249   
1250   // allow the following attributes to be added to the <table> tag
1251   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1252   
1253   $table = '<table' . $attrib_str . ">\n";
1254     
1255   // add table title
1256   $table .= "<thead><tr>\n";
1257
1258   foreach ($a_show_cols as $col)
1038d5 1259     $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
4e17e6 1260
T 1261   $table .= "</tr></thead>\n<tbody>\n";
1262   
1263   $c = 0;
d1d2c4 1264
S 1265   if (!is_array($table_data)) 
4e17e6 1266     {
d1d2c4 1267     while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
4e17e6 1268       {
d1d2c4 1269       $zebra_class = $c%2 ? 'even' : 'odd';
4e17e6 1270
d1d2c4 1271       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
S 1272
1273       // format each col
1274       foreach ($a_show_cols as $col)
1275         {
1276         $cont = rep_specialchars_output($sql_arr[$col]);
1277         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1278         }
1279
1280       $table .= "</tr>\n";
1281       $c++;
1282       }
1283     }
1284   else 
1285     {
1286     foreach ($table_data as $row_data)
1287       {
1288       $zebra_class = $c%2 ? 'even' : 'odd';
1289
1290       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1291
1292       // format each col
1293       foreach ($a_show_cols as $col)
1294         {
1295         $cont = rep_specialchars_output($row_data[$col]);
1296         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1297         }
1298
1299       $table .= "</tr>\n";
1300       $c++;
1301       }
4e17e6 1302     }
T 1303
1304   // complete message table
1305   $table .= "</tbody></table>\n";
1306   
1307   return $table;
1308   }
1309
1310
1311
1312 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1313   {
1314   $fname = '_'.$col;
1315   $attrib['name'] = $fname;
1316   
1317   if ($type=='checkbox')
1318     {
1319     $attrib['value'] = '1';
1320     $input = new checkbox($attrib);
1321     }
1322   else if ($type=='textarea')
1323     {
1324     $attrib['cols'] = $attrib['size'];
1325     $input = new textarea($attrib);
1326     }
1327   else
1328     $input = new textfield($attrib);
1329
1330   // use value from post
597170 1331   if (!empty($_POST[$fname]))
4e17e6 1332     $value = $_POST[$fname];
T 1333
1334   $out = $input->show($value);
1335          
1336   return $out;
1337   }
1338
1339
1340 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1341   {
1342   // allow the following attributes to be added to the <iframe> tag
1343   $attrib_str = '';
1344   foreach ($allowed_attribs as $a)
1345     if (isset($attrib[$a]))
1346       $attrib_str .= sprintf(' %s="%s"', $a, $attrib[$a]);
1347
1348   return $attrib_str;
1349   }
1350
1351
1352
1353 function format_date($date, $format=NULL)
1354   {
1355   global $CONFIG, $sess_user_lang;
1356   
1357   if (is_numeric($date))
1358     $ts = $date;
b076a4 1359   else if (!empty($date))
4e17e6 1360     $ts = strtotime($date);
b076a4 1361   else
T 1362     return '';
4e17e6 1363
T 1364   // convert time to user's timezone
1365   $timestamp = $ts - date('Z', $ts) + ($CONFIG['timezone'] * 3600);
1366   
1367   // get current timestamp in user's timezone
1368   $now = time();  // local time
1369   $now -= (int)date('Z'); // make GMT time
1370   $now += ($CONFIG['timezone'] * 3600); // user's time
749b07 1371   $now_date = getdate();
4e17e6 1372
749b07 1373   //$day_secs = 60*((int)date('H', $now)*60 + (int)date('i', $now));
T 1374   //$week_secs = 60 * 60 * 24 * 7;
1375   //$diff = $now - $timestamp;
1376   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1377   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 1378
30233b 1379   // define date format depending on current time  
749b07 1380   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
4e17e6 1381     return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
749b07 1382   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
4e17e6 1383     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 1384   else if (!$format)
1385     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1386
1387
1388   // parse format string manually in order to provide localized weekday and month names
1389   // an alternative would be to convert the date() format string to fit with strftime()
1390   $out = '';
1391   for($i=0; $i<strlen($format); $i++)
1392     {
1393     if ($format{$i}=='\\')  // skip escape chars
1394       continue;
1395     
1396     // write char "as-is"
1397     if ($format{$i}==' ' || $format{$i-1}=='\\')
1398       $out .= $format{$i};
1399     // weekday (short)
1400     else if ($format{$i}=='D')
1401       $out .= rcube_label(strtolower(date('D', $timestamp)));
1402     // weekday long
1403     else if ($format{$i}=='l')
1404       $out .= rcube_label(strtolower(date('l', $timestamp)));
1405     // month name (short)
1406     else if ($format{$i}=='M')
1407       $out .= rcube_label(strtolower(date('M', $timestamp)));
1408     // month name (long)
1409     else if ($format{$i}=='F')
1410       $out .= rcube_label(strtolower(date('F', $timestamp)));
1411     else
1412       $out .= date($format{$i}, $timestamp);
1413     }
1414   
1415   return $out;
1416   }
1417
1418
1419 // ************** functions delivering gui objects **************
1420
1421
1422
1423 function rcmail_message_container($attrib)
1424   {
1425   global $OUTPUT, $JS_OBJECT_NAME;
1426
1427   if (!$attrib['id'])
1428     $attrib['id'] = 'rcmMessageContainer';
1429
1430   // allow the following attributes to be added to the <table> tag
1431   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1432   $out = '<div' . $attrib_str . "></div>";
1433   
1434   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1435   
1436   return $out;
1437   }
1438
1439
15a9d1 1440 // return the IMAP username of the current session
T 1441 function rcmail_current_username($attrib)
1442   {
1443   global $DB;
1444   static $s_username;
1445
1446   // alread fetched  
1447   if (!empty($s_username))
1448     return $s_username;
1449
1450   // get e-mail address form default identity
1451   $sql_result = $DB->query("SELECT email AS mailto
1452                             FROM ".get_table_name('identities')."
1453                             WHERE  user_id=?
1454                             AND    standard=1
1455                             AND    del<>1",
1456                             $_SESSION['user_id']);
1457                                    
1458   if ($DB->num_rows($sql_result))
1459     {
1460     $sql_arr = $DB->fetch_assoc($sql_result);
1461     $s_username = $sql_arr['mailto'];
1462     }
1463   else if (strstr($_SESSION['username'], '@'))
1464     $s_username = $_SESSION['username'];
1465   else
1466     $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1467
1468   return $s_username;
1469   }
1470
1471
4e17e6 1472 // return code for the webmail login form
T 1473 function rcmail_login_form($attrib)
1474   {
1475   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1476   
1477   $labels = array();
1478   $labels['user'] = rcube_label('username');
1479   $labels['pass'] = rcube_label('password');
1480   $labels['host'] = rcube_label('server');
1481   
1482   $input_user = new textfield(array('name' => '_user', 'size' => 30));
1483   $input_pass = new passwordfield(array('name' => '_pass', 'size' => 30));
1484   $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
1485     
1486   $fields = array();
1487   $fields['user'] = $input_user->show($_POST['_user']);
1488   $fields['pass'] = $input_pass->show();
1489   $fields['action'] = $input_action->show();
1490   
1491   if (is_array($CONFIG['default_host']))
1492     {
1493     $select_host = new select(array('name' => '_host'));
42b113 1494     
T 1495     foreach ($CONFIG['default_host'] as $key => $value)
1496       $select_host->add($value, (is_numeric($key) ? $value : $key));
1497       
4e17e6 1498     $fields['host'] = $select_host->show($_POST['_host']);
T 1499     }
1500   else if (!strlen($CONFIG['default_host']))
1501     {
1502     $input_host = new textfield(array('name' => '_host', 'size' => 30));
1503     $fields['host'] = $input_host->show($_POST['_host']);
1504     }
1505
1506   $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1507   $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1508   $form_end = !strlen($attrib['form']) ? '</form>' : '';
1509   
1510   if ($fields['host'])
1511     $form_host = <<<EOF
1512     
1513 </tr><tr>
1514
1515 <td class="title">$labels[host]</td>
1516 <td>$fields[host]</td>
1517
1518 EOF;
1519
1520   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1521   
1522   $out = <<<EOF
1523 $form_start
1524 $SESS_HIDDEN_FIELD
1525 $fields[action]
1526 <table><tr>
1527
1528 <td class="title">$labels[user]</td>
1529 <td>$fields[user]</td>
1530
1531 </tr><tr>
1532
1533 <td class="title">$labels[pass]</td>
1534 <td>$fields[pass]</td>
1535 $form_host
1536 </tr></table>
1537 $form_end
1538 EOF;
1539
1540   return $out;
1541   }
1542
1543
1cded8 1544 function rcmail_charset_selector($attrib)
T 1545   {
1546   // pass the following attributes to the form class
1547   $field_attrib = array('name' => '_charset');
1548   foreach ($attrib as $attr => $value)
1549     if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1550       $field_attrib[$attr] = $value;
1551       
1552   $charsets = array(
1553     'US-ASCII'     => 'ASCII (English)',
f88d41 1554     'EUC-JP'       => 'EUC-JP (Japanese)',
1cded8 1555     'EUC-KR'       => 'EUC-KR (Korean)',
T 1556     'BIG5'         => 'BIG5 (Chinese)',
1557     'GB2312'       => 'GB2312 (Chinese)',
f88d41 1558     'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1cded8 1559     'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
T 1560     'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1561     'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1562     'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1563     'Windows-1251' => 'Windows-1251 (Cyrillic)',
1564     'Windows-1252' => 'Windows-1252 (Western)',
1565     'Windows-1255' => 'Windows-1255 (Hebrew)',
1566     'Windows-1256' => 'Windows-1256 (Arabic)',
1567     'Windows-1257' => 'Windows-1257 (Baltic)',
1568     'UTF-8'        => 'UTF-8'
1569     );
1570
1571   $select = new select($field_attrib);
1572   $select->add(array_values($charsets), array_keys($charsets));
1573   
1574   $set = $_POST['_charset'] ? $_POST['_charset'] : $GLOBALS['CHARSET'];
1575   return $select->show($set);
1576   }
1577
1578
cc9570 1579 /****** debugging function ********/
T 1580
15a9d1 1581 function rcube_timer()
T 1582   {
1583   list($usec, $sec) = explode(" ", microtime());
1584   return ((float)$usec + (float)$sec);
1585   }
1586   
1587
1588 function rcube_print_time($timer, $label='Timer')
1589   {
1590   static $print_count = 0;
1591   
1592   $print_count++;
1593   $now = rcube_timer();
1594   $diff = $now-$timer;
1595   
1596   if (empty($label))
1597     $label = 'Timer '.$print_count;
1598   
1599   console(sprintf("%s: %0.4f sec", $label, $diff));
1600   }
1601
d1d2c4 1602 ?>