source: github/program/include/main.inc @ 6f987669

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 6f987669 was 6f987669, checked in by alecpl <alec@…>, 5 years ago

#1484624: do ob_start/ob_end_clean when reading config files

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