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

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

More input sanitizing

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