thomascube
2006-03-04 f5121b5639992fc9e51fd551bac2254429b638fa
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/main.inc                                              |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005, RoundCube Dev, - Switzerland                      |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 11  | PURPOSE:                                                              |
12  |   Provide basic functions for the webmail package                     |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id$
19
20 */
21
22 require_once('lib/des.inc');
0af7e8 23 require_once('lib/utf7.inc');
83dbb7 24 require_once('lib/utf8.class.php');
4e17e6 25
T 26
ea7c46 27 // define constannts for input reading
T 28 define('RCUBE_INPUT_GET', 0x0101);
29 define('RCUBE_INPUT_POST', 0x0102);
30 define('RCUBE_INPUT_GPC', 0x0103);
31
32
4e17e6 33 // register session and connect to server
T 34 function rcmail_startup($task='mail')
35   {
36   global $sess_id, $sess_auth, $sess_user_lang;
37   global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
38
39   // check client
40   $BROWSER = rcube_browser();
de2e1e 41
4e17e6 42   // load config file
T 43   include_once('config/main.inc.php');
44   $CONFIG = is_array($rcmail_config) ? $rcmail_config : array();
45   $CONFIG['skin_path'] = $CONFIG['skin_path'] ? preg_replace('/\/$/', '', $CONFIG['skin_path']) : 'skins/default';
46
47   // load db conf
48   include_once('config/db.inc.php');
49   $CONFIG = array_merge($CONFIG, $rcmail_config);
50
fd8c50 51   if (empty($CONFIG['log_dir']))
T 52     $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
53   else
54     $CONFIG['log_dir'] = ereg_replace('\/$', '', $CONFIG['log_dir']);
4e17e6 55
T 56   // set PHP error logging according to config
57   if ($CONFIG['debug_level'] & 1)
58     {
59     ini_set('log_errors', 1);
fd8c50 60     ini_set('error_log', $CONFIG['log_dir'].'/errors');
4e17e6 61     }
T 62   if ($CONFIG['debug_level'] & 4)
63     ini_set('display_errors', 1);
64   else
65     ini_set('display_errors', 0);
7902df 66   
T 67   // set session garbage collecting time according to session_lifetime
68   if (!empty($CONFIG['session_lifetime']))
69     ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']+2)*60);
4e17e6 70
T 71
72   // prepare DB connection
f45ec7 73   require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
S 74   
1676e1 75   $DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr']);
42b113 76   $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
4e17e6 77
T 78   // we can use the database for storing session data
36df57 79   // session queries do not work with MDB2
58e360 80   if ($CONFIG['db_backend']!='mdb2' && is_object($DB))
4e17e6 81     include_once('include/session.inc');
T 82
83
84   // init session
85   session_start();
86   $sess_id = session_id();
87   
88   // create session and set session vars
89   if (!$_SESSION['client_id'])
90     {
91     $_SESSION['client_id'] = $sess_id;
0af7e8 92     $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
4e17e6 93     $_SESSION['auth_time'] = mktime();
T 94     $_SESSION['auth'] = rcmail_auth_hash($sess_id, $_SESSION['auth_time']);
95     unset($GLOBALS['_auth']);
96     }
97
98   // set session vars global
99   $sess_auth = $_SESSION['auth'];
0af7e8 100   $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
4e17e6 101
T 102
103   // overwrite config with user preferences
104   if (is_array($_SESSION['user_prefs']))
105     $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
106
107
108   // reset some session parameters when changing task
109   if ($_SESSION['task'] != $task)
110     unset($_SESSION['page']);
111
112   // set current task to session
113   $_SESSION['task'] = $task;
114
115
116   // create IMAP object
117   if ($task=='mail')
118     rcmail_imap_init();
119
120
121   // set localization
122   if ($CONFIG['locale_string'])
123     setlocale(LC_ALL, $CONFIG['locale_string']);
124   else if ($sess_user_lang)
125     setlocale(LC_ALL, $sess_user_lang);
126
127
128   register_shutdown_function('rcmail_shutdown');
129   }
130   
131
132 // create authorization hash
133 function rcmail_auth_hash($sess_id, $ts)
134   {
135   global $CONFIG;
136   
137   $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
138                          $sess_id,
139                          $ts,
140                          $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
141                          $_SERVER['HTTP_USER_AGENT']);
142   
143   if (function_exists('sha1'))
144     return sha1($auth_string);
145   else
146     return md5($auth_string);
147   }
148
149
150
151 // create IMAP object and connect to server
152 function rcmail_imap_init($connect=FALSE)
153   {
1cded8 154   global $CONFIG, $DB, $IMAP;
6dc026 155
1cded8 156   $IMAP = new rcube_imap($DB);
15a9d1 157   $IMAP->debug_level = $CONFIG['debug_level'];
T 158   $IMAP->skip_deleted = $CONFIG['skip_deleted'];
159
4e17e6 160
7902df 161   // connect with stored session data
T 162   if ($connect)
163     {
164     if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
165       show_message('imaperror', 'error');
166       
167     rcmail_set_imap_prop();
168     }
169
6dc026 170   // enable caching of imap data
T 171   if ($CONFIG['enable_caching']===TRUE)
172     $IMAP->set_caching(TRUE);
173
4e17e6 174   if (is_array($CONFIG['default_imap_folders']))
T 175     $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
176
177   // set pagesize from config
178   if (isset($CONFIG['pagesize']))
179     $IMAP->set_pagesize($CONFIG['pagesize']);
7902df 180   }
4e17e6 181
T 182
7902df 183 // set root dir and last stored mailbox
T 184 // this must be done AFTER connecting to the server
185 function rcmail_set_imap_prop()
186   {
187   global $CONFIG, $IMAP;
188
189   // set root dir from config
190   if (strlen($CONFIG['imap_root']))
191     $IMAP->set_rootdir($CONFIG['imap_root']);
192
193   if (strlen($_SESSION['mbox']))
194     $IMAP->set_mailbox($_SESSION['mbox']);
195     
196   if (isset($_SESSION['page']))
197     $IMAP->set_page($_SESSION['page']);
4e17e6 198   }
T 199
200
201 // do these things on script shutdown
202 function rcmail_shutdown()
203   {
204   global $IMAP;
205   
206   if (is_object($IMAP))
207     {
208     $IMAP->close();
209     $IMAP->write_cache();
210     }
0af7e8 211     
T 212   // before closing the database connection, write session data
213   session_write_close();
4e17e6 214   }
T 215
216
217 // destroy session data and remove cookie
218 function rcmail_kill_session()
219   {
220 /* $sess_name = session_name();
221   if (isset($_COOKIE[$sess_name]))
222    setcookie($sess_name, '', time()-42000, '/');
223 */
224   $_SESSION = array();
225   session_destroy();
226   }
227
228
229 // return correct name for a specific database table
230 function get_table_name($table)
231   {
232   global $CONFIG;
233   
234   // return table name if configured
235   $config_key = 'db_table_'.$table;
236
237   if (strlen($CONFIG[$config_key]))
238     return $CONFIG[$config_key];
239   
240   return $table;
241   }
242
243
1cded8 244 // return correct name for a specific database sequence
T 245 // (used for Postres only)
246 function get_sequence_name($sequence)
247   {
248   global $CONFIG;
249   
250   // return table name if configured
251   $config_key = 'db_sequence_'.$sequence;
252
253   if (strlen($CONFIG[$config_key]))
254     return $CONFIG[$config_key];
255   
256   return $table;
257   }
0af7e8 258
T 259
260 // check the given string and returns language properties
261 function rcube_language_prop($lang, $prop='lang')
262   {
263   global $INSTLL_PATH;
264   static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
265
266   if (empty($rcube_languages))
267     @include($INSTLL_PATH.'program/localization/index.inc');
268     
269   // check if we have an alias for that language
270   if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
271     $lang = $rcube_language_aliases[$lang];
272     
273   // try the first two chars
f88d41 274   if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
0af7e8 275     {
T 276     $lang = substr($lang, 0, 2);
277     $lang = rcube_language_prop($lang);
278     }
279
280   if (!isset($rcube_languages[$lang]))
281     $lang = 'en_US';
282
283   // language has special charset configured
284   if (isset($rcube_charsets[$lang]))
285     $charset = $rcube_charsets[$lang];
286   else
287     $charset = 'UTF-8';    
f88d41 288
0af7e8 289
T 290   if ($prop=='charset')
291     return $charset;
292   else
293     return $lang;
294   }
1cded8 295   
4e17e6 296
T 297 // init output object for GUI and add common scripts
298 function load_gui()
299   {
3f9edb 300   global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
4e17e6 301
T 302   // init output page
303   $OUTPUT = new rcube_html_page();
304   
305   // add common javascripts
306   $javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
307   $javascript .= "$JS_OBJECT_NAME.set_env('comm_path', '$COMM_PATH');\n";
308
597170 309   if (!empty($GLOBALS['_framed']))
4e17e6 310     $javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
7cc38e 311     
4e17e6 312   $OUTPUT->add_script($javascript);
T 313   $OUTPUT->include_script('program/js/common.js');
7cc38e 314   $OUTPUT->include_script('program/js/app.js');
T 315
13c1af 316   // set locale setting
T 317   rcmail_set_locale($sess_user_lang);
318
7cc38e 319   // set user-selected charset
5bc8cb 320   if (!empty($CONFIG['charset']))
7cc38e 321     $OUTPUT->set_charset($CONFIG['charset']);
0af7e8 322
10a699 323   // add some basic label to client
T 324   rcube_add_label('loading');
0af7e8 325   }
7cc38e 326
T 327
328 // set localization charset based on the given language
329 function rcmail_set_locale($lang)
330   {
f88d41 331   global $OUTPUT, $MBSTRING, $MBSTRING_ENCODING;
T 332   static $s_mbstring_loaded = NULL;
333   
334   // settings for mbstring module (by Tadashi Jokagi)
335   if ($s_mbstring_loaded===NULL)
336     {
337     if ($s_mbstring_loaded = extension_loaded("mbstring"))
338       {
339       $MBSTRING = TRUE;
340       if (function_exists("mb_mbstring_encodings"))
341         $MBSTRING_ENCODING = mb_mbstring_encodings();
342       else
343         $MBSTRING_ENCODING = array("ISO-8859-1", "UTF-7", "UTF7-IMAP", "UTF-8",
344                                    "ISO-2022-JP", "EUC-JP", "EUCJP-WIN",
345                                    "SJIS", "SJIS-WIN");
346
347        $MBSTRING_ENCODING = array_map("strtoupper", $MBSTRING_ENCODING);
348        if (in_array("SJIS", $MBSTRING_ENCODING))
349          $MBSTRING_ENCODING[] = "SHIFT_JIS";
350        }
351      else
352       {
353       $MBSTRING = FALSE;
354       $MBSTRING_ENCODING = array();
355       }
356     }
357
358   if ($MBSTRING && function_exists("mb_language"))
359     {
13c1af 360     if (!@mb_language(strtok($lang, "_")))
f88d41 361       $MBSTRING = FALSE;   //  unsupport language
T 362     }
363
3f9edb 364   $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
7cc38e 365   }
4e17e6 366
T 367
368 // perfom login to the IMAP server and to the webmail service
369 function rcmail_login($user, $pass, $host=NULL)
370   {
371   global $CONFIG, $IMAP, $DB, $sess_user_lang;
42b113 372   $user_id = NULL;
4e17e6 373   
T 374   if (!$host)
375     $host = $CONFIG['default_host'];
376
f619de 377   // parse $host URL
T 378   $a_host = parse_url($host);
379   if ($a_host['host'])
380     {
381     $host = $a_host['host'];
382     $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
383     $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
384     }
ea7c46 385   else
T 386     $imap_port = $CONFIG['default_port'];
f619de 387
4e17e6 388   // query if user already registered
d7cb77 389   $sql_result = $DB->query("SELECT user_id, username, language, preferences
S 390                             FROM ".get_table_name('users')."
391                             WHERE  mail_host=? AND (username=? OR alias=?)",
392                             $host,
393                             $user,
394                             $user);
4e17e6 395
42b113 396   // user already registered -> overwrite username
4e17e6 397   if ($sql_arr = $DB->fetch_assoc($sql_result))
T 398     {
399     $user_id = $sql_arr['user_id'];
42b113 400     $user = $sql_arr['username'];
T 401     }
402
977a29 403   // try to resolve email address from virtuser table    
T 404   if (!empty($CONFIG['virtuser_file']) && strstr($user, '@'))
405     $user = rcmail_email2user($user);
406
407
42b113 408   // exit if IMAP login failed
T 409   if (!($imap_login  = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
410     return FALSE;
411
412   // user already registered
413   if ($user_id && !empty($sql_arr))
414     {
4e17e6 415     // get user prefs
T 416     if (strlen($sql_arr['preferences']))
417       {
418       $user_prefs = unserialize($sql_arr['preferences']);
419       $_SESSION['user_prefs'] = $user_prefs;
420       array_merge($CONFIG, $user_prefs);
421       }
422
f3b659 423
4e17e6 424     // set user specific language
T 425     if (strlen($sql_arr['language']))
426       $sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
f3b659 427       
4e17e6 428     // update user's record
d7cb77 429     $DB->query("UPDATE ".get_table_name('users')."
667737 430                 SET    last_login=now()
d7cb77 431                 WHERE  user_id=?",
S 432                 $user_id);
4e17e6 433     }
T 434   // create new system user
435   else if ($CONFIG['auto_create_user'])
436     {
437     $user_id = rcmail_create_user($user, $host);
438     }
439
440   if ($user_id)
441     {
442     $_SESSION['user_id']   = $user_id;
443     $_SESSION['imap_host'] = $host;
7902df 444     $_SESSION['imap_port'] = $imap_port;
T 445     $_SESSION['imap_ssl']  = $imap_ssl;
4e17e6 446     $_SESSION['username']  = $user;
f3b659 447     $_SESSION['user_lang'] = $sess_user_lang;
4e17e6 448     $_SESSION['password']  = encrypt_passwd($pass);
T 449
450     // force reloading complete list of subscribed mailboxes    
451     $IMAP->clear_cache('mailboxes');
452
453     return TRUE;
454     }
455
456   return FALSE;
457   }
458
459
460 // create new entry in users and identities table
461 function rcmail_create_user($user, $host)
462   {
463   global $DB, $CONFIG, $IMAP;
977a29 464
T 465   $user_email = '';
466
467   // try to resolve user in virtusertable
468   if (!empty($CONFIG['virtuser_file']) && strstr($user, '@')==FALSE)
469     $user_email = rcmail_user2email($user);
470
d7cb77 471   $DB->query("INSERT INTO ".get_table_name('users')."
977a29 472               (created, last_login, username, mail_host, alias, language)
T 473               VALUES (now(), now(), ?, ?, ?, ?)",
d7cb77 474               $user,
S 475               $host,
977a29 476               $user_email,
d7cb77 477               $_SESSION['user_lang']);
4e17e6 478
1cded8 479   if ($user_id = $DB->insert_id(get_sequence_name('users')))
4e17e6 480     {
bddb8f 481     if (is_array($CONFIG['mail_domain']) && isset($CONFIG['mail_domain'][$host]))
977a29 482       $mail_domain = $CONFIG['mail_domain'][$host];
bddb8f 483     else if (!empty($CONFIG['mail_domain']))
T 484       $mail_domain = $CONFIG['mail_domain'];
977a29 485     else
T 486       $mail_domain = $host;
487    
488     if ($user_email=='')
489       $user_email = strstr($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
490
52c1f2 491     $user_name = $user!=$user_email ? $user : '';
977a29 492
f88d41 493     // try to resolve the e-mail address from the virtuser table
T 494     if (!empty($CONFIG['virtuser_query']))
495       {
496       $sql_result = $DB->query(preg_replace('/%u/', $user, $CONFIG['virtuser_query']));
497       if ($sql_arr = $DB->fetch_array($sql_result))
498         $user_email = $sql_arr[0];
499       }
500
501     // also create new identity records
d7cb77 502     $DB->query("INSERT INTO ".get_table_name('identities')."
1cded8 503                 (user_id, del, standard, name, email)
T 504                 VALUES (?, 0, 1, ?, ?)",
d7cb77 505                 $user_id,
S 506                 $user_name,
507                 $user_email);
f88d41 508
4e17e6 509                        
T 510     // get existing mailboxes
511     $a_mailboxes = $IMAP->list_mailboxes();
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   }
ea7c46 906
T 907
908 /**
909  * Read input value and convert it for internal use
910  * Performs stripslashes() and charset conversion if necessary
911  * 
912  * @param  string   Field name to read
913  * @param  int      Source to get value from (GPC)
914  * @param  boolean  Allow HTML tags in field value
915  * @param  string   Charset to convert into
916  * @return string   Field value or NULL if not available
917  */
918 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
919   {
920   global $OUTPUT;
921   $value = NULL;
922   
923   if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
924     $value = $_GET[$fname];
925   else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
926     $value = $_POST[$fname];
927   else if ($source==RCUBE_INPUT_GPC)
928     {
929     if (isset($_GET[$fname]))
930       $value = $_GET[$fname];
931     else if (isset($_POST[$fname]))
932       $value = $_POST[$fname];
933     else if (isset($_COOKIE[$fname]))
934       $value = $_COOKIE[$fname];
935     }
936   
937   // strip slashes if magic_quotes enabled
938   if ((bool)get_magic_quotes_gpc())
939     $value = stripslashes($value);
940
941   // remove HTML tags if not allowed    
942   if (!$allow_html)
943     $value = strip_tags($value);
944   
945   // convert to internal charset
946   return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
947   }
948
10a699 949
T 950
4e17e6 951
T 952 // ************** template parsing and gui functions **************
953
954
955 // return boolean if a specific template exists
956 function template_exists($name)
957   {
958   global $CONFIG, $OUTPUT;
959   $skin_path = $CONFIG['skin_path'];
960
961   // check template file
962   return is_file("$skin_path/templates/$name.html");
963   }
964
965
966 // get page template an replace variable
967 // similar function as used in nexImage
968 function parse_template($name='main', $exit=TRUE)
969   {
970   global $CONFIG, $OUTPUT;
971   $skin_path = $CONFIG['skin_path'];
972
973   // read template file
974   $templ = '';
975   $path = "$skin_path/templates/$name.html";
976
977   if($fp = @fopen($path, 'r'))
978     {
979     $templ = fread($fp, filesize($path));
980     fclose($fp);
981     }
982   else
983     {
984     raise_error(array('code' => 500,
985                       'type' => 'php',
986                       'line' => __LINE__,
987                       'file' => __FILE__,
988                       'message' => "Error loading template for '$name'"), TRUE, TRUE);
989     return FALSE;
990     }
991
992
993   // parse for specialtags
994   $output = parse_rcube_xml($templ);
995   
996   $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
997
998   if ($exit)
999     exit;
1000   }
1001
1002
1003
1004 // replace all strings ($varname) with the content of the according global variable
1005 function parse_with_globals($input)
1006   {
b595c9 1007   $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
4e17e6 1008   $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
T 1009   return $output;
1010   }
1011
1012
1013
1014 function parse_rcube_xml($input)
1015   {
1016   $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
1017   return $output;
1018   }
1019
1020
1021 function rcube_xml_command($command, $str_attrib, $a_attrib=NULL)
1022   {
0af7e8 1023   global $IMAP, $CONFIG, $OUTPUT;
4e17e6 1024   
T 1025   $attrib = array();
1026   $command = strtolower($command);
1027
1028   preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str_attrib), $regs, PREG_SET_ORDER);
1029
1030   // convert attributes to an associative array (name => value)
1031   if ($regs)
1032     foreach ($regs as $attr)
1033       $attrib[strtolower($attr[1])] = $attr[2];
1034   else if ($a_attrib)
1035     $attrib = $a_attrib;
1036
1037   // execute command
1038   switch ($command)
1039     {
1040     // return a button
1041     case 'button':
1042       if ($attrib['command'])
1043         return rcube_button($attrib);
1044       break;
1045
1046     // show a label
1047     case 'label':
1048       if ($attrib['name'] || $attrib['command'])
7dd801 1049         return rep_specialchars_output(rcube_label($attrib));
4e17e6 1050       break;
T 1051
1052     // create a menu item
1053     case 'menu':
1054       if ($attrib['command'] && $attrib['group'])
1055         rcube_menu($attrib);
1056       break;
1057
1058     // include a file 
1059     case 'include':
1060       $path = realpath($CONFIG['skin_path'].$attrib['file']);
1061       
1062       if($fp = @fopen($path, 'r'))
1063         {
1064         $incl = fread($fp, filesize($path));
1065         fclose($fp);        
1066         return parse_rcube_xml($incl);
1067         }
1068       break;
1069
1070     // return code for a specific application object
1071     case 'object':
1072       $object = strtolower($attrib['name']);
1073
1cded8 1074       $object_handlers = array(
15a9d1 1075         // GENERAL
T 1076         'loginform' => 'rcmail_login_form',
1077         'username'  => 'rcmail_current_username',
1078         
1cded8 1079         // MAIL
T 1080         'mailboxlist' => 'rcmail_mailbox_list',
15a9d1 1081         'message' => 'rcmail_message_container',
1cded8 1082         'messages' => 'rcmail_message_list',
T 1083         'messagecountdisplay' => 'rcmail_messagecount_display',
58e360 1084         'quotadisplay' => 'rcmail_quota_display',
1cded8 1085         'messageheaders' => 'rcmail_message_headers',
T 1086         'messagebody' => 'rcmail_message_body',
1087         'messageattachments' => 'rcmail_message_attachments',
1088         'blockedobjects' => 'rcmail_remote_objects_msg',
1089         'messagecontentframe' => 'rcmail_messagecontent_frame',
1090         'messagepartframe' => 'rcmail_message_part_frame',
1091         'messagepartcontrols' => 'rcmail_message_part_controls',
1092         'composeheaders' => 'rcmail_compose_headers',
1093         'composesubject' => 'rcmail_compose_subject',
1094         'composebody' => 'rcmail_compose_body',
1095         'composeattachmentlist' => 'rcmail_compose_attachment_list',
1096         'composeattachmentform' => 'rcmail_compose_attachment_form',
1097         'composeattachment' => 'rcmail_compose_attachment_field',
1098         'priorityselector' => 'rcmail_priority_selector',
1099         'charsetselector' => 'rcmail_charset_selector',
1100         
1101         // ADDRESS BOOK
1102         'addresslist' => 'rcmail_contacts_list',
1103         'addressframe' => 'rcmail_contact_frame',
1104         'recordscountdisplay' => 'rcmail_rowcount_display',
1105         'contactdetails' => 'rcmail_contact_details',
1106         'contacteditform' => 'rcmail_contact_editform',
d1d2c4 1107         'ldappublicsearch' => 'rcmail_ldap_public_search_form',
S 1108         'ldappublicaddresslist' => 'rcmail_ldap_public_list',
1cded8 1109
T 1110         // USER SETTINGS
1111         'userprefs' => 'rcmail_user_prefs_form',
1112         'itentitieslist' => 'rcmail_identities_list',
1113         'identityframe' => 'rcmail_identity_frame',
1114         'identityform' => 'rcube_identity_form',
1115         'foldersubscription' => 'rcube_subscription_form',
1116         'createfolder' => 'rcube_create_folder_form',
1117         'composebody' => 'rcmail_compose_body'
1118       );
1119
1120       
1121       // execute object handler function
15a9d1 1122       if ($object_handlers[$object] && function_exists($object_handlers[$object]))
1cded8 1123         return call_user_func($object_handlers[$object], $attrib);
4e17e6 1124
T 1125       else if ($object=='pagetitle')
1126         {
1127         $task = $GLOBALS['_task'];
15a9d1 1128         $title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
T 1129         
4e17e6 1130         if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
15a9d1 1131           $title .= $GLOBALS['MESSAGE']['subject'];
4e17e6 1132         else if (isset($GLOBALS['PAGE_TITLE']))
15a9d1 1133           $title .= $GLOBALS['PAGE_TITLE'];
4e17e6 1134         else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
3f9edb 1135           $title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
4e17e6 1136         else
15a9d1 1137           $title .= $task;
T 1138           
1139         return rep_specialchars_output($title, 'html', 'all');
4e17e6 1140         }
T 1141
1142       break;
1143     }
1144
1145   return '';
1146   }
1147
1148
1149 // create and register a button
1150 function rcube_button($attrib)
1151   {
14eafe 1152   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER;
4e17e6 1153   static $sa_buttons = array();
T 1154   static $s_button_count = 100;
1155   
1156   $skin_path = $CONFIG['skin_path'];
1157   
1158   if (!($attrib['command'] || $attrib['name']))
1159     return '';
1160
1161   // try to find out the button type
1162   if ($attrib['type'])
1163     $attrib['type'] = strtolower($attrib['type']);
1164   else
1165     $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imagect']) ? 'image' : 'link';
1166   
1167   
1168   $command = $attrib['command'];
1169   
1170   // take the button from the stack
1171   if($attrib['name'] && $sa_buttons[$attrib['name']])
1172     $attrib = $sa_buttons[$attrib['name']];
1173
1174   // add button to button stack
1175   else if($attrib['image'] || $arg['imagect'] || $attrib['imagepas'] || $attrib['class'])
1176     {
1177     if(!$attrib['name'])
1178       $attrib['name'] = $command;
1179
1180     if (!$attrib['image'])
1181       $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1182
1183     $sa_buttons[$attrib['name']] = $attrib;
1184     }
1185
1186   // get saved button for this command/name
1187   else if ($command && $sa_buttons[$command])
1188     $attrib = $sa_buttons[$command];
1189
1190   //else
1191   //  return '';
1192
1193
1194   // set border to 0 because of the link arround the button
1195   if ($attrib['type']=='image' && !isset($attrib['border']))
1196     $attrib['border'] = 0;
1197     
1198   if (!$attrib['id'])
1199     $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
1200
1201   // get localized text for labels and titles
1202   if ($attrib['title'])
1203     $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
1204   if ($attrib['label'])
1205     $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
1206
1207   if ($attrib['alt'])
1208     $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
14eafe 1209
T 1210   // set title to alt attribute for IE browsers
1211   if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
1212     {
1213     $attrib['alt'] = $attrib['title'];
1214     unset($attrib['title']);
1215     }
1216
4e17e6 1217   // add empty alt attribute for XHTML compatibility
T 1218   if (!isset($attrib['alt']))
1219     $attrib['alt'] = '';
1220
1221
1222   // register button in the system
1223   if ($attrib['command'])
1224     $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
1225                                 $JS_OBJECT_NAME,
1226                                 $command,
1227                                 $attrib['id'],
1228                                 $attrib['type'],
1229                                 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
1230                                 $attirb['imagesel'] ? $skin_path.$attirb['imagesel'] : $attrib['classsel'],
1231                                 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
1232
1233   // overwrite attributes
1234   if (!$attrib['href'])
1235     $attrib['href'] = '#';
1236
1237   if ($command)
1238     $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
1239     
1240   if ($command && $attrib['imageover'])
1241     {
1242     $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1243     $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1244     }
1245
1246
1247   $out = '';
1248
1249   // generate image tag
1250   if ($attrib['type']=='image')
1251     {
1cded8 1252     $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
4e17e6 1253     $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
T 1254     $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
1255     if ($attrib['label'])
1256       $btn_content .= ' '.$attrib['label'];
1257     
1258     $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'title');
1259     }
1260   else if ($attrib['type']=='link')
1261     {
1262     $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
1263     $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
1264     }
1265   else if ($attrib['type']=='input')
1266     {
1267     $attrib['type'] = 'button';
1268     
1269     if ($attrib['label'])
1270       $attrib['value'] = $attrib['label'];
1271       
1272     $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
1273     $out = sprintf('<input%s disabled />', $attrib_str);
1274     }
1275
1276   // generate html code for button
1277   if ($btn_content)
1278     {
1279     $attrib_str = create_attrib_string($attrib, $link_attrib);
1280     $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1281     }
1282
1283   return $out;
1284   }
1285
1286
1287 function rcube_menu($attrib)
1288   {
1289   
1290   return '';
1291   }
1292
1293
1294
d1d2c4 1295 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
4e17e6 1296   {
T 1297   global $DB;
1298   
1299   // allow the following attributes to be added to the <table> tag
1300   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1301   
1302   $table = '<table' . $attrib_str . ">\n";
1303     
1304   // add table title
1305   $table .= "<thead><tr>\n";
1306
1307   foreach ($a_show_cols as $col)
1038d5 1308     $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
4e17e6 1309
T 1310   $table .= "</tr></thead>\n<tbody>\n";
1311   
1312   $c = 0;
d1d2c4 1313
S 1314   if (!is_array($table_data)) 
4e17e6 1315     {
d1d2c4 1316     while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
4e17e6 1317       {
d1d2c4 1318       $zebra_class = $c%2 ? 'even' : 'odd';
4e17e6 1319
d1d2c4 1320       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
S 1321
1322       // format each col
1323       foreach ($a_show_cols as $col)
1324         {
1325         $cont = rep_specialchars_output($sql_arr[$col]);
1326         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1327         }
1328
1329       $table .= "</tr>\n";
1330       $c++;
1331       }
1332     }
1333   else 
1334     {
1335     foreach ($table_data as $row_data)
1336       {
1337       $zebra_class = $c%2 ? 'even' : 'odd';
1338
1339       $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1340
1341       // format each col
1342       foreach ($a_show_cols as $col)
1343         {
1344         $cont = rep_specialchars_output($row_data[$col]);
1345         $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1346         }
1347
1348       $table .= "</tr>\n";
1349       $c++;
1350       }
4e17e6 1351     }
T 1352
1353   // complete message table
1354   $table .= "</tbody></table>\n";
1355   
1356   return $table;
1357   }
1358
1359
1360
1361 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1362   {
1363   $fname = '_'.$col;
1364   $attrib['name'] = $fname;
1365   
1366   if ($type=='checkbox')
1367     {
1368     $attrib['value'] = '1';
1369     $input = new checkbox($attrib);
1370     }
1371   else if ($type=='textarea')
1372     {
1373     $attrib['cols'] = $attrib['size'];
1374     $input = new textarea($attrib);
1375     }
1376   else
1377     $input = new textfield($attrib);
1378
1379   // use value from post
597170 1380   if (!empty($_POST[$fname]))
4e17e6 1381     $value = $_POST[$fname];
T 1382
1383   $out = $input->show($value);
1384          
1385   return $out;
1386   }
1387
1388
1389 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1390   {
1391   // allow the following attributes to be added to the <iframe> tag
1392   $attrib_str = '';
1393   foreach ($allowed_attribs as $a)
1394     if (isset($attrib[$a]))
1395       $attrib_str .= sprintf(' %s="%s"', $a, $attrib[$a]);
1396
1397   return $attrib_str;
1398   }
1399
1400
1401
1402 function format_date($date, $format=NULL)
1403   {
1404   global $CONFIG, $sess_user_lang;
1405   
1406   if (is_numeric($date))
1407     $ts = $date;
b076a4 1408   else if (!empty($date))
4e17e6 1409     $ts = strtotime($date);
b076a4 1410   else
T 1411     return '';
4e17e6 1412
T 1413   // convert time to user's timezone
1414   $timestamp = $ts - date('Z', $ts) + ($CONFIG['timezone'] * 3600);
1415   
1416   // get current timestamp in user's timezone
1417   $now = time();  // local time
1418   $now -= (int)date('Z'); // make GMT time
1419   $now += ($CONFIG['timezone'] * 3600); // user's time
749b07 1420   $now_date = getdate();
4e17e6 1421
749b07 1422   //$day_secs = 60*((int)date('H', $now)*60 + (int)date('i', $now));
T 1423   //$week_secs = 60 * 60 * 24 * 7;
1424   //$diff = $now - $timestamp;
1425   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1426   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 1427
30233b 1428   // define date format depending on current time  
749b07 1429   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
4e17e6 1430     return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
749b07 1431   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
4e17e6 1432     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 1433   else if (!$format)
1434     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1435
1436
1437   // parse format string manually in order to provide localized weekday and month names
1438   // an alternative would be to convert the date() format string to fit with strftime()
1439   $out = '';
1440   for($i=0; $i<strlen($format); $i++)
1441     {
1442     if ($format{$i}=='\\')  // skip escape chars
1443       continue;
1444     
1445     // write char "as-is"
1446     if ($format{$i}==' ' || $format{$i-1}=='\\')
1447       $out .= $format{$i};
1448     // weekday (short)
1449     else if ($format{$i}=='D')
1450       $out .= rcube_label(strtolower(date('D', $timestamp)));
1451     // weekday long
1452     else if ($format{$i}=='l')
1453       $out .= rcube_label(strtolower(date('l', $timestamp)));
1454     // month name (short)
1455     else if ($format{$i}=='M')
1456       $out .= rcube_label(strtolower(date('M', $timestamp)));
1457     // month name (long)
1458     else if ($format{$i}=='F')
1459       $out .= rcube_label(strtolower(date('F', $timestamp)));
1460     else
1461       $out .= date($format{$i}, $timestamp);
1462     }
1463   
1464   return $out;
1465   }
1466
1467
1468 // ************** functions delivering gui objects **************
1469
1470
1471
1472 function rcmail_message_container($attrib)
1473   {
1474   global $OUTPUT, $JS_OBJECT_NAME;
1475
1476   if (!$attrib['id'])
1477     $attrib['id'] = 'rcmMessageContainer';
1478
1479   // allow the following attributes to be added to the <table> tag
1480   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1481   $out = '<div' . $attrib_str . "></div>";
1482   
1483   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1484   
1485   return $out;
1486   }
1487
1488
15a9d1 1489 // return the IMAP username of the current session
T 1490 function rcmail_current_username($attrib)
1491   {
1492   global $DB;
1493   static $s_username;
1494
1495   // alread fetched  
1496   if (!empty($s_username))
1497     return $s_username;
1498
1499   // get e-mail address form default identity
1500   $sql_result = $DB->query("SELECT email AS mailto
1501                             FROM ".get_table_name('identities')."
1502                             WHERE  user_id=?
1503                             AND    standard=1
1504                             AND    del<>1",
1505                             $_SESSION['user_id']);
1506                                    
1507   if ($DB->num_rows($sql_result))
1508     {
1509     $sql_arr = $DB->fetch_assoc($sql_result);
1510     $s_username = $sql_arr['mailto'];
1511     }
1512   else if (strstr($_SESSION['username'], '@'))
1513     $s_username = $_SESSION['username'];
1514   else
1515     $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1516
1517   return $s_username;
1518   }
1519
1520
4e17e6 1521 // return code for the webmail login form
T 1522 function rcmail_login_form($attrib)
1523   {
1524   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1525   
1526   $labels = array();
1527   $labels['user'] = rcube_label('username');
1528   $labels['pass'] = rcube_label('password');
1529   $labels['host'] = rcube_label('server');
1530   
1531   $input_user = new textfield(array('name' => '_user', 'size' => 30));
1532   $input_pass = new passwordfield(array('name' => '_pass', 'size' => 30));
1533   $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
1534     
1535   $fields = array();
ea7c46 1536   $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
4e17e6 1537   $fields['pass'] = $input_pass->show();
T 1538   $fields['action'] = $input_action->show();
1539   
1540   if (is_array($CONFIG['default_host']))
1541     {
1542     $select_host = new select(array('name' => '_host'));
42b113 1543     
T 1544     foreach ($CONFIG['default_host'] as $key => $value)
1545       $select_host->add($value, (is_numeric($key) ? $value : $key));
1546       
4e17e6 1547     $fields['host'] = $select_host->show($_POST['_host']);
T 1548     }
1549   else if (!strlen($CONFIG['default_host']))
1550     {
1551     $input_host = new textfield(array('name' => '_host', 'size' => 30));
1552     $fields['host'] = $input_host->show($_POST['_host']);
1553     }
1554
1555   $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1556   $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1557   $form_end = !strlen($attrib['form']) ? '</form>' : '';
1558   
1559   if ($fields['host'])
1560     $form_host = <<<EOF
1561     
1562 </tr><tr>
1563
1564 <td class="title">$labels[host]</td>
1565 <td>$fields[host]</td>
1566
1567 EOF;
1568
1569   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1570   
1571   $out = <<<EOF
1572 $form_start
1573 $SESS_HIDDEN_FIELD
1574 $fields[action]
1575 <table><tr>
1576
1577 <td class="title">$labels[user]</td>
1578 <td>$fields[user]</td>
1579
1580 </tr><tr>
1581
1582 <td class="title">$labels[pass]</td>
1583 <td>$fields[pass]</td>
1584 $form_host
1585 </tr></table>
1586 $form_end
1587 EOF;
1588
1589   return $out;
1590   }
1591
1592
1cded8 1593 function rcmail_charset_selector($attrib)
T 1594   {
13c1af 1595   global $OUTPUT;
T 1596   
1cded8 1597   // pass the following attributes to the form class
T 1598   $field_attrib = array('name' => '_charset');
1599   foreach ($attrib as $attr => $value)
1600     if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1601       $field_attrib[$attr] = $value;
1602       
1603   $charsets = array(
1604     'US-ASCII'     => 'ASCII (English)',
f88d41 1605     'EUC-JP'       => 'EUC-JP (Japanese)',
1cded8 1606     'EUC-KR'       => 'EUC-KR (Korean)',
T 1607     'BIG5'         => 'BIG5 (Chinese)',
1608     'GB2312'       => 'GB2312 (Chinese)',
f88d41 1609     'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1cded8 1610     'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
T 1611     'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1612     'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1613     'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1614     'Windows-1251' => 'Windows-1251 (Cyrillic)',
1615     'Windows-1252' => 'Windows-1252 (Western)',
1616     'Windows-1255' => 'Windows-1255 (Hebrew)',
1617     'Windows-1256' => 'Windows-1256 (Arabic)',
1618     'Windows-1257' => 'Windows-1257 (Baltic)',
1619     'UTF-8'        => 'UTF-8'
1620     );
1621
1622   $select = new select($field_attrib);
1623   $select->add(array_values($charsets), array_keys($charsets));
1624   
13c1af 1625   $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
1cded8 1626   return $select->show($set);
T 1627   }
1628
1629
cc9570 1630 /****** debugging function ********/
T 1631
15a9d1 1632 function rcube_timer()
T 1633   {
1634   list($usec, $sec) = explode(" ", microtime());
1635   return ((float)$usec + (float)$sec);
1636   }
1637   
1638
1639 function rcube_print_time($timer, $label='Timer')
1640   {
1641   static $print_count = 0;
1642   
1643   $print_count++;
1644   $now = rcube_timer();
1645   $diff = $now-$timer;
1646   
1647   if (empty($label))
1648     $label = 'Timer '.$print_count;
1649   
1650   console(sprintf("%s: %0.4f sec", $label, $diff));
1651   }
1652
d1d2c4 1653 ?>