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