source: subversion/trunk/roundcubemail/program/include/main.inc @ 1251

Last change on this file since 1251 was 1251, checked in by thomasb, 5 years ago

Remove unnecessary code; unread counts are added client side

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.2 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/main.inc                                              |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005-2008, RoundCube Dev, - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
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/**
23 * RoundCube Webmail common functions
24 *
25 * @package Core
26 * @author Thomas Bruederli <roundcube@gmail.com>
27 */
28
29require_once('lib/utf7.inc');
30require_once('include/rcube_user.inc');
31require_once('include/rcube_shared.inc');
32require_once('include/rcmail_template.inc');
33
34// fallback if not PHP modules are available
35@include_once('lib/des.inc');
36@include_once('lib/utf8.class.php');
37
38// define constannts for input reading
39define('RCUBE_INPUT_GET', 0x0101);
40define('RCUBE_INPUT_POST', 0x0102);
41define('RCUBE_INPUT_GPC', 0x0103);
42
43
44/**
45 * Initial startup function
46 * to register session, create database and imap connections
47 *
48 * @param string Current task
49 */
50function rcmail_startup($task='mail')
51  {
52  global $sess_id, $sess_user_lang;
53  global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $USER;
54
55  // check client
56  $BROWSER = rcube_browser();
57
58  // load configuration
59  $CONFIG = rcmail_load_config();
60
61  // set session domain
62  if (isset($CONFIG['session_domain']) && !empty($CONFIG['session_domain'])) {
63    ini_set('session.cookie_domain', $CONFIG['session_domain']);
64  }
65
66  // set session garbage collecting time according to session_lifetime
67  if (!empty($CONFIG['session_lifetime']))
68    ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
69
70  // prepare DB connection
71  $dbwrapper = empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend'];
72  $dbclass = "rcube_" . $dbwrapper;
73  require_once("include/$dbclass.inc");
74 
75  $DB = new $dbclass($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
76  $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
77  $DB->set_debug((bool)$CONFIG['sql_debug']);
78  $DB->db_connect('w');
79
80  // use database for storing session data
81  include_once('include/session.inc');
82
83  // init session
84  session_start();
85  $sess_id = session_id();
86
87  // create session and set session vars
88  if (!isset($_SESSION['auth_time']))
89    {
90    $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
91    $_SESSION['auth_time'] = time();
92    $_SESSION['temp'] = true;
93    }
94
95  // set session vars global
96  $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
97
98  // create user object
99  $USER = new rcube_user($_SESSION['user_id']);
100
101  // overwrite config with user preferences
102  $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
103
104
105  // reset some session parameters when changing task
106  if ($_SESSION['task'] != $task)
107    unset($_SESSION['page']);
108
109  // set current task to session
110  $_SESSION['task'] = $task;
111
112  // create IMAP object
113  if ($task=='mail')
114    rcmail_imap_init();
115
116
117  // set localization
118  if ($CONFIG['locale_string'])
119    setlocale(LC_ALL, $CONFIG['locale_string']);
120  else if ($sess_user_lang)
121    setlocale(LC_ALL, $sess_user_lang);
122
123
124  register_shutdown_function('rcmail_shutdown');
125  }
126
127
128/**
129 * Load roundcube configuration array
130 *
131 * @return array Named configuration parameters
132 */
133function rcmail_load_config()
134  {
135  global $INSTALL_PATH;
136
137  // load config file
138  include_once('config/main.inc.php');
139  $conf = is_array($rcmail_config) ? $rcmail_config : array();
140
141  // load host-specific configuration
142  rcmail_load_host_config($conf);
143
144  $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
145
146  // load db conf
147  include_once('config/db.inc.php');
148  $conf = array_merge($conf, $rcmail_config);
149
150  if (empty($conf['log_dir']))
151    $conf['log_dir'] = $INSTALL_PATH.'logs';
152  else
153    $conf['log_dir'] = unslashify($conf['log_dir']);
154
155  // set PHP error logging according to config
156  if ($conf['debug_level'] & 1)
157    {
158    ini_set('log_errors', 1);
159    ini_set('error_log', $conf['log_dir'].'/errors');
160    }
161  if ($conf['debug_level'] & 4)
162    ini_set('display_errors', 1);
163  else
164    ini_set('display_errors', 0);
165
166  return $conf;
167  }
168
169
170/**
171 * Load a host-specific config file if configured
172 * This will merge the host specific configuration with the given one
173 *
174 * @param array Global configuration parameters
175 */
176function rcmail_load_host_config(&$config)
177  {
178  $fname = NULL;
179 
180  if (is_array($config['include_host_config']))
181    $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
182  else if (!empty($config['include_host_config']))
183    $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
184
185   if ($fname && is_file('config/'.$fname))
186     {
187     include('config/'.$fname);
188     $config = array_merge($config, $rcmail_config);
189     }
190  }
191
192
193/**
194 * Create unique authorization hash
195 *
196 * @param string Session ID
197 * @param int Timestamp
198 * @return string The generated auth hash
199 */
200function rcmail_auth_hash($sess_id, $ts)
201  {
202  global $CONFIG;
203 
204  $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
205                         $sess_id,
206                         $ts,
207                         $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
208                         $_SERVER['HTTP_USER_AGENT']);
209 
210  if (function_exists('sha1'))
211    return sha1($auth_string);
212  else
213    return md5($auth_string);
214  }
215
216
217/**
218 * Check the auth hash sent by the client against the local session credentials
219 *
220 * @return boolean True if valid, False if not
221 */
222function rcmail_authenticate_session()
223  {
224  global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
225 
226  // advanced session authentication
227  if ($CONFIG['double_auth'])
228  {
229    $now = time();
230    $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
231              $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
232
233    // renew auth cookie every 5 minutes (only for GET requests)
234    if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
235    {
236      $_SESSION['last_auth'] = $_SESSION['auth_time'];
237      $_SESSION['auth_time'] = $now;
238      setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
239    }
240  }
241  else
242    $valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
243 
244  // check session filetime
245  if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED)
246      && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < time())
247    $valid = false;
248 
249  return $valid;
250  }
251
252
253/**
254 * Create global IMAP object and connect to server
255 *
256 * @param boolean True if connection should be established
257 */
258function rcmail_imap_init($connect=FALSE)
259  {
260  global $CONFIG, $DB, $IMAP, $OUTPUT;
261
262  $IMAP = new rcube_imap($DB);
263  $IMAP->debug_level = $CONFIG['debug_level'];
264  $IMAP->skip_deleted = $CONFIG['skip_deleted'];
265
266
267  // connect with stored session data
268  if ($connect)
269    {
270    if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
271      $OUTPUT->show_message('imaperror', 'error');
272     
273    rcmail_set_imap_prop();
274    }
275
276  // enable caching of imap data
277  if ($CONFIG['enable_caching']===TRUE)
278    $IMAP->set_caching(TRUE);
279
280  // set pagesize from config
281  if (isset($CONFIG['pagesize']))
282    $IMAP->set_pagesize($CONFIG['pagesize']);
283  }
284
285
286/**
287 * Set root dir and last stored mailbox
288 * This must be done AFTER connecting to the server!
289 */
290function rcmail_set_imap_prop()
291  {
292  global $CONFIG, $IMAP;
293 
294  if (!empty($CONFIG['default_charset']))
295    $IMAP->set_charset($CONFIG['default_charset']);
296
297  // set root dir from config
298  if (!empty($CONFIG['imap_root']))
299    $IMAP->set_rootdir($CONFIG['imap_root']);
300
301  if (is_array($CONFIG['default_imap_folders']))
302    $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
303
304  if (!empty($_SESSION['mbox']))
305    $IMAP->set_mailbox($_SESSION['mbox']);
306  if (isset($_SESSION['page']))
307    $IMAP->set_page($_SESSION['page']);
308  }
309
310
311/**
312 * Do these things on script shutdown
313 */
314function rcmail_shutdown()
315  {
316  global $IMAP, $CONTACTS;
317 
318  if (is_object($IMAP))
319    {
320    $IMAP->close();
321    $IMAP->write_cache();
322    }
323   
324  if (is_object($CONTACTS))
325    $CONTACTS->close();
326   
327  // before closing the database connection, write session data
328  session_write_close();
329  }
330
331
332/**
333 * Destroy session data and remove cookie
334 */
335function rcmail_kill_session()
336  {
337  global $USER;
338 
339  if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
340      (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
341    {
342    $a_user_prefs = array('message_sort_col' => $_SESSION['sort_col'], 'message_sort_order' => $_SESSION['sort_order']);
343    $USER->save_prefs($a_user_prefs);
344    }
345
346  $_SESSION = array('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
347  setcookie('sessauth', '-del-', time()-60);
348  $USER->reset();
349  }
350
351
352/**
353 * Return correct name for a specific database table
354 *
355 * @param string Table name
356 * @return string Translated table name
357 */
358function get_table_name($table)
359  {
360  global $CONFIG;
361 
362  // return table name if configured
363  $config_key = 'db_table_'.$table;
364
365  if (strlen($CONFIG[$config_key]))
366    return $CONFIG[$config_key];
367 
368  return $table;
369  }
370
371
372/**
373 * Return correct name for a specific database sequence
374 * (used for Postres only)
375 *
376 * @param string Secuence name
377 * @return string Translated sequence name
378 */
379function get_sequence_name($sequence)
380  {
381  global $CONFIG;
382 
383  // return table name if configured
384  $config_key = 'db_sequence_'.$sequence;
385
386  if (strlen($CONFIG[$config_key]))
387    return $CONFIG[$config_key];
388 
389  return $sequence;
390  }
391
392
393/**
394 * Check the given string and returns language properties
395 *
396 * @param string Language code
397 * @param string Peropert name
398 * @return string Property value
399 */
400function rcube_language_prop($lang, $prop='lang')
401  {
402  global $INSTALL_PATH;
403  static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
404
405  if (empty($rcube_languages))
406    @include($INSTALL_PATH.'program/localization/index.inc');
407   
408  // check if we have an alias for that language
409  if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
410    $lang = $rcube_language_aliases[$lang];
411   
412  // try the first two chars
413  if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
414    {
415    $lang = substr($lang, 0, 2);
416    $lang = rcube_language_prop($lang);
417    }
418
419  if (!isset($rcube_languages[$lang]))
420    $lang = 'en_US';
421
422  // language has special charset configured
423  if (isset($rcube_charsets[$lang]))
424    $charset = $rcube_charsets[$lang];
425  else
426    $charset = 'UTF-8';   
427
428
429  if ($prop=='charset')
430    return $charset;
431  else
432    return $lang;
433  }
434 
435
436/**
437 * Init output object for GUI and add common scripts.
438 * This will instantiate a rcmail_template object and set
439 * environment vars according to the current session and configuration
440 */
441function rcmail_load_gui()
442  {
443  global $CONFIG, $OUTPUT, $sess_user_lang;
444
445  // init output page
446  $OUTPUT = new rcmail_template($CONFIG, $GLOBALS['_task']);
447  $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
448
449  if (is_array($CONFIG['javascript_config']))
450  {
451    foreach ($CONFIG['javascript_config'] as $js_config_var)
452      $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
453  }
454
455  if (!empty($GLOBALS['_framed']))
456    $OUTPUT->set_env('framed', true);
457
458  // set locale setting
459  rcmail_set_locale($sess_user_lang);
460
461  // set user-selected charset
462  if (!empty($CONFIG['charset']))
463    $OUTPUT->set_charset($CONFIG['charset']);
464   
465  // register common UI objects
466  $OUTPUT->add_handlers(array(
467    'loginform' => 'rcmail_login_form',
468    'username'  => 'rcmail_current_username',
469    'message' => 'rcmail_message_container',
470    'charsetselector' => 'rcmail_charset_selector',
471  ));
472
473  // add some basic label to client
474  if (!$OUTPUT->ajax_call)
475    rcube_add_label('loading', 'movingmessage');
476  }
477
478
479/**
480 * Set localization charset based on the given language.
481 * This also creates a global property for mbstring usage.
482 */
483function rcmail_set_locale($lang)
484  {
485  global $OUTPUT, $MBSTRING;
486  static $s_mbstring_loaded = NULL;
487 
488  // settings for mbstring module (by Tadashi Jokagi)
489  if (is_null($s_mbstring_loaded))
490    $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring");
491  else
492    $MBSTRING = $s_mbstring_loaded = FALSE;
493 
494  if ($MBSTRING)
495    mb_internal_encoding(RCMAIL_CHARSET);
496
497  $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
498  }
499
500
501/**
502 * Auto-select IMAP host based on the posted login information
503 *
504 * @return string Selected IMAP host
505 */
506function rcmail_autoselect_host()
507  {
508  global $CONFIG;
509 
510  $host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
511  if (is_array($host))
512    {
513    list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
514    if (!empty($domain))
515      {
516      foreach ($host as $imap_host => $mail_domains)
517        if (is_array($mail_domains) && in_array($domain, $mail_domains))
518          {
519          $host = $imap_host;
520          break;
521          }
522      }
523
524    // take the first entry if $host is still an array
525    if (is_array($host))
526      $host = array_shift($host);
527    }
528 
529  return $host;
530  }
531
532
533/**
534 * Perfom login to the IMAP server and to the webmail service.
535 * This will also create a new user entry if auto_create_user is configured.
536 *
537 * @param string IMAP user name
538 * @param string IMAP password
539 * @param string IMAP host
540 * @return boolean True on success, False on failure
541 */
542function rcmail_login($user, $pass, $host=NULL)
543  {
544  global $CONFIG, $IMAP, $DB, $USER, $sess_user_lang;
545  $user_id = NULL;
546 
547  if (!$host)
548    $host = $CONFIG['default_host'];
549
550  // Validate that selected host is in the list of configured hosts
551  if (is_array($CONFIG['default_host']))
552    {
553    $allowed = FALSE;
554    foreach ($CONFIG['default_host'] as $key => $host_allowed)
555      {
556      if (!is_numeric($key))
557        $host_allowed = $key;
558      if ($host == $host_allowed)
559        {
560        $allowed = TRUE;
561        break;
562        }
563      }
564    if (!$allowed)
565      return FALSE;
566    }
567  else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
568    return FALSE;
569
570  // parse $host URL
571  $a_host = parse_url($host);
572  if ($a_host['host'])
573    {
574    $host = $a_host['host'];
575    $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
576    $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
577    }
578  else
579    $imap_port = $CONFIG['default_port'];
580
581
582  /* Modify username with domain if required 
583     Inspired by Marco <P0L0_notspam_binware.org>
584  */
585  // Check if we need to add domain
586  if (!empty($CONFIG['username_domain']) && !strpos($user, '@'))
587    {
588    if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
589      $user .= '@'.$CONFIG['username_domain'][$host];
590    else if (is_string($CONFIG['username_domain']))
591      $user .= '@'.$CONFIG['username_domain'];
592    }
593
594  // try to resolve email address from virtuser table   
595  if (!empty($CONFIG['virtuser_file']) && strpos($user, '@'))
596    $user = rcube_user::email2user($user);
597
598  // lowercase username if it's an e-mail address (#1484473)
599  if (strpos($user, '@'))
600    $user = strtolower($user);
601
602  // query if user already registered
603  if ($existing = rcube_user::query($user, $host))
604    $USER = $existing;
605
606  // user already registered -> overwrite username
607  if ($USER->ID)
608    {
609    $user_id = $USER->ID;
610    $user = $USER->data['username'];
611    }
612
613  // exit if IMAP login failed
614  if (!($imap_login  = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
615    return false;
616
617  // user already registered
618  if ($USER->ID)
619    {
620    // get user prefs
621    $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
622
623    // set user specific language
624    if (!empty($USER->data['language']))
625      $sess_user_lang = $_SESSION['user_lang'] = $USER->data['language'];
626     
627    // update user's record
628    $USER->touch();
629    }
630  // create new system user
631  else if ($CONFIG['auto_create_user'])
632    {
633    if ($created = rcube_user::create($user, $host))
634    {
635      $USER = $created;
636     
637      // get existing mailboxes
638      $a_mailboxes = $IMAP->list_mailboxes();
639    }
640    }
641  else
642    {
643    raise_error(array(
644      'code' => 600,
645      'type' => 'php',
646      'file' => "config/main.inc.php",
647      'message' => "Acces denied for new user $user. 'auto_create_user' is disabled"
648      ), true, false);
649    }
650
651  if ($USER->ID)
652    {
653    $_SESSION['user_id']   = $USER->ID;
654    $_SESSION['username']  = $USER->data['username'];
655    $_SESSION['imap_host'] = $host;
656    $_SESSION['imap_port'] = $imap_port;
657    $_SESSION['imap_ssl']  = $imap_ssl;
658    $_SESSION['user_lang'] = $sess_user_lang;
659    $_SESSION['password']  = encrypt_passwd($pass);
660    $_SESSION['login_time'] = mktime();
661
662    // force reloading complete list of subscribed mailboxes
663    rcmail_set_imap_prop();
664    $IMAP->clear_cache('mailboxes');
665
666    if ($CONFIG['create_default_folders'])
667        $IMAP->create_default_folders();
668
669    return TRUE;
670    }
671
672  return FALSE;
673  }
674
675
676/**
677 * Load virtuser table in array
678 *
679 * @return array Virtuser table entries
680 */
681function rcmail_getvirtualfile()
682  {
683  global $CONFIG;
684  if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
685    return FALSE;
686 
687  // read file
688  $a_lines = file($CONFIG['virtuser_file']);
689  return $a_lines;
690  }
691
692
693/**
694 * Find matches of the given pattern in virtuser table
695 *
696 * @param string Regular expression to search for
697 * @return array Matching entries
698 */
699function rcmail_findinvirtual($pattern)
700  {
701  $result = array();
702  $virtual = rcmail_getvirtualfile();
703  if ($virtual==FALSE)
704    return $result;
705
706  // check each line for matches
707  foreach ($virtual as $line)
708    {
709    $line = trim($line);
710    if (empty($line) || $line{0}=='#')
711      continue;
712     
713    if (eregi($pattern, $line))
714      $result[] = $line;
715    }
716
717  return $result;
718  }
719
720
721/**
722 * Overwrite action variable
723 *
724 * @param string New action value
725 */
726function rcmail_overwrite_action($action)
727  {
728  global $OUTPUT;
729  $GLOBALS['_action'] = $action;
730  $OUTPUT->set_env('action', $action);
731  }
732
733
734/**
735 * Compose an URL for a specific action
736 *
737 * @param string  Request action
738 * @param array   More URL parameters
739 * @param string  Request task (omit if the same)
740 * @return The application URL
741 */
742function rcmail_url($action, $p=array(), $task=null)
743{
744  global $MAIN_TASKS, $COMM_PATH;
745  $qstring = '';
746  $base = $COMM_PATH;
747 
748  if ($task && in_array($task, $MAIN_TASKS))
749    $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
750 
751  if (is_array($p))
752    foreach ($p as $key => $val)
753      $qstring .= '&'.urlencode($key).'='.urlencode($val);
754 
755  return $base . ($action ? '&_action='.$action : '') . $qstring;
756}
757
758
759// @deprecated
760function show_message($message, $type='notice', $vars=NULL)
761  {
762  global $OUTPUT;
763  $OUTPUT->show_message($message, $type, $vars);
764  }
765
766
767/**
768 * Encrypt IMAP password using DES encryption
769 *
770 * @param string Password to encrypt
771 * @return string Encryprted string
772 */
773function encrypt_passwd($pass)
774{
775  if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
776    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
777    mcrypt_generic_init($td, get_des_key(), $iv);
778    $cypher = mcrypt_generic($td, $pass);
779    mcrypt_generic_deinit($td);
780    mcrypt_module_close($td);
781  }
782  else if (function_exists('des')) {
783    $cypher = des(get_des_key(), $pass, 1, 0, NULL);
784  }
785  else {
786    $cypher = $pass;
787   
788    raise_error(array(
789      'code' => 500,
790      'type' => 'php',
791      'file' => __FILE__,
792      'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
793      ), true, false);
794  }
795 
796  return base64_encode($cypher);
797}
798
799
800/**
801 * Decrypt IMAP password using DES encryption
802 *
803 * @param string Encrypted password
804 * @return string Plain password
805 */
806function decrypt_passwd($cypher)
807{
808  if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
809    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
810    mcrypt_generic_init($td, get_des_key(), $iv);
811    $pass = mdecrypt_generic($td, base64_decode($cypher));
812    mcrypt_generic_deinit($td);
813    mcrypt_module_close($td);
814  }
815  else if (function_exists('des')) {
816    $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
817  }
818  else {
819    $pass = base64_decode($cypher);
820  }
821 
822  return preg_replace('/\x00/', '', $pass);
823  }
824
825
826/**
827 * Return a 24 byte key for the DES encryption
828 *
829 * @return string DES encryption key
830 */
831function get_des_key()
832  {
833  $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
834  $len = strlen($key);
835 
836  // make sure the key is exactly 24 chars long
837  if ($len<24)
838    $key .= str_repeat('_', 24-$len);
839  else if ($len>24)
840    substr($key, 0, 24);
841 
842  return $key;
843  }
844
845
846/**
847 * Read directory program/localization and return a list of available languages
848 *
849 * @return array List of available localizations
850 */
851function rcube_list_languages()
852  {
853  global $CONFIG, $INSTALL_PATH;
854  static $sa_languages = array();
855
856  if (!sizeof($sa_languages))
857    {
858    @include($INSTALL_PATH.'program/localization/index.inc');
859
860    if ($dh = @opendir($INSTALL_PATH.'program/localization'))
861      {
862      while (($name = readdir($dh)) !== false)
863        {
864        if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
865          continue;
866
867        if ($label = $rcube_languages[$name])
868          $sa_languages[$name] = $label ? $label : $name;
869        }
870      closedir($dh);
871      }
872    }
873  return $sa_languages;
874  }
875
876
877/**
878 * Add a localized label to the client environment
879 */
880function rcube_add_label()
881  {
882  global $OUTPUT;
883 
884  $arg_list = func_get_args();
885  foreach ($arg_list as $i => $name)
886    $OUTPUT->command('add_label', $name, rcube_label($name));
887  }
888
889
890/**
891 * Garbage collector function for temp files.
892 * Remove temp files older than two days
893 */
894function rcmail_temp_gc()
895  {
896  $tmp = unslashify($CONFIG['temp_dir']);
897  $expire = mktime() - 172800;  // expire in 48 hours
898
899  if ($dir = opendir($tmp))
900    {
901    while (($fname = readdir($dir)) !== false)
902      {
903      if ($fname{0} == '.')
904        continue;
905
906      if (filemtime($tmp.'/'.$fname) < $expire)
907        @unlink($tmp.'/'.$fname);
908      }
909
910    closedir($dir);
911    }
912  }
913
914
915/**
916 * Garbage collector for cache entries.
917 * Remove all expired message cache records
918 */
919function rcmail_message_cache_gc()
920  {
921  global $DB, $CONFIG;
922 
923  // no cache lifetime configured
924  if (empty($CONFIG['message_cache_lifetime']))
925    return;
926 
927  // get target timestamp
928  $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
929 
930  $DB->query("DELETE FROM ".get_table_name('messages')."
931             WHERE  created < ".$DB->fromunixtime($ts));
932  }
933
934
935/**
936 * Convert a string from one charset to another.
937 * Uses mbstring and iconv functions if possible
938 *
939 * @param  string Input string
940 * @param  string Suspected charset of the input string
941 * @param  string Target charset to convert to; defaults to RCMAIL_CHARSET
942 * @return Converted string
943 */
944function rcube_charset_convert($str, $from, $to=NULL)
945  {
946  global $MBSTRING;
947  static $convert_warning = false;
948
949  $from = strtoupper($from);
950  $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
951  $error = false; $conv = null;
952
953  if ($from==$to || $str=='' || empty($from))
954    return $str;
955   
956  $aliases = array(
957    'UNKNOWN-8BIT'   => 'ISO-8859-15',
958    'X-UNKNOWN'      => 'ISO-8859-15',
959    'X-USER-DEFINED' => 'ISO-8859-15',
960    'ISO-8859-8-I'   => 'ISO-8859-8',
961    'KS_C_5601-1987' => 'EUC-KR',
962  );
963
964  // convert charset using iconv module 
965  if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
966    {
967    $aliases['GB2312'] = 'GB18030';
968    return iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
969    }
970
971  // convert charset using mbstring module 
972  if ($MBSTRING)
973    {
974    $aliases['UTF-7'] = 'UTF7-IMAP';
975    $aliases['WINDOWS-1257'] = 'ISO-8859-13';
976   
977    // return if convert succeeded
978    if (($out = mb_convert_encoding($str, ($aliases[$to] ? $aliases[$to] : $to), ($aliases[$from] ? $aliases[$from] : $from))) != '')
979      return $out;
980    }
981   
982 
983  if (class_exists('utf8'))
984    $conv = new utf8();
985
986  // convert string to UTF-8
987  if ($from == 'UTF-7')
988    $str = utf7_to_utf8($str);
989  else if (($from == 'ISO-8859-1') && function_exists('utf8_encode'))
990    $str = utf8_encode($str);
991  else if ($from != 'UTF-8' && $conv)
992    {
993    $conv->loadCharset($from);
994    $str = $conv->strToUtf8($str);
995    }
996  else if ($from != 'UTF-8')
997    $error = true;
998
999  // encode string for output
1000  if ($to == 'UTF-7')
1001    return utf8_to_utf7($str);
1002  else if ($to == 'ISO-8859-1' && function_exists('utf8_decode'))
1003    return utf8_decode($str);
1004  else if ($to != 'UTF-8' && $conv)
1005    {
1006    $conv->loadCharset($to);
1007    return $conv->utf8ToStr($str);
1008    }
1009  else if ($to != 'UTF-8')
1010    $error = true;
1011
1012  // report error
1013  if ($error && !$convert_warning)
1014    {
1015    raise_error(array(
1016      'code' => 500,
1017      'type' => 'php',
1018      'file' => __FILE__,
1019      'message' => "Could not convert string charset. Make sure iconv is installed or lib/utf8.class is available"
1020      ), true, false);
1021   
1022    $convert_warning = true;
1023    }
1024 
1025  // return UTF-8 string
1026  return $str;
1027  }
1028
1029
1030/**
1031 * Replacing specials characters to a specific encoding type
1032 *
1033 * @param  string  Input string
1034 * @param  string  Encoding type: text|html|xml|js|url
1035 * @param  string  Replace mode for tags: show|replace|remove
1036 * @param  boolean Convert newlines
1037 * @return The quoted string
1038 */
1039function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
1040  {
1041  global $OUTPUT_TYPE, $OUTPUT;
1042  static $html_encode_arr, $js_rep_table, $xml_rep_table;
1043
1044  if (!$enctype)
1045    $enctype = $GLOBALS['OUTPUT_TYPE'];
1046
1047  // encode for plaintext
1048  if ($enctype=='text')
1049    return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
1050
1051  // encode for HTML output
1052  if ($enctype=='html')
1053    {
1054    if (!$html_encode_arr)
1055      {
1056      $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);       
1057      unset($html_encode_arr['?']);
1058      }
1059
1060    $ltpos = strpos($str, '<');
1061    $encode_arr = $html_encode_arr;
1062
1063    // don't replace quotes and html tags
1064    if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1065      {
1066      unset($encode_arr['"']);
1067      unset($encode_arr['<']);
1068      unset($encode_arr['>']);
1069      unset($encode_arr['&']);
1070      }
1071    else if ($mode=='remove')
1072      $str = strip_tags($str);
1073   
1074    // avoid douple quotation of &
1075    $out = preg_replace('/&amp;([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1076     
1077    return $newlines ? nl2br($out) : $out;
1078    }
1079
1080  if ($enctype=='url')
1081    return rawurlencode($str);
1082
1083  // if the replace tables for XML and JS are not yet defined
1084  if (!$js_rep_table)
1085    {
1086    $js_rep_table = $xml_rep_table = array();
1087    $xml_rep_table['&'] = '&amp;';
1088
1089    for ($c=160; $c<256; $c++)  // can be increased to support more charsets
1090      {
1091      $xml_rep_table[Chr($c)] = "&#$c;";
1092     
1093      if ($OUTPUT->get_charset()=='ISO-8859-1')
1094        $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1095      }
1096
1097    $xml_rep_table['"'] = '&quot;';
1098    }
1099
1100  // encode for XML
1101  if ($enctype=='xml')
1102    return strtr($str, $xml_rep_table);
1103
1104  // encode for javascript use
1105  if ($enctype=='js')
1106    {
1107    if ($OUTPUT->get_charset()!='UTF-8')
1108      $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1109     
1110    return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1111    }
1112
1113  // no encoding given -> return original string
1114  return $str;
1115  }
1116 
1117/**
1118 * Quote a given string.
1119 * Shortcut function for rep_specialchars_output
1120 *
1121 * @return string HTML-quoted string
1122 * @see rep_specialchars_output()
1123 */
1124function Q($str, $mode='strict', $newlines=TRUE)
1125  {
1126  return rep_specialchars_output($str, 'html', $mode, $newlines);
1127  }
1128
1129/**
1130 * Quote a given string for javascript output.
1131 * Shortcut function for rep_specialchars_output
1132 *
1133 * @return string JS-quoted string
1134 * @see rep_specialchars_output()
1135 */
1136function JQ($str)
1137  {
1138  return rep_specialchars_output($str, 'js');
1139  }
1140
1141
1142/**
1143 * Read input value and convert it for internal use
1144 * Performs stripslashes() and charset conversion if necessary
1145 *
1146 * @param  string   Field name to read
1147 * @param  int      Source to get value from (GPC)
1148 * @param  boolean  Allow HTML tags in field value
1149 * @param  string   Charset to convert into
1150 * @return string   Field value or NULL if not available
1151 */
1152function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1153  {
1154  global $OUTPUT;
1155  $value = NULL;
1156 
1157  if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1158    $value = $_GET[$fname];
1159  else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1160    $value = $_POST[$fname];
1161  else if ($source==RCUBE_INPUT_GPC)
1162    {
1163    if (isset($_POST[$fname]))
1164      $value = $_POST[$fname];
1165    else if (isset($_GET[$fname]))
1166      $value = $_GET[$fname];
1167    else if (isset($_COOKIE[$fname]))
1168      $value = $_COOKIE[$fname];
1169    }
1170 
1171  // strip slashes if magic_quotes enabled
1172  if ((bool)get_magic_quotes_gpc())
1173    $value = stripslashes($value);
1174
1175  // remove HTML tags if not allowed   
1176  if (!$allow_html)
1177    $value = strip_tags($value);
1178 
1179  // convert to internal charset
1180  if (is_object($OUTPUT))
1181    return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1182  else
1183    return $value;
1184  }
1185
1186/**
1187 * Remove all non-ascii and non-word chars
1188 * except . and -
1189 */
1190function asciiwords($str)
1191{
1192  return preg_replace('/[^a-z0-9.-_]/i', '', $str);
1193}
1194
1195/**
1196 * Remove single and double quotes from given string
1197 *
1198 * @param string Input value
1199 * @return string Dequoted string
1200 */
1201function strip_quotes($str)
1202{
1203  return preg_replace('/[\'"]/', '', $str);
1204}
1205
1206
1207/**
1208 * Remove new lines characters from given string
1209 *
1210 * @param string Input value
1211 * @return string Stripped string
1212 */
1213function strip_newlines($str)
1214{
1215  return preg_replace('/[\r\n]/', '', $str);
1216}
1217
1218
1219/**
1220 * Check if a specific template exists
1221 *
1222 * @param string Template name
1223 * @return boolean True if template exists
1224 */
1225function template_exists($name)
1226  {
1227  global $CONFIG;
1228  $skin_path = $CONFIG['skin_path'];
1229
1230  // check template file
1231  return is_file("$skin_path/templates/$name.html");
1232  }
1233
1234
1235/**
1236 * Wrapper for rcmail_template::parse()
1237 * @deprecated
1238 */
1239function parse_template($name='main', $exit=true)
1240  {
1241  $GLOBALS['OUTPUT']->parse($name, $exit);
1242  }
1243
1244
1245/**
1246 * Create a HTML table based on the given data
1247 *
1248 * @param  array  Named table attributes
1249 * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
1250 * @param  array  List of cols to show
1251 * @param  string Name of the identifier col
1252 * @return string HTML table code
1253 */
1254function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1255  {
1256  global $DB;
1257 
1258  // allow the following attributes to be added to the <table> tag
1259  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1260 
1261  $table = '<table' . $attrib_str . ">\n";
1262   
1263  // add table title
1264  $table .= "<thead><tr>\n";
1265
1266  foreach ($a_show_cols as $col)
1267    $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1268
1269  $table .= "</tr></thead>\n<tbody>\n";
1270 
1271  $c = 0;
1272  if (!is_array($table_data))
1273    {
1274    while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1275      {
1276      $zebra_class = $c%2 ? 'even' : 'odd';
1277
1278      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1279
1280      // format each col
1281      foreach ($a_show_cols as $col)
1282        {
1283        $cont = Q($sql_arr[$col]);
1284        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1285        }
1286
1287      $table .= "</tr>\n";
1288      $c++;
1289      }
1290    }
1291  else
1292    {
1293    foreach ($table_data as $row_data)
1294      {
1295      $zebra_class = $c%2 ? 'even' : 'odd';
1296
1297      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1298
1299      // format each col
1300      foreach ($a_show_cols as $col)
1301        {
1302        $cont = Q($row_data[$col]);
1303        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1304        }
1305
1306      $table .= "</tr>\n";
1307      $c++;
1308      }
1309    }
1310
1311  // complete message table
1312  $table .= "</tbody></table>\n";
1313 
1314  return $table;
1315  }
1316
1317
1318/**
1319 * Create an edit field for inclusion on a form
1320 *
1321 * @param string col field name
1322 * @param string value field value
1323 * @param array attrib HTML element attributes for field
1324 * @param string type HTML element type (default 'text')
1325 * @return string HTML field definition
1326 */
1327function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1328  {
1329  $fname = '_'.$col;
1330  $attrib['name'] = $fname;
1331 
1332  if ($type=='checkbox')
1333    {
1334    $attrib['value'] = '1';
1335    $input = new checkbox($attrib);
1336    }
1337  else if ($type=='textarea')
1338    {
1339    $attrib['cols'] = $attrib['size'];
1340    $input = new textarea($attrib);
1341    }
1342  else
1343    $input = new textfield($attrib);
1344
1345  // use value from post
1346  if (!empty($_POST[$fname]))
1347    $value = get_input_value($fname, RCUBE_INPUT_POST);
1348
1349  $out = $input->show($value);
1350         
1351  return $out;
1352  }
1353
1354
1355/**
1356 * Return the mail domain configured for the given host
1357 *
1358 * @param string IMAP host
1359 * @return string Resolved SMTP host
1360 */
1361function rcmail_mail_domain($host)
1362  {
1363  global $CONFIG;
1364
1365  $domain = $host;
1366  if (is_array($CONFIG['mail_domain']))
1367    {
1368    if (isset($CONFIG['mail_domain'][$host]))
1369      $domain = $CONFIG['mail_domain'][$host];
1370    }
1371  else if (!empty($CONFIG['mail_domain']))
1372    $domain = $CONFIG['mail_domain'];
1373
1374  return $domain;
1375  }
1376
1377
1378/**
1379 * Replace all css definitions with #container [def]
1380 * and remove css-inlined scripting
1381 *
1382 * @param string CSS source code
1383 * @param string Container ID to use as prefix
1384 * @return string Modified CSS source
1385 */
1386function rcmail_mod_css_styles($source, $container_id, $base_url = '')
1387  {
1388  $a_css_values = array();
1389  $last_pos = 0;
1390 
1391  // ignore the whole block if evil styles are detected
1392  if (stristr($source, 'expression') || stristr($source, 'behavior'))
1393    return '';
1394
1395  // cut out all contents between { and }
1396  while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1397  {
1398    $key = sizeof($a_css_values);
1399    $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1400    $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1401    $last_pos = $pos+2;
1402  }
1403
1404  // remove html comments and add #container to each tag selector.
1405  // also replace body definition because we also stripped off the <body> tag
1406  $styles = preg_replace(
1407    array(
1408      '/(^\s*<!--)|(-->\s*$)/',
1409      '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1410      '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
1411      '/<<str_replacement\[([0-9]+)\]>>/e',
1412      "/$container_id\s+body/i"
1413    ),
1414    array(
1415      '',
1416      "\\1#$container_id \\2",
1417      "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
1418      "\$a_css_values[\\1]",
1419      "$container_id div.rcmBody"
1420    ),
1421    $source);
1422
1423  return $styles;
1424  }
1425
1426/**
1427 * Try to autodetect operating system and find the correct line endings
1428 *
1429 * @return string The appropriate mail header delimiter
1430 */
1431function rcmail_header_delm()
1432{
1433  global $CONFIG;
1434 
1435  // use the configured delimiter for headers
1436  if (!empty($CONFIG['mail_header_delimiter']))
1437    return $CONFIG['mail_header_delimiter'];
1438  else if (strtolower(substr(PHP_OS, 0, 3)=='win'))
1439    return "\r\n";
1440  else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
1441    return "\r\n";
1442  else   
1443    return "\n";
1444}
1445
1446
1447/**
1448 * Compose a valid attribute string for HTML tags
1449 *
1450 * @param array Named tag attributes
1451 * @param array List of allowed attributes
1452 * @return string HTML formatted attribute string
1453 */
1454function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1455  {
1456  // allow the following attributes to be added to the <iframe> tag
1457  $attrib_str = '';
1458  foreach ($allowed_attribs as $a)
1459    if (isset($attrib[$a]))
1460      $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
1461
1462  return $attrib_str;
1463  }
1464
1465
1466/**
1467 * Convert a HTML attribute string attributes to an associative array (name => value)
1468 *
1469 * @param string Input string
1470 * @return array Key-value pairs of parsed attributes
1471 */
1472function parse_attrib_string($str)
1473  {
1474  $attrib = array();
1475  preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1476
1477  // convert attributes to an associative array (name => value)
1478  if ($regs)
1479    foreach ($regs as $attr)
1480      $attrib[strtolower($attr[1])] = $attr[3];
1481
1482  return $attrib;
1483  }
1484
1485
1486/**
1487 * Convert the given date to a human readable form
1488 * This uses the date formatting properties from config
1489 *
1490 * @param mixed Date representation (string or timestamp)
1491 * @param string Date format to use
1492 * @return string Formatted date string
1493 */
1494function format_date($date, $format=NULL)
1495  {
1496  global $CONFIG, $sess_user_lang;
1497 
1498  $ts = NULL;
1499 
1500  if (is_numeric($date))
1501    $ts = $date;
1502  else if (!empty($date))
1503    $ts = @strtotime($date);
1504   
1505  if (empty($ts))
1506    return '';
1507   
1508  // get user's timezone
1509  $tz = $CONFIG['timezone'];
1510  if ($CONFIG['dst_active'])
1511    $tz++;
1512
1513  // convert time to user's timezone
1514  $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1515 
1516  // get current timestamp in user's timezone
1517  $now = time();  // local time
1518  $now -= (int)date('Z'); // make GMT time
1519  $now += ($tz * 3600); // user's time
1520  $now_date = getdate($now);
1521
1522  $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1523  $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1524
1525  // define date format depending on current time 
1526  if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1527    return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1528  else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1529    $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1530  else if (!$format)
1531    $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1532
1533
1534  // parse format string manually in order to provide localized weekday and month names
1535  // an alternative would be to convert the date() format string to fit with strftime()
1536  $out = '';
1537  for($i=0; $i<strlen($format); $i++)
1538    {
1539    if ($format{$i}=='\\')  // skip escape chars
1540      continue;
1541   
1542    // write char "as-is"
1543    if ($format{$i}==' ' || $format{$i-1}=='\\')
1544      $out .= $format{$i};
1545    // weekday (short)
1546    else if ($format{$i}=='D')
1547      $out .= rcube_label(strtolower(date('D', $timestamp)));
1548    // weekday long
1549    else if ($format{$i}=='l')
1550      $out .= rcube_label(strtolower(date('l', $timestamp)));
1551    // month name (short)
1552    else if ($format{$i}=='M')
1553      $out .= rcube_label(strtolower(date('M', $timestamp)));
1554    // month name (long)
1555    else if ($format{$i}=='F')
1556      $out .= rcube_label(strtolower(date('F', $timestamp)));
1557    else
1558      $out .= date($format{$i}, $timestamp);
1559    }
1560 
1561  return $out;
1562  }
1563
1564
1565/**
1566 * Compose a valid representaion of name and e-mail address
1567 *
1568 * @param string E-mail address
1569 * @param string Person name
1570 * @return string Formatted string
1571 */
1572function format_email_recipient($email, $name='')
1573  {
1574  if ($name && $name != $email)
1575    {
1576    // Special chars as defined by RFC 822 need to in quoted string (or escaped).
1577    return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
1578    }
1579  else
1580    return $email;
1581  }
1582
1583
1584
1585/****** debugging functions ********/
1586
1587
1588/**
1589 * Print or write debug messages
1590 *
1591 * @param mixed Debug message or data
1592 */
1593function console($msg)
1594  {
1595  if (!is_string($msg))
1596    $msg = var_export($msg, true);
1597
1598  if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1599    write_log('console', $msg);
1600  else if ($GLOBALS['REMOTE_REQUEST'])
1601    print "/*\n $msg \n*/\n";
1602  else
1603    {
1604    print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1605    print $msg;
1606    print "</pre></div>\n";
1607    }
1608  }
1609
1610
1611/**
1612 * Append a line to a logfile in the logs directory.
1613 * Date will be added automatically to the line.
1614 *
1615 * @param $name Name of logfile
1616 * @param $line Line to append
1617 */
1618function write_log($name, $line)
1619  {
1620  global $CONFIG, $INSTALL_PATH;
1621
1622  if (!is_string($line))
1623    $line = var_export($line, true);
1624 
1625  $log_entry = sprintf("[%s]: %s\n",
1626                 date("d-M-Y H:i:s O", mktime()),
1627                 $line);
1628                 
1629  if (empty($CONFIG['log_dir']))
1630    $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1631     
1632  // try to open specific log file for writing
1633  if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))   
1634    {
1635    fwrite($fp, $log_entry);
1636    fclose($fp);
1637    }
1638  }
1639
1640
1641/**
1642 * @access private
1643 */
1644function rcube_timer()
1645  {
1646  list($usec, $sec) = explode(" ", microtime());
1647  return ((float)$usec + (float)$sec);
1648  }
1649 
1650
1651/**
1652 * @access private
1653 */
1654function rcube_print_time($timer, $label='Timer')
1655  {
1656  static $print_count = 0;
1657 
1658  $print_count++;
1659  $now = rcube_timer();
1660  $diff = $now-$timer;
1661 
1662  if (empty($label))
1663    $label = 'Timer '.$print_count;
1664 
1665  console(sprintf("%s: %0.4f sec", $label, $diff));
1666  }
1667
1668
1669/**
1670 * Return the mailboxlist in HTML
1671 *
1672 * @param array Named parameters
1673 * @return string HTML code for the gui object
1674 */
1675function rcmail_mailbox_list($attrib)
1676  {
1677  global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1678  static $s_added_script = FALSE;
1679  static $a_mailboxes;
1680
1681  // add some labels to client
1682  rcube_add_label('purgefolderconfirm');
1683  rcube_add_label('deletemessagesconfirm');
1684 
1685// $mboxlist_start = rcube_timer();
1686 
1687  $type = $attrib['type'] ? $attrib['type'] : 'ul';
1688  $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1689                                  array('style', 'class', 'id');
1690                                 
1691  if ($type=='ul' && !$attrib['id'])
1692    $attrib['id'] = 'rcmboxlist';
1693
1694  // allow the following attributes to be added to the <ul> tag
1695  $attrib_str = create_attrib_string($attrib, $add_attrib);
1696 
1697  $out = '<' . $type . $attrib_str . ">\n";
1698 
1699  // add no-selection option
1700  if ($type=='select' && $attrib['noselection'])
1701    $out .= sprintf('<option value="0">%s</option>'."\n",
1702                    rcube_label($attrib['noselection']));
1703 
1704  // get mailbox list
1705  $mbox_name = $IMAP->get_mailbox_name();
1706 
1707  // build the folders tree
1708  if (empty($a_mailboxes))
1709    {
1710    // get mailbox list
1711    $a_folders = $IMAP->list_mailboxes();
1712    $delimiter = $IMAP->get_hierarchy_delimiter();
1713    $a_mailboxes = array();
1714
1715// rcube_print_time($mboxlist_start, 'list_mailboxes()');
1716
1717    foreach ($a_folders as $folder)
1718      rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1719    }
1720
1721// var_dump($a_mailboxes);
1722
1723  if ($type=='select')
1724    $out .= rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength']);
1725   else
1726    $out .= rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $attrib['maxlength']);
1727
1728// rcube_print_time($mboxlist_start, 'render_folder_tree()');
1729
1730
1731  if ($type=='ul')
1732    $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1733
1734  return $out . "</$type>";
1735  }
1736
1737
1738
1739
1740/**
1741 * Create a hierarchical array of the mailbox list
1742 * @access private
1743 */
1744function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1745  {
1746  $pos = strpos($folder, $delm);
1747  if ($pos !== false)
1748    {
1749    $subFolders = substr($folder, $pos+1);
1750    $currentFolder = substr($folder, 0, $pos);
1751    }
1752  else
1753    {
1754    $subFolders = false;
1755    $currentFolder = $folder;
1756    }
1757
1758  $path .= $currentFolder;
1759
1760  if (!isset($arrFolders[$currentFolder]))
1761    {
1762    $arrFolders[$currentFolder] = array('id' => $path,
1763                                        'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1764                                        'folders' => array());
1765    }
1766
1767  if (!empty($subFolders))
1768    rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1769  }
1770 
1771
1772/**
1773 * Return html for a structured list &lt;ul&gt; for the mailbox tree
1774 * @access private
1775 */
1776function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1777  {
1778  global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1779
1780  $idx = 0;
1781  $out = '';
1782  foreach ($arrFolders as $key => $folder)
1783    {
1784    $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1785    $title = '';
1786
1787    if ($folder_class = rcmail_folder_classname($folder['id']))
1788      $foldername = rcube_label($folder_class);
1789    else
1790      {
1791      $foldername = $folder['name'];
1792
1793      // shorten the folder name to a given length
1794      if ($maxlength && $maxlength>1)
1795        {
1796        $fname = abbreviate_string($foldername, $maxlength);
1797        if ($fname != $foldername)
1798          $title = ' title="'.Q($foldername).'"';
1799        $foldername = $fname;
1800        }
1801      }
1802
1803    // make folder name safe for ids and class names
1804    $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1805    $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_class ? $folder_class : strtolower($folder['id']));
1806
1807    // set special class for Sent, Drafts, Trash and Junk
1808    if ($folder['id']==$CONFIG['sent_mbox'])
1809      $class_name = 'sent';
1810    else if ($folder['id']==$CONFIG['drafts_mbox'])
1811      $class_name = 'drafts';
1812    else if ($folder['id']==$CONFIG['trash_mbox'])
1813      $class_name = 'trash';
1814    else if ($folder['id']==$CONFIG['junk_mbox'])
1815      $class_name = 'junk';
1816
1817    $js_name = htmlspecialchars(JQ($folder['id']));
1818    $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1819                    ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1820                    ' onmouseover="return %s.focus_folder(\'%s\')"' .
1821                    ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1822                    ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1823                    $folder_id,
1824                    $class_name,
1825                    $zebra_class,
1826                    $unread_count ? ' unread' : '',
1827                    $folder['id']==$mbox_name ? ' selected' : '',
1828                    Q(rcmail_url('', array('_mbox' => $folder['id']))),
1829                    JS_OBJECT_NAME,
1830                    $js_name,
1831                    JS_OBJECT_NAME,
1832                    $js_name,
1833                    JS_OBJECT_NAME,
1834                    $js_name,
1835                    JS_OBJECT_NAME,
1836                    $js_name,
1837                    $title,
1838                    Q($foldername));
1839
1840    if (!empty($folder['folders']))
1841      $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1842
1843    $out .= "</li>\n";
1844    $idx++;
1845    }
1846
1847  return $out;
1848  }
1849
1850
1851/**
1852 * Return html for a flat list <select> for the mailbox tree
1853 * @access private
1854 */
1855function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1856  {
1857  global $IMAP, $OUTPUT;
1858
1859  $idx = 0;
1860  $out = '';
1861  foreach ($arrFolders as $key=>$folder)
1862    {
1863    if ($folder_class = rcmail_folder_classname($folder['id']))
1864      $foldername = rcube_label($folder_class);
1865    else
1866      {
1867      $foldername = $folder['name'];
1868     
1869      // shorten the folder name to a given length
1870      if ($maxlength && $maxlength>1)
1871        $foldername = abbreviate_string($foldername, $maxlength);
1872      }
1873
1874    $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1875                    htmlspecialchars($folder['id']),
1876                    str_repeat('&nbsp;', $nestLevel*4),
1877                    Q($foldername));
1878
1879    if (!empty($folder['folders']))
1880      $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $nestLevel+1);
1881
1882    $idx++;
1883    }
1884
1885  return $out;
1886  }
1887
1888
1889/**
1890 * Return internal name for the given folder if it matches the configured special folders
1891 * @access private
1892 */
1893function rcmail_folder_classname($folder_id)
1894{
1895  global $CONFIG;
1896
1897  $cname = null;
1898  $folder_lc = strtolower($folder_id);
1899 
1900  // for these mailboxes we have localized labels and css classes
1901  foreach (array('inbox', 'sent', 'drafts', 'trash', 'junk') as $smbx)
1902  {
1903    if ($folder_lc == $smbx || $folder_id == $CONFIG[$smbx.'_mbox'])
1904      $cname = $smbx;
1905  }
1906 
1907  return $cname;
1908}
1909
1910
1911/**
1912 * Try to localize the given IMAP folder name.
1913 * UTF-7 decode it in case no localized text was found
1914 *
1915 * @param string Folder name
1916 * @return string Localized folder name in UTF-8 encoding
1917 */
1918function rcmail_localize_foldername($name)
1919{
1920  if ($folder_class = rcmail_folder_classname($name))
1921    return rcube_label($folder_class);
1922  else
1923    return rcube_charset_convert($name, 'UTF-7');
1924}
1925
1926
1927?>
Note: See TracBrowser for help on using the repository browser.