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

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

Respect config when localize folder names

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