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

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

Allow to save particular user prefs

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