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