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

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

Make some code work without non-GPL libs

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