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