source: github/program/include/main.inc @ 17b5fb7

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 17b5fb7 was 17b5fb7, checked in by thomascube <thomas@…>, 5 years ago

Add configurable default charset for message decoding

  • Property mode set to 100644
File size: 49.1 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    'GB2312'         => 'GB18030'
963  );
964
965  // convert charset using iconv module 
966  if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
967    {
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    $mb_map = $aliases + array('UTF-7' => 'UTF7-IMAP');
975   
976    // return if convert succeeded
977    if (($out = mb_convert_encoding($str, ($mb_map[$to] ? $mb_map[$to] : $to), ($mb_map[$from] ? $mb_map[$from] : $from))) != '')
978      return $out;
979    }
980   
981 
982  if (class_exists('utf8'))
983    $conv = new utf8();
984
985  // convert string to UTF-8
986  if ($from == 'UTF-7')
987    $str = utf7_to_utf8($str);
988  else if (($from == 'ISO-8859-1') && function_exists('utf8_encode'))
989    $str = utf8_encode($str);
990  else if ($from != 'UTF-8' && $conv)
991    {
992    $conv->loadCharset($from);
993    $str = $conv->strToUtf8($str);
994    }
995  else if ($from != 'UTF-8')
996    $error = true;
997
998  // encode string for output
999  if ($to == 'UTF-7')
1000    return utf8_to_utf7($str);
1001  else if ($to == 'ISO-8859-1' && function_exists('utf8_decode'))
1002    return utf8_decode($str);
1003  else if ($to != 'UTF-8' && $conv)
1004    {
1005    $conv->loadCharset($to);
1006    return $conv->utf8ToStr($str);
1007    }
1008  else if ($to != 'UTF-8')
1009    $error = true;
1010
1011  // report error
1012  if ($error && !$convert_warning)
1013    {
1014    raise_error(array(
1015      'code' => 500,
1016      'type' => 'php',
1017      'file' => __FILE__,
1018      'message' => "Could not convert string charset. Make sure iconv is installed or lib/utf8.class is available"
1019      ), true, false);
1020   
1021    $convert_warning = true;
1022    }
1023 
1024  // return UTF-8 string
1025  return $str;
1026  }
1027
1028
1029/**
1030 * Replacing specials characters to a specific encoding type
1031 *
1032 * @param  string  Input string
1033 * @param  string  Encoding type: text|html|xml|js|url
1034 * @param  string  Replace mode for tags: show|replace|remove
1035 * @param  boolean Convert newlines
1036 * @return The quoted string
1037 */
1038function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
1039  {
1040  global $OUTPUT_TYPE, $OUTPUT;
1041  static $html_encode_arr, $js_rep_table, $xml_rep_table;
1042
1043  if (!$enctype)
1044    $enctype = $GLOBALS['OUTPUT_TYPE'];
1045
1046  // encode for plaintext
1047  if ($enctype=='text')
1048    return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
1049
1050  // encode for HTML output
1051  if ($enctype=='html')
1052    {
1053    if (!$html_encode_arr)
1054      {
1055      $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);       
1056      unset($html_encode_arr['?']);
1057      }
1058
1059    $ltpos = strpos($str, '<');
1060    $encode_arr = $html_encode_arr;
1061
1062    // don't replace quotes and html tags
1063    if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1064      {
1065      unset($encode_arr['"']);
1066      unset($encode_arr['<']);
1067      unset($encode_arr['>']);
1068      unset($encode_arr['&']);
1069      }
1070    else if ($mode=='remove')
1071      $str = strip_tags($str);
1072   
1073    // avoid douple quotation of &
1074    $out = preg_replace('/&amp;([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1075     
1076    return $newlines ? nl2br($out) : $out;
1077    }
1078
1079  if ($enctype=='url')
1080    return rawurlencode($str);
1081
1082  // if the replace tables for XML and JS are not yet defined
1083  if (!$js_rep_table)
1084    {
1085    $js_rep_table = $xml_rep_table = array();
1086    $xml_rep_table['&'] = '&amp;';
1087
1088    for ($c=160; $c<256; $c++)  // can be increased to support more charsets
1089      {
1090      $xml_rep_table[Chr($c)] = "&#$c;";
1091     
1092      if ($OUTPUT->get_charset()=='ISO-8859-1')
1093        $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1094      }
1095
1096    $xml_rep_table['"'] = '&quot;';
1097    }
1098
1099  // encode for XML
1100  if ($enctype=='xml')
1101    return strtr($str, $xml_rep_table);
1102
1103  // encode for javascript use
1104  if ($enctype=='js')
1105    {
1106    if ($OUTPUT->get_charset()!='UTF-8')
1107      $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1108     
1109    return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1110    }
1111
1112  // no encoding given -> return original string
1113  return $str;
1114  }
1115 
1116/**
1117 * Quote a given string.
1118 * Shortcut function for rep_specialchars_output
1119 *
1120 * @return string HTML-quoted string
1121 * @see rep_specialchars_output()
1122 */
1123function Q($str, $mode='strict', $newlines=TRUE)
1124  {
1125  return rep_specialchars_output($str, 'html', $mode, $newlines);
1126  }
1127
1128/**
1129 * Quote a given string for javascript output.
1130 * Shortcut function for rep_specialchars_output
1131 *
1132 * @return string JS-quoted string
1133 * @see rep_specialchars_output()
1134 */
1135function JQ($str)
1136  {
1137  return rep_specialchars_output($str, 'js');
1138  }
1139
1140
1141/**
1142 * Read input value and convert it for internal use
1143 * Performs stripslashes() and charset conversion if necessary
1144 *
1145 * @param  string   Field name to read
1146 * @param  int      Source to get value from (GPC)
1147 * @param  boolean  Allow HTML tags in field value
1148 * @param  string   Charset to convert into
1149 * @return string   Field value or NULL if not available
1150 */
1151function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1152  {
1153  global $OUTPUT;
1154  $value = NULL;
1155 
1156  if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1157    $value = $_GET[$fname];
1158  else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1159    $value = $_POST[$fname];
1160  else if ($source==RCUBE_INPUT_GPC)
1161    {
1162    if (isset($_POST[$fname]))
1163      $value = $_POST[$fname];
1164    else if (isset($_GET[$fname]))
1165      $value = $_GET[$fname];
1166    else if (isset($_COOKIE[$fname]))
1167      $value = $_COOKIE[$fname];
1168    }
1169 
1170  // strip slashes if magic_quotes enabled
1171  if ((bool)get_magic_quotes_gpc())
1172    $value = stripslashes($value);
1173
1174  // remove HTML tags if not allowed   
1175  if (!$allow_html)
1176    $value = strip_tags($value);
1177 
1178  // convert to internal charset
1179  if (is_object($OUTPUT))
1180    return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1181  else
1182    return $value;
1183  }
1184
1185/**
1186 * Remove all non-ascii and non-word chars
1187 * except . and -
1188 */
1189function asciiwords($str)
1190{
1191  return preg_replace('/[^a-z0-9.-_]/i', '', $str);
1192}
1193
1194/**
1195 * Remove single and double quotes from given string
1196 *
1197 * @param string Input value
1198 * @return string Dequoted string
1199 */
1200function strip_quotes($str)
1201{
1202  return preg_replace('/[\'"]/', '', $str);
1203}
1204
1205
1206/**
1207 * Remove new lines characters from given string
1208 *
1209 * @param string Input value
1210 * @return string Stripped string
1211 */
1212function strip_newlines($str)
1213{
1214  return preg_replace('/[\r\n]/', '', $str);
1215}
1216
1217
1218/**
1219 * Check if a specific template exists
1220 *
1221 * @param string Template name
1222 * @return boolean True if template exists
1223 */
1224function template_exists($name)
1225  {
1226  global $CONFIG;
1227  $skin_path = $CONFIG['skin_path'];
1228
1229  // check template file
1230  return is_file("$skin_path/templates/$name.html");
1231  }
1232
1233
1234/**
1235 * Wrapper for rcmail_template::parse()
1236 * @deprecated
1237 */
1238function parse_template($name='main', $exit=true)
1239  {
1240  $GLOBALS['OUTPUT']->parse($name, $exit);
1241  }
1242
1243
1244/**
1245 * Create a HTML table based on the given data
1246 *
1247 * @param  array  Named table attributes
1248 * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
1249 * @param  array  List of cols to show
1250 * @param  string Name of the identifier col
1251 * @return string HTML table code
1252 */
1253function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1254  {
1255  global $DB;
1256 
1257  // allow the following attributes to be added to the <table> tag
1258  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1259 
1260  $table = '<table' . $attrib_str . ">\n";
1261   
1262  // add table title
1263  $table .= "<thead><tr>\n";
1264
1265  foreach ($a_show_cols as $col)
1266    $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1267
1268  $table .= "</tr></thead>\n<tbody>\n";
1269 
1270  $c = 0;
1271  if (!is_array($table_data))
1272    {
1273    while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1274      {
1275      $zebra_class = $c%2 ? 'even' : 'odd';
1276
1277      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1278
1279      // format each col
1280      foreach ($a_show_cols as $col)
1281        {
1282        $cont = Q($sql_arr[$col]);
1283        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1284        }
1285
1286      $table .= "</tr>\n";
1287      $c++;
1288      }
1289    }
1290  else
1291    {
1292    foreach ($table_data as $row_data)
1293      {
1294      $zebra_class = $c%2 ? 'even' : 'odd';
1295
1296      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1297
1298      // format each col
1299      foreach ($a_show_cols as $col)
1300        {
1301        $cont = Q($row_data[$col]);
1302        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1303        }
1304
1305      $table .= "</tr>\n";
1306      $c++;
1307      }
1308    }
1309
1310  // complete message table
1311  $table .= "</tbody></table>\n";
1312 
1313  return $table;
1314  }
1315
1316
1317/**
1318 * Create an edit field for inclusion on a form
1319 *
1320 * @param string col field name
1321 * @param string value field value
1322 * @param array attrib HTML element attributes for field
1323 * @param string type HTML element type (default 'text')
1324 * @return string HTML field definition
1325 */
1326function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1327  {
1328  $fname = '_'.$col;
1329  $attrib['name'] = $fname;
1330 
1331  if ($type=='checkbox')
1332    {
1333    $attrib['value'] = '1';
1334    $input = new checkbox($attrib);
1335    }
1336  else if ($type=='textarea')
1337    {
1338    $attrib['cols'] = $attrib['size'];
1339    $input = new textarea($attrib);
1340    }
1341  else
1342    $input = new textfield($attrib);
1343
1344  // use value from post
1345  if (!empty($_POST[$fname]))
1346    $value = get_input_value($fname, RCUBE_INPUT_POST);
1347
1348  $out = $input->show($value);
1349         
1350  return $out;
1351  }
1352
1353
1354/**
1355 * Return the mail domain configured for the given host
1356 *
1357 * @param string IMAP host
1358 * @return string Resolved SMTP host
1359 */
1360function rcmail_mail_domain($host)
1361  {
1362  global $CONFIG;
1363
1364  $domain = $host;
1365  if (is_array($CONFIG['mail_domain']))
1366    {
1367    if (isset($CONFIG['mail_domain'][$host]))
1368      $domain = $CONFIG['mail_domain'][$host];
1369    }
1370  else if (!empty($CONFIG['mail_domain']))
1371    $domain = $CONFIG['mail_domain'];
1372
1373  return $domain;
1374  }
1375
1376
1377/**
1378 * Replace all css definitions with #container [def]
1379 *
1380 * @param string CSS source code
1381 * @param string Container ID to use as prefix
1382 * @return string Modified CSS source
1383 */
1384function rcmail_mod_css_styles($source, $container_id, $base_url = '')
1385  {
1386  $a_css_values = array();
1387  $last_pos = 0;
1388
1389  // cut out all contents between { and }
1390  while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1391  {
1392    $key = sizeof($a_css_values);
1393    $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1394    $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1395    $last_pos = $pos+2;
1396  }
1397
1398  // remove html commends and add #container to each tag selector.
1399  // also replace body definition because we also stripped off the <body> tag
1400  $styles = preg_replace(
1401    array(
1402      '/(^\s*<!--)|(-->\s*$)/',
1403      '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1404      '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
1405      '/<<str_replacement\[([0-9]+)\]>>/e',
1406      "/$container_id\s+body/i"
1407    ),
1408    array(
1409      '',
1410      "\\1#$container_id \\2",
1411      "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
1412      "\$a_css_values[\\1]",
1413      "$container_id div.rcmBody"
1414    ),
1415    $source);
1416
1417  return $styles;
1418  }
1419
1420/**
1421 * Try to autodetect operating system and find the correct line endings
1422 *
1423 * @return string The appropriate mail header delimiter
1424 */
1425function rcmail_header_delm()
1426{
1427  global $CONFIG;
1428 
1429  // use the configured delimiter for headers
1430  if (!empty($CONFIG['mail_header_delimiter']))
1431    return $CONFIG['mail_header_delimiter'];
1432  else if (strtolower(substr(PHP_OS, 0, 3)=='win'))
1433    return "\r\n";
1434  else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
1435    return "\r\n";
1436  else   
1437    return "\n";
1438}
1439
1440
1441/**
1442 * Compose a valid attribute string for HTML tags
1443 *
1444 * @param array Named tag attributes
1445 * @param array List of allowed attributes
1446 * @return string HTML formatted attribute string
1447 */
1448function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1449  {
1450  // allow the following attributes to be added to the <iframe> tag
1451  $attrib_str = '';
1452  foreach ($allowed_attribs as $a)
1453    if (isset($attrib[$a]))
1454      $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
1455
1456  return $attrib_str;
1457  }
1458
1459
1460/**
1461 * Convert a HTML attribute string attributes to an associative array (name => value)
1462 *
1463 * @param string Input string
1464 * @return array Key-value pairs of parsed attributes
1465 */
1466function parse_attrib_string($str)
1467  {
1468  $attrib = array();
1469  preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1470
1471  // convert attributes to an associative array (name => value)
1472  if ($regs)
1473    foreach ($regs as $attr)
1474      $attrib[strtolower($attr[1])] = $attr[3];
1475
1476  return $attrib;
1477  }
1478
1479
1480/**
1481 * Convert the given date to a human readable form
1482 * This uses the date formatting properties from config
1483 *
1484 * @param mixed Date representation (string or timestamp)
1485 * @param string Date format to use
1486 * @return string Formatted date string
1487 */
1488function format_date($date, $format=NULL)
1489  {
1490  global $CONFIG, $sess_user_lang;
1491 
1492  $ts = NULL;
1493 
1494  if (is_numeric($date))
1495    $ts = $date;
1496  else if (!empty($date))
1497    $ts = @strtotime($date);
1498   
1499  if (empty($ts))
1500    return '';
1501   
1502  // get user's timezone
1503  $tz = $CONFIG['timezone'];
1504  if ($CONFIG['dst_active'])
1505    $tz++;
1506
1507  // convert time to user's timezone
1508  $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1509 
1510  // get current timestamp in user's timezone
1511  $now = time();  // local time
1512  $now -= (int)date('Z'); // make GMT time
1513  $now += ($tz * 3600); // user's time
1514  $now_date = getdate($now);
1515
1516  $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1517  $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1518
1519  // define date format depending on current time 
1520  if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1521    return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1522  else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1523    $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1524  else if (!$format)
1525    $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1526
1527
1528  // parse format string manually in order to provide localized weekday and month names
1529  // an alternative would be to convert the date() format string to fit with strftime()
1530  $out = '';
1531  for($i=0; $i<strlen($format); $i++)
1532    {
1533    if ($format{$i}=='\\')  // skip escape chars
1534      continue;
1535   
1536    // write char "as-is"
1537    if ($format{$i}==' ' || $format{$i-1}=='\\')
1538      $out .= $format{$i};
1539    // weekday (short)
1540    else if ($format{$i}=='D')
1541      $out .= rcube_label(strtolower(date('D', $timestamp)));
1542    // weekday long
1543    else if ($format{$i}=='l')
1544      $out .= rcube_label(strtolower(date('l', $timestamp)));
1545    // month name (short)
1546    else if ($format{$i}=='M')
1547      $out .= rcube_label(strtolower(date('M', $timestamp)));
1548    // month name (long)
1549    else if ($format{$i}=='F')
1550      $out .= rcube_label(strtolower(date('F', $timestamp)));
1551    else
1552      $out .= date($format{$i}, $timestamp);
1553    }
1554 
1555  return $out;
1556  }
1557
1558
1559/**
1560 * Compose a valid representaion of name and e-mail address
1561 *
1562 * @param string E-mail address
1563 * @param string Person name
1564 * @return string Formatted string
1565 */
1566function format_email_recipient($email, $name='')
1567  {
1568  if ($name && $name != $email)
1569    return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
1570  else
1571    return $email;
1572  }
1573
1574
1575
1576/****** debugging functions ********/
1577
1578
1579/**
1580 * Print or write debug messages
1581 *
1582 * @param mixed Debug message or data
1583 */
1584function console($msg)
1585  {
1586  if (!is_string($msg))
1587    $msg = var_export($msg, true);
1588
1589  if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1590    write_log('console', $msg);
1591  else if ($GLOBALS['REMOTE_REQUEST'])
1592    print "/*\n $msg \n*/\n";
1593  else
1594    {
1595    print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1596    print $msg;
1597    print "</pre></div>\n";
1598    }
1599  }
1600
1601
1602/**
1603 * Append a line to a logfile in the logs directory.
1604 * Date will be added automatically to the line.
1605 *
1606 * @param $name Name of logfile
1607 * @param $line Line to append
1608 */
1609function write_log($name, $line)
1610  {
1611  global $CONFIG, $INSTALL_PATH;
1612
1613  if (!is_string($line))
1614    $line = var_export($line, true);
1615 
1616  $log_entry = sprintf("[%s]: %s\n",
1617                 date("d-M-Y H:i:s O", mktime()),
1618                 $line);
1619                 
1620  if (empty($CONFIG['log_dir']))
1621    $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1622     
1623  // try to open specific log file for writing
1624  if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))   
1625    {
1626    fwrite($fp, $log_entry);
1627    fclose($fp);
1628    }
1629  }
1630
1631
1632/**
1633 * @access private
1634 */
1635function rcube_timer()
1636  {
1637  list($usec, $sec) = explode(" ", microtime());
1638  return ((float)$usec + (float)$sec);
1639  }
1640 
1641
1642/**
1643 * @access private
1644 */
1645function rcube_print_time($timer, $label='Timer')
1646  {
1647  static $print_count = 0;
1648 
1649  $print_count++;
1650  $now = rcube_timer();
1651  $diff = $now-$timer;
1652 
1653  if (empty($label))
1654    $label = 'Timer '.$print_count;
1655 
1656  console(sprintf("%s: %0.4f sec", $label, $diff));
1657  }
1658
1659
1660/**
1661 * Return the mailboxlist in HTML
1662 *
1663 * @param array Named parameters
1664 * @return string HTML code for the gui object
1665 */
1666function rcmail_mailbox_list($attrib)
1667  {
1668  global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1669  static $s_added_script = FALSE;
1670  static $a_mailboxes;
1671
1672  // add some labels to client
1673  rcube_add_label('purgefolderconfirm');
1674  rcube_add_label('deletemessagesconfirm');
1675 
1676// $mboxlist_start = rcube_timer();
1677 
1678  $type = $attrib['type'] ? $attrib['type'] : 'ul';
1679  $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1680                                  array('style', 'class', 'id');
1681                                 
1682  if ($type=='ul' && !$attrib['id'])
1683    $attrib['id'] = 'rcmboxlist';
1684
1685  // allow the following attributes to be added to the <ul> tag
1686  $attrib_str = create_attrib_string($attrib, $add_attrib);
1687 
1688  $out = '<' . $type . $attrib_str . ">\n";
1689 
1690  // add no-selection option
1691  if ($type=='select' && $attrib['noselection'])
1692    $out .= sprintf('<option value="0">%s</option>'."\n",
1693                    rcube_label($attrib['noselection']));
1694 
1695  // get mailbox list
1696  $mbox_name = $IMAP->get_mailbox_name();
1697 
1698  // build the folders tree
1699  if (empty($a_mailboxes))
1700    {
1701    // get mailbox list
1702    $a_folders = $IMAP->list_mailboxes();
1703    $delimiter = $IMAP->get_hierarchy_delimiter();
1704    $a_mailboxes = array();
1705
1706// rcube_print_time($mboxlist_start, 'list_mailboxes()');
1707
1708    foreach ($a_folders as $folder)
1709      rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1710    }
1711
1712// var_dump($a_mailboxes);
1713
1714  if ($type=='select')
1715    $out .= rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength']);
1716   else
1717    $out .= rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $attrib['maxlength']);
1718
1719// rcube_print_time($mboxlist_start, 'render_folder_tree()');
1720
1721
1722  if ($type=='ul')
1723    $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1724
1725  return $out . "</$type>";
1726  }
1727
1728
1729
1730
1731/**
1732 * Create a hierarchical array of the mailbox list
1733 * @access private
1734 */
1735function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1736  {
1737  $pos = strpos($folder, $delm);
1738  if ($pos !== false)
1739    {
1740    $subFolders = substr($folder, $pos+1);
1741    $currentFolder = substr($folder, 0, $pos);
1742    }
1743  else
1744    {
1745    $subFolders = false;
1746    $currentFolder = $folder;
1747    }
1748
1749  $path .= $currentFolder;
1750
1751  if (!isset($arrFolders[$currentFolder]))
1752    {
1753    $arrFolders[$currentFolder] = array('id' => $path,
1754                                        'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1755                                        'folders' => array());
1756    }
1757
1758  if (!empty($subFolders))
1759    rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1760  }
1761 
1762
1763/**
1764 * Return html for a structured list &lt;ul&gt; for the mailbox tree
1765 * @access private
1766 */
1767function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1768  {
1769  global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1770
1771  $idx = 0;
1772  $out = '';
1773  foreach ($arrFolders as $key => $folder)
1774    {
1775    $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1776    $title = '';
1777
1778    if ($folder_class = rcmail_folder_classname($folder['id']))
1779      $foldername = rcube_label($folder_class);
1780    else
1781      {
1782      $foldername = $folder['name'];
1783
1784      // shorten the folder name to a given length
1785      if ($maxlength && $maxlength>1)
1786        {
1787        $fname = abbreviate_string($foldername, $maxlength);
1788        if ($fname != $foldername)
1789          $title = ' title="'.Q($foldername).'"';
1790        $foldername = $fname;
1791        }
1792      }
1793
1794    // add unread message count display
1795    if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox_name)))
1796      $foldername .= sprintf(' (%d)', $unread_count);
1797
1798    // make folder name safe for ids and class names
1799    $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1800    $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_class ? $folder_class : strtolower($folder['id']));
1801
1802    // set special class for Sent, Drafts, Trash and Junk
1803    if ($folder['id']==$CONFIG['sent_mbox'])
1804      $class_name = 'sent';
1805    else if ($folder['id']==$CONFIG['drafts_mbox'])
1806      $class_name = 'drafts';
1807    else if ($folder['id']==$CONFIG['trash_mbox'])
1808      $class_name = 'trash';
1809    else if ($folder['id']==$CONFIG['junk_mbox'])
1810      $class_name = 'junk';
1811
1812    $js_name = htmlspecialchars(JQ($folder['id']));
1813    $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1814                    ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1815                    ' onmouseover="return %s.focus_folder(\'%s\')"' .
1816                    ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1817                    ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1818                    $folder_id,
1819                    $class_name,
1820                    $zebra_class,
1821                    $unread_count ? ' unread' : '',
1822                    $folder['id']==$mbox_name ? ' selected' : '',
1823                    Q(rcmail_url('', array('_mbox' => $folder['id']))),
1824                    JS_OBJECT_NAME,
1825                    $js_name,
1826                    JS_OBJECT_NAME,
1827                    $js_name,
1828                    JS_OBJECT_NAME,
1829                    $js_name,
1830                    JS_OBJECT_NAME,
1831                    $js_name,
1832                    $title,
1833                    Q($foldername));
1834
1835    if (!empty($folder['folders']))
1836      $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1837
1838    $out .= "</li>\n";
1839    $idx++;
1840    }
1841
1842  return $out;
1843  }
1844
1845
1846/**
1847 * Return html for a flat list <select> for the mailbox tree
1848 * @access private
1849 */
1850function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1851  {
1852  global $IMAP, $OUTPUT;
1853
1854  $idx = 0;
1855  $out = '';
1856  foreach ($arrFolders as $key=>$folder)
1857    {
1858    if ($folder_class = rcmail_folder_classname($folder['id']))
1859      $foldername = rcube_label($folder_class);
1860    else
1861      {
1862      $foldername = $folder['name'];
1863     
1864      // shorten the folder name to a given length
1865      if ($maxlength && $maxlength>1)
1866        $foldername = abbreviate_string($foldername, $maxlength);
1867      }
1868
1869    $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1870                    htmlspecialchars($folder['id']),
1871                    str_repeat('&nbsp;', $nestLevel*4),
1872                    Q($foldername));
1873
1874    if (!empty($folder['folders']))
1875      $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $nestLevel+1);
1876
1877    $idx++;
1878    }
1879
1880  return $out;
1881  }
1882
1883
1884/**
1885 * Return internal name for the given folder if it matches the configured special folders
1886 * @access private
1887 */
1888function rcmail_folder_classname($folder_id)
1889{
1890  global $CONFIG;
1891
1892  $cname = null;
1893  $folder_lc = strtolower($folder_id);
1894 
1895  // for these mailboxes we have localized labels and css classes
1896  foreach (array('inbox', 'sent', 'drafts', 'trash', 'junk') as $smbx)
1897  {
1898    if ($folder_lc == $smbx || $folder_id == $CONFIG[$smbx.'_mbox'])
1899      $cname = $smbx;
1900  }
1901 
1902  return $cname;
1903}
1904
1905
1906/**
1907 * Try to localize the given IMAP folder name.
1908 * UTF-7 decode it in case no localized text was found
1909 *
1910 * @param string Folder name
1911 * @return string Localized folder name in UTF-8 encoding
1912 */
1913function rcmail_localize_foldername($name)
1914{
1915  if ($folder_class = rcmail_folder_classname($name))
1916    return rcube_label($folder_class);
1917  else
1918    return rcube_charset_convert($name, 'UTF-7');
1919}
1920
1921
1922?>
Note: See TracBrowser for help on using the repository browser.