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

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

Add support for Korean charset (KS_C_5601)

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