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

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

Fix charset converting issues with iconv and mbstring

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