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

Last change on this file since 938 was 938, checked in by thomasb, 6 years ago

New class rcube_user + send message disposition notification

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.3 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  if (is_array($_SESSION['user_prefs']))
96    $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
97
98
99  // reset some session parameters when changing task
100  if ($_SESSION['task'] != $task)
101    unset($_SESSION['page']);
102
103  // set current task to session
104  $_SESSION['task'] = $task;
105
106  // create IMAP object
107  if ($task=='mail')
108    rcmail_imap_init();
109
110
111  // set localization
112  if ($CONFIG['locale_string'])
113    setlocale(LC_ALL, $CONFIG['locale_string']);
114  else if ($sess_user_lang)
115    setlocale(LC_ALL, $sess_user_lang);
116
117
118  register_shutdown_function('rcmail_shutdown');
119  }
120
121
122/**
123 * Load roundcube configuration array
124 *
125 * @return array Named configuration parameters
126 */
127function rcmail_load_config()
128  {
129  global $INSTALL_PATH;
130
131  // load config file
132  include_once('config/main.inc.php');
133  $conf = is_array($rcmail_config) ? $rcmail_config : array();
134
135  // load host-specific configuration
136  rcmail_load_host_config($conf);
137
138  $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
139
140  // load db conf
141  include_once('config/db.inc.php');
142  $conf = array_merge($conf, $rcmail_config);
143
144  if (empty($conf['log_dir']))
145    $conf['log_dir'] = $INSTALL_PATH.'logs';
146  else
147    $conf['log_dir'] = unslashify($conf['log_dir']);
148
149  // set PHP error logging according to config
150  if ($conf['debug_level'] & 1)
151    {
152    ini_set('log_errors', 1);
153    ini_set('error_log', $conf['log_dir'].'/errors');
154    }
155  if ($conf['debug_level'] & 4)
156    ini_set('display_errors', 1);
157  else
158    ini_set('display_errors', 0);
159
160  return $conf;
161  }
162
163
164/**
165 * Load a host-specific config file if configured
166 * This will merge the host specific configuration with the given one
167 *
168 * @param array Global configuration parameters
169 */
170function rcmail_load_host_config(&$config)
171  {
172  $fname = NULL;
173 
174  if (is_array($config['include_host_config']))
175    $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
176  else if (!empty($config['include_host_config']))
177    $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
178
179   if ($fname && is_file('config/'.$fname))
180     {
181     include('config/'.$fname);
182     $config = array_merge($config, $rcmail_config);
183     }
184  }
185
186
187/**
188 * Create unique authorization hash
189 *
190 * @param string Session ID
191 * @param int Timestamp
192 * @return string The generated auth hash
193 */
194function rcmail_auth_hash($sess_id, $ts)
195  {
196  global $CONFIG;
197 
198  $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
199                         $sess_id,
200                         $ts,
201                         $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
202                         $_SERVER['HTTP_USER_AGENT']);
203 
204  if (function_exists('sha1'))
205    return sha1($auth_string);
206  else
207    return md5($auth_string);
208  }
209
210
211/**
212 * Check the auth hash sent by the client against the local session credentials
213 *
214 * @return boolean True if valid, False if not
215 */
216function rcmail_authenticate_session()
217  {
218  global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
219 
220  // advanced session authentication
221  if ($CONFIG['double_auth'])
222  {
223    $now = time();
224    $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
225              $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
226
227    // renew auth cookie every 5 minutes (only for GET requests)
228    if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
229    {
230      $_SESSION['last_auth'] = $_SESSION['auth_time'];
231      $_SESSION['auth_time'] = $now;
232      setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
233    }
234  }
235  else
236    $valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
237 
238  // check session filetime
239  if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED) && $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    $_SESSION['user_prefs'] = $USER->get_prefs();
612    array_merge($CONFIG, $_SESSION['user_prefs']);
613
614    // set user specific language
615    if (!empty($USER->data['language']))
616      $sess_user_lang = $_SESSION['user_lang'] = $USER->data['language'];
617     
618    // update user's record
619    $USER->touch();
620    }
621  // create new system user
622  else if ($CONFIG['auto_create_user'])
623    {
624    if ($created = rcube_user::create($user, $host))
625    {
626      $USER = $created;
627     
628      // get existing mailboxes
629      $a_mailboxes = $IMAP->list_mailboxes();
630    }
631    }
632  else
633    {
634    raise_error(array(
635      'code' => 600,
636      'type' => 'php',
637      'file' => "config/main.inc.php",
638      'message' => "Acces denied for new user $user. 'auto_create_user' is disabled"
639      ), true, false);
640    }
641
642  if ($USER->ID)
643    {
644    $_SESSION['user_id']   = $USER->ID;
645    $_SESSION['username']  = $USER->data['username'];
646    $_SESSION['imap_host'] = $host;
647    $_SESSION['imap_port'] = $imap_port;
648    $_SESSION['imap_ssl']  = $imap_ssl;
649    $_SESSION['user_lang'] = $sess_user_lang;
650    $_SESSION['password']  = encrypt_passwd($pass);
651    $_SESSION['login_time'] = mktime();
652
653    // force reloading complete list of subscribed mailboxes
654    rcmail_set_imap_prop();
655    $IMAP->clear_cache('mailboxes');
656
657    if ($CONFIG['create_default_folders'])
658        $IMAP->create_default_folders();
659
660    return TRUE;
661    }
662
663  return FALSE;
664  }
665
666
667/**
668 * Load virtuser table in array
669 *
670 * @return array Virtuser table entries
671 */
672function rcmail_getvirtualfile()
673  {
674  global $CONFIG;
675  if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
676    return FALSE;
677 
678  // read file
679  $a_lines = file($CONFIG['virtuser_file']);
680  return $a_lines;
681  }
682
683
684/**
685 * Find matches of the given pattern in virtuser table
686 *
687 * @param string Regular expression to search for
688 * @return array Matching entries
689 */
690function rcmail_findinvirtual($pattern)
691  {
692  $result = array();
693  $virtual = rcmail_getvirtualfile();
694  if ($virtual==FALSE)
695    return $result;
696
697  // check each line for matches
698  foreach ($virtual as $line)
699    {
700    $line = trim($line);
701    if (empty($line) || $line{0}=='#')
702      continue;
703     
704    if (eregi($pattern, $line))
705      $result[] = $line;
706    }
707
708  return $result;
709  }
710
711
712/**
713 * Overwrite action variable
714 *
715 * @param string New action value
716 */
717function rcmail_overwrite_action($action)
718  {
719  global $OUTPUT;
720  $GLOBALS['_action'] = $action;
721  $OUTPUT->set_env('action', $action);
722  }
723
724
725/**
726 * Compose an URL for a specific action
727 *
728 * @param string  Request action
729 * @param array   More URL parameters
730 * @param string  Request task (omit if the same)
731 * @return The application URL
732 */
733function rcmail_url($action, $p=array(), $task=null)
734{
735  global $MAIN_TASKS, $COMM_PATH;
736  $qstring = '';
737  $base = $COMM_PATH;
738 
739  if ($task && in_array($task, $MAIN_TASKS))
740    $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
741 
742  if (is_array($p))
743    foreach ($p as $key => $val)
744      $qstring .= '&'.urlencode($key).'='.urlencode($val);
745 
746  return $base . ($action ? '&_action='.$action : '') . $qstring;
747}
748
749
750// @deprecated
751function show_message($message, $type='notice', $vars=NULL)
752  {
753  global $OUTPUT;
754  $OUTPUT->show_message($message, $type, $vars);
755  }
756
757
758/**
759 * Encrypt IMAP password using DES encryption
760 *
761 * @param string Password to encrypt
762 * @return string Encryprted string
763 */
764function encrypt_passwd($pass)
765  {
766  $cypher = des(get_des_key(), $pass, 1, 0, NULL);
767  return base64_encode($cypher);
768  }
769
770
771/**
772 * Decrypt IMAP password using DES encryption
773 *
774 * @param string Encrypted password
775 * @return string Plain password
776 */
777function decrypt_passwd($cypher)
778  {
779  $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
780  return preg_replace('/\x00/', '', $pass);
781  }
782
783
784/**
785 * Return a 24 byte key for the DES encryption
786 *
787 * @return string DES encryption key
788 */
789function get_des_key()
790  {
791  $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
792  $len = strlen($key);
793 
794  // make sure the key is exactly 24 chars long
795  if ($len<24)
796    $key .= str_repeat('_', 24-$len);
797  else if ($len>24)
798    substr($key, 0, 24);
799 
800  return $key;
801  }
802
803
804/**
805 * Read directory program/localization and return a list of available languages
806 *
807 * @return array List of available localizations
808 */
809function rcube_list_languages()
810  {
811  global $CONFIG, $INSTALL_PATH;
812  static $sa_languages = array();
813
814  if (!sizeof($sa_languages))
815    {
816    @include($INSTALL_PATH.'program/localization/index.inc');
817
818    if ($dh = @opendir($INSTALL_PATH.'program/localization'))
819      {
820      while (($name = readdir($dh)) !== false)
821        {
822        if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
823          continue;
824
825        if ($label = $rcube_languages[$name])
826          $sa_languages[$name] = $label ? $label : $name;
827        }
828      closedir($dh);
829      }
830    }
831  return $sa_languages;
832  }
833
834
835/**
836 * Add a localized label to the client environment
837 */
838function rcube_add_label()
839  {
840  global $OUTPUT;
841 
842  $arg_list = func_get_args();
843  foreach ($arg_list as $i => $name)
844    $OUTPUT->command('add_label', $name, rcube_label($name));
845  }
846
847
848/**
849 * Garbage collector function for temp files.
850 * Remove temp files older than two days
851 */
852function rcmail_temp_gc()
853  {
854  $tmp = unslashify($CONFIG['temp_dir']);
855  $expire = mktime() - 172800;  // expire in 48 hours
856
857  if ($dir = opendir($tmp))
858    {
859    while (($fname = readdir($dir)) !== false)
860      {
861      if ($fname{0} == '.')
862        continue;
863
864      if (filemtime($tmp.'/'.$fname) < $expire)
865        @unlink($tmp.'/'.$fname);
866      }
867
868    closedir($dir);
869    }
870  }
871
872
873/**
874 * Garbage collector for cache entries.
875 * Remove all expired message cache records
876 */
877function rcmail_message_cache_gc()
878  {
879  global $DB, $CONFIG;
880 
881  // no cache lifetime configured
882  if (empty($CONFIG['message_cache_lifetime']))
883    return;
884 
885  // get target timestamp
886  $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
887 
888  $DB->query("DELETE FROM ".get_table_name('messages')."
889             WHERE  created < ".$DB->fromunixtime($ts));
890  }
891
892
893/**
894 * Convert a string from one charset to another.
895 * Uses mbstring and iconv functions if possible
896 *
897 * @param  string Input string
898 * @param  string Suspected charset of the input string
899 * @param  string Target charset to convert to; defaults to RCMAIL_CHARSET
900 * @return Converted string
901 */
902function rcube_charset_convert($str, $from, $to=NULL)
903  {
904  global $MBSTRING;
905
906  $from = strtoupper($from);
907  $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
908
909  if ($from==$to || $str=='' || empty($from))
910    return $str;
911
912  // convert charset using iconv module 
913  if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
914    {
915    $iconv_map = array('KS_C_5601-1987' => 'EUC-KR');
916    return iconv(($iconv_map[$from] ? $iconv_map[$from] : $from), ($iconv_map[$to] ? $iconv_map[$to] : $to) . "//IGNORE", $str);
917    }
918
919  // convert charset using mbstring module 
920  if ($MBSTRING)
921    {
922    $mb_map = array('UTF-7' => 'UTF7-IMAP', 'KS_C_5601-1987' => 'EUC-KR');
923   
924    // return if convert succeeded
925    if (($out = mb_convert_encoding($str, ($mb_map[$to] ? $mb_map[$to] : $to), ($mb_map[$from] ? $mb_map[$from] : $from))) != '')
926      return $out;
927    }
928
929  $conv = new utf8();
930
931  // convert string to UTF-8
932  if ($from=='UTF-7')
933    $str = utf7_to_utf8($str);
934  else if (($from=='ISO-8859-1') && function_exists('utf8_encode'))
935    $str = utf8_encode($str);
936  else if ($from!='UTF-8')
937    {
938    $conv->loadCharset($from);
939    $str = $conv->strToUtf8($str);
940    }
941
942  // encode string for output
943  if ($to=='UTF-7')
944    return utf8_to_utf7($str);
945  else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
946    return utf8_decode($str);
947  else if ($to!='UTF-8')
948    {
949    $conv->loadCharset($to);
950    return $conv->utf8ToStr($str);
951    }
952
953  // return UTF-8 string
954  return $str;
955  }
956
957
958/**
959 * Replacing specials characters to a specific encoding type
960 *
961 * @param  string  Input string
962 * @param  string  Encoding type: text|html|xml|js|url
963 * @param  string  Replace mode for tags: show|replace|remove
964 * @param  boolean Convert newlines
965 * @return The quoted string
966 */
967function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
968  {
969  global $OUTPUT_TYPE, $OUTPUT;
970  static $html_encode_arr, $js_rep_table, $xml_rep_table;
971
972  if (!$enctype)
973    $enctype = $GLOBALS['OUTPUT_TYPE'];
974
975  // encode for plaintext
976  if ($enctype=='text')
977    return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
978
979  // encode for HTML output
980  if ($enctype=='html')
981    {
982    if (!$html_encode_arr)
983      {
984      $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);       
985      unset($html_encode_arr['?']);
986      }
987
988    $ltpos = strpos($str, '<');
989    $encode_arr = $html_encode_arr;
990
991    // don't replace quotes and html tags
992    if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
993      {
994      unset($encode_arr['"']);
995      unset($encode_arr['<']);
996      unset($encode_arr['>']);
997      unset($encode_arr['&']);
998      }
999    else if ($mode=='remove')
1000      $str = strip_tags($str);
1001   
1002    // avoid douple quotation of &
1003    $out = preg_replace('/&amp;([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1004     
1005    return $newlines ? nl2br($out) : $out;
1006    }
1007
1008  if ($enctype=='url')
1009    return rawurlencode($str);
1010
1011  // if the replace tables for XML and JS are not yet defined
1012  if (!$js_rep_table)
1013    {
1014    $js_rep_table = $xml_rep_table = array();
1015    $xml_rep_table['&'] = '&amp;';
1016
1017    for ($c=160; $c<256; $c++)  // can be increased to support more charsets
1018      {
1019      $xml_rep_table[Chr($c)] = "&#$c;";
1020     
1021      if ($OUTPUT->get_charset()=='ISO-8859-1')
1022        $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1023      }
1024
1025    $xml_rep_table['"'] = '&quot;';
1026    }
1027
1028  // encode for XML
1029  if ($enctype=='xml')
1030    return strtr($str, $xml_rep_table);
1031
1032  // encode for javascript use
1033  if ($enctype=='js')
1034    {
1035    if ($OUTPUT->get_charset()!='UTF-8')
1036      $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1037     
1038    return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1039    }
1040
1041  // no encoding given -> return original string
1042  return $str;
1043  }
1044 
1045/**
1046 * Quote a given string.
1047 * Shortcut function for rep_specialchars_output
1048 *
1049 * @return string HTML-quoted string
1050 * @see rep_specialchars_output()
1051 */
1052function Q($str, $mode='strict', $newlines=TRUE)
1053  {
1054  return rep_specialchars_output($str, 'html', $mode, $newlines);
1055  }
1056
1057/**
1058 * Quote a given string for javascript output.
1059 * Shortcut function for rep_specialchars_output
1060 *
1061 * @return string JS-quoted string
1062 * @see rep_specialchars_output()
1063 */
1064function JQ($str)
1065  {
1066  return rep_specialchars_output($str, 'js');
1067  }
1068
1069
1070/**
1071 * Read input value and convert it for internal use
1072 * Performs stripslashes() and charset conversion if necessary
1073 *
1074 * @param  string   Field name to read
1075 * @param  int      Source to get value from (GPC)
1076 * @param  boolean  Allow HTML tags in field value
1077 * @param  string   Charset to convert into
1078 * @return string   Field value or NULL if not available
1079 */
1080function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1081  {
1082  global $OUTPUT;
1083  $value = NULL;
1084 
1085  if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1086    $value = $_GET[$fname];
1087  else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1088    $value = $_POST[$fname];
1089  else if ($source==RCUBE_INPUT_GPC)
1090    {
1091    if (isset($_POST[$fname]))
1092      $value = $_POST[$fname];
1093    else if (isset($_GET[$fname]))
1094      $value = $_GET[$fname];
1095    else if (isset($_COOKIE[$fname]))
1096      $value = $_COOKIE[$fname];
1097    }
1098 
1099  // strip slashes if magic_quotes enabled
1100  if ((bool)get_magic_quotes_gpc())
1101    $value = stripslashes($value);
1102
1103  // remove HTML tags if not allowed   
1104  if (!$allow_html)
1105    $value = strip_tags($value);
1106 
1107  // convert to internal charset
1108  if (is_object($OUTPUT))
1109    return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1110  else
1111    return $value;
1112  }
1113
1114/**
1115 * Remove all non-ascii and non-word chars
1116 * except . and -
1117 */
1118function asciiwords($str)
1119{
1120  return preg_replace('/[^a-z0-9.-_]/i', '', $str);
1121}
1122
1123/**
1124 * Remove single and double quotes from given string
1125 *
1126 * @param string Input value
1127 * @return string Dequoted string
1128 */
1129function strip_quotes($str)
1130{
1131  return preg_replace('/[\'"]/', '', $str);
1132}
1133
1134
1135/**
1136 * Remove new lines characters from given string
1137 *
1138 * @param string Input value
1139 * @return string Stripped string
1140 */
1141function strip_newlines($str)
1142{
1143  return preg_replace('/[\r\n]/', '', $str);
1144}
1145
1146
1147/**
1148 * Check if a specific template exists
1149 *
1150 * @param string Template name
1151 * @return boolean True if template exists
1152 */
1153function template_exists($name)
1154  {
1155  global $CONFIG;
1156  $skin_path = $CONFIG['skin_path'];
1157
1158  // check template file
1159  return is_file("$skin_path/templates/$name.html");
1160  }
1161
1162
1163/**
1164 * Wrapper for rcmail_template::parse()
1165 * @deprecated
1166 */
1167function parse_template($name='main', $exit=true)
1168  {
1169  $GLOBALS['OUTPUT']->parse($name, $exit);
1170  }
1171
1172
1173/**
1174 * Create a HTML table based on the given data
1175 *
1176 * @param  array  Named table attributes
1177 * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
1178 * @param  array  List of cols to show
1179 * @param  string Name of the identifier col
1180 * @return string HTML table code
1181 */
1182function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1183  {
1184  global $DB;
1185 
1186  // allow the following attributes to be added to the <table> tag
1187  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1188 
1189  $table = '<table' . $attrib_str . ">\n";
1190   
1191  // add table title
1192  $table .= "<thead><tr>\n";
1193
1194  foreach ($a_show_cols as $col)
1195    $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1196
1197  $table .= "</tr></thead>\n<tbody>\n";
1198 
1199  $c = 0;
1200  if (!is_array($table_data))
1201    {
1202    while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1203      {
1204      $zebra_class = $c%2 ? 'even' : 'odd';
1205
1206      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1207
1208      // format each col
1209      foreach ($a_show_cols as $col)
1210        {
1211        $cont = Q($sql_arr[$col]);
1212        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1213        }
1214
1215      $table .= "</tr>\n";
1216      $c++;
1217      }
1218    }
1219  else
1220    {
1221    foreach ($table_data as $row_data)
1222      {
1223      $zebra_class = $c%2 ? 'even' : 'odd';
1224
1225      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1226
1227      // format each col
1228      foreach ($a_show_cols as $col)
1229        {
1230        $cont = Q($row_data[$col]);
1231        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1232        }
1233
1234      $table .= "</tr>\n";
1235      $c++;
1236      }
1237    }
1238
1239  // complete message table
1240  $table .= "</tbody></table>\n";
1241 
1242  return $table;
1243  }
1244
1245
1246/**
1247 * Create an edit field for inclusion on a form
1248 *
1249 * @param string col field name
1250 * @param string value field value
1251 * @param array attrib HTML element attributes for field
1252 * @param string type HTML element type (default 'text')
1253 * @return string HTML field definition
1254 */
1255function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1256  {
1257  $fname = '_'.$col;
1258  $attrib['name'] = $fname;
1259 
1260  if ($type=='checkbox')
1261    {
1262    $attrib['value'] = '1';
1263    $input = new checkbox($attrib);
1264    }
1265  else if ($type=='textarea')
1266    {
1267    $attrib['cols'] = $attrib['size'];
1268    $input = new textarea($attrib);
1269    }
1270  else
1271    $input = new textfield($attrib);
1272
1273  // use value from post
1274  if (!empty($_POST[$fname]))
1275    $value = get_input_value($fname, RCUBE_INPUT_POST);
1276
1277  $out = $input->show($value);
1278         
1279  return $out;
1280  }
1281
1282
1283/**
1284 * Return the mail domain configured for the given host
1285 *
1286 * @param string IMAP host
1287 * @return string Resolved SMTP host
1288 */
1289function rcmail_mail_domain($host)
1290  {
1291  global $CONFIG;
1292
1293  $domain = $host;
1294  if (is_array($CONFIG['mail_domain']))
1295    {
1296    if (isset($CONFIG['mail_domain'][$host]))
1297      $domain = $CONFIG['mail_domain'][$host];
1298    }
1299  else if (!empty($CONFIG['mail_domain']))
1300    $domain = $CONFIG['mail_domain'];
1301
1302  return $domain;
1303  }
1304
1305
1306/**
1307 * Replace all css definitions with #container [def]
1308 *
1309 * @param string CSS source code
1310 * @param string Container ID to use as prefix
1311 * @return string Modified CSS source
1312 */
1313function rcmail_mod_css_styles($source, $container_id, $base_url = '')
1314  {
1315  $a_css_values = array();
1316  $last_pos = 0;
1317
1318  // cut out all contents between { and }
1319  while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1320  {
1321    $key = sizeof($a_css_values);
1322    $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1323    $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1324    $last_pos = $pos+2;
1325  }
1326
1327  // remove html commends and add #container to each tag selector.
1328  // also replace body definition because we also stripped off the <body> tag
1329  $styles = preg_replace(
1330    array(
1331      '/(^\s*<!--)|(-->\s*$)/',
1332      '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1333      '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
1334      '/<<str_replacement\[([0-9]+)\]>>/e',
1335      "/$container_id\s+body/i"
1336    ),
1337    array(
1338      '',
1339      "\\1#$container_id \\2",
1340      "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
1341      "\$a_css_values[\\1]",
1342      "$container_id div.rcmBody"
1343    ),
1344    $source);
1345
1346  return $styles;
1347  }
1348
1349/**
1350 * Try to autodetect operating system and find the correct line endings
1351 *
1352 * @return string The appropriate mail header delimiter
1353 */
1354function rcmail_header_delm()
1355{
1356  global $CONFIG;
1357 
1358  // use the configured delimiter for headers
1359  if (!empty($CONFIG['mail_header_delimiter']))
1360    return $CONFIG['mail_header_delimiter'];
1361  else if (strtolower(substr(PHP_OS, 0, 3)=='win'))
1362    return "\r\n";
1363  else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
1364    return "\r\n";
1365  else   
1366    return "\n";
1367}
1368
1369
1370/**
1371 * Compose a valid attribute string for HTML tags
1372 *
1373 * @param array Named tag attributes
1374 * @param array List of allowed attributes
1375 * @return string HTML formatted attribute string
1376 */
1377function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1378  {
1379  // allow the following attributes to be added to the <iframe> tag
1380  $attrib_str = '';
1381  foreach ($allowed_attribs as $a)
1382    if (isset($attrib[$a]))
1383      $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
1384
1385  return $attrib_str;
1386  }
1387
1388
1389/**
1390 * Convert a HTML attribute string attributes to an associative array (name => value)
1391 *
1392 * @param string Input string
1393 * @return array Key-value pairs of parsed attributes
1394 */
1395function parse_attrib_string($str)
1396  {
1397  $attrib = array();
1398  preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1399
1400  // convert attributes to an associative array (name => value)
1401  if ($regs)
1402    foreach ($regs as $attr)
1403      $attrib[strtolower($attr[1])] = $attr[3];
1404
1405  return $attrib;
1406  }
1407
1408
1409/**
1410 * Convert the given date to a human readable form
1411 * This uses the date formatting properties from config
1412 *
1413 * @param mixed Date representation (string or timestamp)
1414 * @param string Date format to use
1415 * @return string Formatted date string
1416 */
1417function format_date($date, $format=NULL)
1418  {
1419  global $CONFIG, $sess_user_lang;
1420 
1421  $ts = NULL;
1422 
1423  if (is_numeric($date))
1424    $ts = $date;
1425  else if (!empty($date))
1426    $ts = @strtotime($date);
1427   
1428  if (empty($ts))
1429    return '';
1430   
1431  // get user's timezone
1432  $tz = $CONFIG['timezone'];
1433  if ($CONFIG['dst_active'])
1434    $tz++;
1435
1436  // convert time to user's timezone
1437  $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1438 
1439  // get current timestamp in user's timezone
1440  $now = time();  // local time
1441  $now -= (int)date('Z'); // make GMT time
1442  $now += ($tz * 3600); // user's time
1443  $now_date = getdate($now);
1444
1445  $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1446  $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1447
1448  // define date format depending on current time 
1449  if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1450    return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1451  else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1452    $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1453  else if (!$format)
1454    $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1455
1456
1457  // parse format string manually in order to provide localized weekday and month names
1458  // an alternative would be to convert the date() format string to fit with strftime()
1459  $out = '';
1460  for($i=0; $i<strlen($format); $i++)
1461    {
1462    if ($format{$i}=='\\')  // skip escape chars
1463      continue;
1464   
1465    // write char "as-is"
1466    if ($format{$i}==' ' || $format{$i-1}=='\\')
1467      $out .= $format{$i};
1468    // weekday (short)
1469    else if ($format{$i}=='D')
1470      $out .= rcube_label(strtolower(date('D', $timestamp)));
1471    // weekday long
1472    else if ($format{$i}=='l')
1473      $out .= rcube_label(strtolower(date('l', $timestamp)));
1474    // month name (short)
1475    else if ($format{$i}=='M')
1476      $out .= rcube_label(strtolower(date('M', $timestamp)));
1477    // month name (long)
1478    else if ($format{$i}=='F')
1479      $out .= rcube_label(strtolower(date('F', $timestamp)));
1480    else
1481      $out .= date($format{$i}, $timestamp);
1482    }
1483 
1484  return $out;
1485  }
1486
1487
1488/**
1489 * Compose a valid representaion of name and e-mail address
1490 *
1491 * @param string E-mail address
1492 * @param string Person name
1493 * @return string Formatted string
1494 */
1495function format_email_recipient($email, $name='')
1496  {
1497  if ($name && $name != $email)
1498    return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
1499  else
1500    return $email;
1501  }
1502
1503
1504
1505/****** debugging functions ********/
1506
1507
1508/**
1509 * Print or write debug messages
1510 *
1511 * @param mixed Debug message or data
1512 */
1513function console($msg)
1514  {
1515  if (!is_string($msg))
1516    $msg = var_export($msg, true);
1517
1518  if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1519    write_log('console', $msg);
1520  else if ($GLOBALS['REMOTE_REQUEST'])
1521    print "/*\n $msg \n*/\n";
1522  else
1523    {
1524    print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1525    print $msg;
1526    print "</pre></div>\n";
1527    }
1528  }
1529
1530
1531/**
1532 * Append a line to a logfile in the logs directory.
1533 * Date will be added automatically to the line.
1534 *
1535 * @param $name Name of logfile
1536 * @param $line Line to append
1537 */
1538function write_log($name, $line)
1539  {
1540  global $CONFIG, $INSTALL_PATH;
1541
1542  if (!is_string($line))
1543    $line = var_export($line, true);
1544 
1545  $log_entry = sprintf("[%s]: %s\n",
1546                 date("d-M-Y H:i:s O", mktime()),
1547                 $line);
1548                 
1549  if (empty($CONFIG['log_dir']))
1550    $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1551     
1552  // try to open specific log file for writing
1553  if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))   
1554    {
1555    fwrite($fp, $log_entry);
1556    fclose($fp);
1557    }
1558  }
1559
1560
1561/**
1562 * @access private
1563 */
1564function rcube_timer()
1565  {
1566  list($usec, $sec) = explode(" ", microtime());
1567  return ((float)$usec + (float)$sec);
1568  }
1569 
1570
1571/**
1572 * @access private
1573 */
1574function rcube_print_time($timer, $label='Timer')
1575  {
1576  static $print_count = 0;
1577 
1578  $print_count++;
1579  $now = rcube_timer();
1580  $diff = $now-$timer;
1581 
1582  if (empty($label))
1583    $label = 'Timer '.$print_count;
1584 
1585  console(sprintf("%s: %0.4f sec", $label, $diff));
1586  }
1587
1588
1589/**
1590 * Return the mailboxlist in HTML
1591 *
1592 * @param array Named parameters
1593 * @return string HTML code for the gui object
1594 */
1595function rcmail_mailbox_list($attrib)
1596  {
1597  global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1598  static $s_added_script = FALSE;
1599  static $a_mailboxes;
1600
1601  // add some labels to client
1602  rcube_add_label('purgefolderconfirm');
1603  rcube_add_label('deletemessagesconfirm');
1604 
1605// $mboxlist_start = rcube_timer();
1606 
1607  $type = $attrib['type'] ? $attrib['type'] : 'ul';
1608  $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1609                                  array('style', 'class', 'id');
1610                                 
1611  if ($type=='ul' && !$attrib['id'])
1612    $attrib['id'] = 'rcmboxlist';
1613
1614  // allow the following attributes to be added to the <ul> tag
1615  $attrib_str = create_attrib_string($attrib, $add_attrib);
1616 
1617  $out = '<' . $type . $attrib_str . ">\n";
1618 
1619  // add no-selection option
1620  if ($type=='select' && $attrib['noselection'])
1621    $out .= sprintf('<option value="0">%s</option>'."\n",
1622                    rcube_label($attrib['noselection']));
1623 
1624  // get mailbox list
1625  $mbox_name = $IMAP->get_mailbox_name();
1626 
1627  // for these mailboxes we have localized labels
1628  $special_mailboxes = array('inbox', 'sent', 'drafts', 'trash', 'junk');
1629
1630
1631  // build the folders tree
1632  if (empty($a_mailboxes))
1633    {
1634    // get mailbox list
1635    $a_folders = $IMAP->list_mailboxes();
1636    $delimiter = $IMAP->get_hierarchy_delimiter();
1637    $a_mailboxes = array();
1638
1639// rcube_print_time($mboxlist_start, 'list_mailboxes()');
1640
1641    foreach ($a_folders as $folder)
1642      rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1643    }
1644
1645// var_dump($a_mailboxes);
1646
1647  if ($type=='select')
1648    $out .= rcmail_render_folder_tree_select($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
1649   else
1650    $out .= rcmail_render_folder_tree_html($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
1651
1652// rcube_print_time($mboxlist_start, 'render_folder_tree()');
1653
1654
1655  if ($type=='ul')
1656    $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1657
1658  return $out . "</$type>";
1659  }
1660
1661
1662
1663
1664/**
1665 * Create a hierarchical array of the mailbox list
1666 * @access private
1667 */
1668function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1669  {
1670  $pos = strpos($folder, $delm);
1671  if ($pos !== false)
1672    {
1673    $subFolders = substr($folder, $pos+1);
1674    $currentFolder = substr($folder, 0, $pos);
1675    }
1676  else
1677    {
1678    $subFolders = false;
1679    $currentFolder = $folder;
1680    }
1681
1682  $path .= $currentFolder;
1683
1684  if (!isset($arrFolders[$currentFolder]))
1685    {
1686    $arrFolders[$currentFolder] = array('id' => $path,
1687                                        'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1688                                        'folders' => array());
1689    }
1690
1691  if (!empty($subFolders))
1692    rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1693  }
1694 
1695
1696/**
1697 * Return html for a structured list &lt;ul&gt; for the mailbox tree
1698 * @access private
1699 */
1700function rcmail_render_folder_tree_html(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
1701  {
1702  global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1703
1704  $idx = 0;
1705  $out = '';
1706  foreach ($arrFolders as $key => $folder)
1707    {
1708    $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1709    $title = '';
1710
1711    $folder_lc = strtolower($folder['id']);
1712    if (in_array($folder_lc, $special))
1713      $foldername = rcube_label($folder_lc);
1714    else
1715      {
1716      $foldername = $folder['name'];
1717
1718      // shorten the folder name to a given length
1719      if ($maxlength && $maxlength>1)
1720        {
1721        $fname = abbrevate_string($foldername, $maxlength);
1722        if ($fname != $foldername)
1723          $title = ' title="'.Q($foldername).'"';
1724        $foldername = $fname;
1725        }
1726      }
1727
1728    // add unread message count display
1729    if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox_name)))
1730      $foldername .= sprintf(' (%d)', $unread_count);
1731
1732    // make folder name safe for ids and class names
1733    $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1734    $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
1735
1736    // set special class for Sent, Drafts, Trash and Junk
1737    if ($folder['id']==$CONFIG['sent_mbox'])
1738      $class_name = 'sent';
1739    else if ($folder['id']==$CONFIG['drafts_mbox'])
1740      $class_name = 'drafts';
1741    else if ($folder['id']==$CONFIG['trash_mbox'])
1742      $class_name = 'trash';
1743    else if ($folder['id']==$CONFIG['junk_mbox'])
1744      $class_name = 'junk';
1745
1746    $js_name = htmlspecialchars(JQ($folder['id']));
1747    $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1748                    ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1749                    ' onmouseover="return %s.focus_folder(\'%s\')"' .
1750                    ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1751                    ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1752                    $folder_id,
1753                    $class_name,
1754                    $zebra_class,
1755                    $unread_count ? ' unread' : '',
1756                    $folder['id']==$mbox_name ? ' selected' : '',
1757                    Q(rcmail_url('', array('_mbox' => $folder['id']))),
1758                    JS_OBJECT_NAME,
1759                    $js_name,
1760                    JS_OBJECT_NAME,
1761                    $js_name,
1762                    JS_OBJECT_NAME,
1763                    $js_name,
1764                    JS_OBJECT_NAME,
1765                    $js_name,
1766                    $title,
1767                    Q($foldername));
1768
1769    if (!empty($folder['folders']))
1770      $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1771
1772    $out .= "</li>\n";
1773    $idx++;
1774    }
1775
1776  return $out;
1777  }
1778
1779
1780/**
1781 * Return html for a flat list <select> for the mailbox tree
1782 * @access private
1783 */
1784function rcmail_render_folder_tree_select(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
1785  {
1786  global $IMAP, $OUTPUT;
1787
1788  $idx = 0;
1789  $out = '';
1790  foreach ($arrFolders as $key=>$folder)
1791    {
1792    $folder_lc = strtolower($folder['id']);
1793    if (in_array($folder_lc, $special))
1794      $foldername = rcube_label($folder_lc);
1795    else
1796      {
1797      $foldername = $folder['name'];
1798     
1799      // shorten the folder name to a given length
1800      if ($maxlength && $maxlength>1)
1801        $foldername = abbrevate_string($foldername, $maxlength);
1802      }
1803
1804    $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1805                    htmlspecialchars($folder['id']),
1806                    str_repeat('&nbsp;', $nestLevel*4),
1807                    Q($foldername));
1808
1809    if (!empty($folder['folders']))
1810      $out .= rcmail_render_folder_tree_select($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1);
1811
1812    $idx++;
1813    }
1814
1815  return $out;
1816  }
1817
1818?>
Note: See TracBrowser for help on using the repository browser.