source: github/program/include/main.inc @ 532844b

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 532844b was 532844b, checked in by thomascube <thomas@…>, 6 years ago

Resolve username from virtuser file before looking up in database

  • Property mode set to 100644
File size: 47.8 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/main.inc                                              |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005-2007, RoundCube Dev, - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Provide basic functions for the webmail package                     |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22/**
23 * RoundCube Webmail common functions
24 *
25 * @package Core
26 * @author Thomas Bruederli <roundcube@gmail.com>
27 */
28
29require_once('lib/des.inc');
30require_once('lib/utf7.inc');
31require_once('lib/utf8.class.php');
32require_once('include/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  $DB->query("UPDATE ".get_table_name('users')."
847              SET    preferences=?,
848                     language=?
849              WHERE  user_id=?",
850              serialize($a_user_prefs),
851              $sess_user_lang,
852              $_SESSION['user_id']);
853
854  if ($DB->affected_rows())
855    {
856    $_SESSION['user_prefs'] = $a_user_prefs; 
857    $CONFIG = array_merge($CONFIG, $a_user_prefs);
858    return TRUE;
859    }
860   
861  return FALSE;
862  }
863
864
865/**
866 * Overwrite action variable
867 *
868 * @param string New action value
869 */
870function rcmail_overwrite_action($action)
871  {
872  global $OUTPUT;
873  $GLOBALS['_action'] = $action;
874  $OUTPUT->set_env('action', $action);
875  }
876
877
878/**
879 * Compose an URL for a specific action
880 *
881 * @param string  Request action
882 * @param array   More URL parameters
883 * @param string  Request task (omit if the same)
884 * @return The application URL
885 */
886function rcmail_url($action, $p=array(), $task=null)
887{
888  global $MAIN_TASKS, $COMM_PATH;
889  $qstring = '';
890  $base = $COMM_PATH;
891 
892  if ($task && in_array($task, $MAIN_TASKS))
893    $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
894 
895  if (is_array($p))
896    foreach ($p as $key => $val)
897      $qstring .= '&'.urlencode($key).'='.urlencode($val);
898 
899  return $base . ($action ? '&_action='.$action : '') . $qstring;
900}
901
902
903// @deprecated
904function show_message($message, $type='notice', $vars=NULL)
905  {
906  global $OUTPUT;
907  $OUTPUT->show_message($message, $type, $vars);
908  }
909
910
911/**
912 * Encrypt IMAP password using DES encryption
913 *
914 * @param string Password to encrypt
915 * @return string Encryprted string
916 */
917function encrypt_passwd($pass)
918  {
919  $cypher = des(get_des_key(), $pass, 1, 0, NULL);
920  return base64_encode($cypher);
921  }
922
923
924/**
925 * Decrypt IMAP password using DES encryption
926 *
927 * @param string Encrypted password
928 * @return string Plain password
929 */
930function decrypt_passwd($cypher)
931  {
932  $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
933  return preg_replace('/\x00/', '', $pass);
934  }
935
936
937/**
938 * Return a 24 byte key for the DES encryption
939 *
940 * @return string DES encryption key
941 */
942function get_des_key()
943  {
944  $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
945  $len = strlen($key);
946 
947  // make sure the key is exactly 24 chars long
948  if ($len<24)
949    $key .= str_repeat('_', 24-$len);
950  else if ($len>24)
951    substr($key, 0, 24);
952 
953  return $key;
954  }
955
956
957/**
958 * Read directory program/localization and return a list of available languages
959 *
960 * @return array List of available localizations
961 */
962function rcube_list_languages()
963  {
964  global $CONFIG, $INSTALL_PATH;
965  static $sa_languages = array();
966
967  if (!sizeof($sa_languages))
968    {
969    @include($INSTALL_PATH.'program/localization/index.inc');
970
971    if ($dh = @opendir($INSTALL_PATH.'program/localization'))
972      {
973      while (($name = readdir($dh)) !== false)
974        {
975        if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
976          continue;
977
978        if ($label = $rcube_languages[$name])
979          $sa_languages[$name] = $label ? $label : $name;
980        }
981      closedir($dh);
982      }
983    }
984  return $sa_languages;
985  }
986
987
988/**
989 * Add a localized label to the client environment
990 */
991function rcube_add_label()
992  {
993  global $OUTPUT;
994 
995  $arg_list = func_get_args();
996  foreach ($arg_list as $i => $name)
997    $OUTPUT->command('add_label', $name, rcube_label($name));
998  }
999
1000
1001/**
1002 * Garbage collector function for temp files.
1003 * Remove temp files older than two days
1004 */
1005function rcmail_temp_gc()
1006  {
1007  $tmp = unslashify($CONFIG['temp_dir']);
1008  $expire = mktime() - 172800;  // expire in 48 hours
1009
1010  if ($dir = opendir($tmp))
1011    {
1012    while (($fname = readdir($dir)) !== false)
1013      {
1014      if ($fname{0} == '.')
1015        continue;
1016
1017      if (filemtime($tmp.'/'.$fname) < $expire)
1018        @unlink($tmp.'/'.$fname);
1019      }
1020
1021    closedir($dir);
1022    }
1023  }
1024
1025
1026/**
1027 * Garbage collector for cache entries.
1028 * Remove all expired message cache records
1029 */
1030function rcmail_message_cache_gc()
1031  {
1032  global $DB, $CONFIG;
1033 
1034  // no cache lifetime configured
1035  if (empty($CONFIG['message_cache_lifetime']))
1036    return;
1037 
1038  // get target timestamp
1039  $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
1040 
1041  $DB->query("DELETE FROM ".get_table_name('messages')."
1042             WHERE  created < ".$DB->fromunixtime($ts));
1043  }
1044
1045
1046/**
1047 * Convert a string from one charset to another.
1048 * Uses mbstring and iconv functions if possible
1049 *
1050 * @param  string Input string
1051 * @param  string Suspected charset of the input string
1052 * @param  string Target charset to convert to; defaults to RCMAIL_CHARSET
1053 * @return Converted string
1054 */
1055function rcube_charset_convert($str, $from, $to=NULL)
1056  {
1057  global $MBSTRING;
1058
1059  $from = strtoupper($from);
1060  $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
1061
1062  if ($from==$to || $str=='' || empty($from))
1063    return $str;
1064
1065  // convert charset using iconv module 
1066  if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
1067    return iconv($from, $to . "//IGNORE", $str);
1068
1069  // convert charset using mbstring module 
1070  if ($MBSTRING)
1071    {
1072    $to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
1073    $from = $from=="UTF-7" ? "UTF7-IMAP": $from;
1074   
1075    // return if convert succeeded
1076    if (($out = mb_convert_encoding($str, $to, $from)) != '')
1077      return $out;
1078    }
1079
1080  $conv = new utf8();
1081
1082  // convert string to UTF-8
1083  if ($from=='UTF-7')
1084    $str = utf7_to_utf8($str);
1085  else if (($from=='ISO-8859-1') && function_exists('utf8_encode'))
1086    $str = utf8_encode($str);
1087  else if ($from!='UTF-8')
1088    {
1089    $conv->loadCharset($from);
1090    $str = $conv->strToUtf8($str);
1091    }
1092
1093  // encode string for output
1094  if ($to=='UTF-7')
1095    return utf8_to_utf7($str);
1096  else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
1097    return utf8_decode($str);
1098  else if ($to!='UTF-8')
1099    {
1100    $conv->loadCharset($to);
1101    return $conv->utf8ToStr($str);
1102    }
1103
1104  // return UTF-8 string
1105  return $str;
1106  }
1107
1108
1109/**
1110 * Replacing specials characters to a specific encoding type
1111 *
1112 * @param  string  Input string
1113 * @param  string  Encoding type: text|html|xml|js|url
1114 * @param  string  Replace mode for tags: show|replace|remove
1115 * @param  boolean Convert newlines
1116 * @return The quoted string
1117 */
1118function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
1119  {
1120  global $OUTPUT_TYPE, $OUTPUT;
1121  static $html_encode_arr, $js_rep_table, $xml_rep_table;
1122
1123  if (!$enctype)
1124    $enctype = $GLOBALS['OUTPUT_TYPE'];
1125
1126  // encode for plaintext
1127  if ($enctype=='text')
1128    return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
1129
1130  // encode for HTML output
1131  if ($enctype=='html')
1132    {
1133    if (!$html_encode_arr)
1134      {
1135      $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);       
1136      unset($html_encode_arr['?']);
1137      }
1138
1139    $ltpos = strpos($str, '<');
1140    $encode_arr = $html_encode_arr;
1141
1142    // don't replace quotes and html tags
1143    if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1144      {
1145      unset($encode_arr['"']);
1146      unset($encode_arr['<']);
1147      unset($encode_arr['>']);
1148      unset($encode_arr['&']);
1149      }
1150    else if ($mode=='remove')
1151      $str = strip_tags($str);
1152   
1153    // avoid douple quotation of &
1154    $out = preg_replace('/&amp;([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1155     
1156    return $newlines ? nl2br($out) : $out;
1157    }
1158
1159  if ($enctype=='url')
1160    return rawurlencode($str);
1161
1162  // if the replace tables for XML and JS are not yet defined
1163  if (!$js_rep_table)
1164    {
1165    $js_rep_table = $xml_rep_table = array();
1166    $xml_rep_table['&'] = '&amp;';
1167
1168    for ($c=160; $c<256; $c++)  // can be increased to support more charsets
1169      {
1170      $xml_rep_table[Chr($c)] = "&#$c;";
1171     
1172      if ($OUTPUT->get_charset()=='ISO-8859-1')
1173        $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1174      }
1175
1176    $xml_rep_table['"'] = '&quot;';
1177    }
1178
1179  // encode for XML
1180  if ($enctype=='xml')
1181    return strtr($str, $xml_rep_table);
1182
1183  // encode for javascript use
1184  if ($enctype=='js')
1185    {
1186    if ($OUTPUT->get_charset()!='UTF-8')
1187      $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1188     
1189    return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1190    }
1191
1192  // no encoding given -> return original string
1193  return $str;
1194  }
1195 
1196/**
1197 * Quote a given string.
1198 * Shortcut function for rep_specialchars_output
1199 *
1200 * @return string HTML-quoted string
1201 * @see rep_specialchars_output()
1202 */
1203function Q($str, $mode='strict', $newlines=TRUE)
1204  {
1205  return rep_specialchars_output($str, 'html', $mode, $newlines);
1206  }
1207
1208/**
1209 * Quote a given string for javascript output.
1210 * Shortcut function for rep_specialchars_output
1211 *
1212 * @return string JS-quoted string
1213 * @see rep_specialchars_output()
1214 */
1215function JQ($str)
1216  {
1217  return rep_specialchars_output($str, 'js');
1218  }
1219
1220
1221/**
1222 * Read input value and convert it for internal use
1223 * Performs stripslashes() and charset conversion if necessary
1224 *
1225 * @param  string   Field name to read
1226 * @param  int      Source to get value from (GPC)
1227 * @param  boolean  Allow HTML tags in field value
1228 * @param  string   Charset to convert into
1229 * @return string   Field value or NULL if not available
1230 */
1231function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1232  {
1233  global $OUTPUT;
1234  $value = NULL;
1235 
1236  if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1237    $value = $_GET[$fname];
1238  else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1239    $value = $_POST[$fname];
1240  else if ($source==RCUBE_INPUT_GPC)
1241    {
1242    if (isset($_POST[$fname]))
1243      $value = $_POST[$fname];
1244    else if (isset($_GET[$fname]))
1245      $value = $_GET[$fname];
1246    else if (isset($_COOKIE[$fname]))
1247      $value = $_COOKIE[$fname];
1248    }
1249 
1250  // strip slashes if magic_quotes enabled
1251  if ((bool)get_magic_quotes_gpc())
1252    $value = stripslashes($value);
1253
1254  // remove HTML tags if not allowed   
1255  if (!$allow_html)
1256    $value = strip_tags($value);
1257 
1258  // convert to internal charset
1259  if (is_object($OUTPUT))
1260    return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1261  else
1262    return $value;
1263  }
1264
1265
1266/**
1267 * Remove single and double quotes from given string
1268 *
1269 * @param string Input value
1270 * @return string Dequoted string
1271 */
1272function strip_quotes($str)
1273{
1274  return preg_replace('/[\'"]/', '', $str);
1275}
1276
1277
1278/**
1279 * Remove new lines characters from given string
1280 *
1281 * @param string Input value
1282 * @return string Stripped string
1283 */
1284function strip_newlines($str)
1285{
1286  return preg_replace('/[\r\n]/', '', $str);
1287}
1288
1289
1290/**
1291 * Check if a specific template exists
1292 *
1293 * @param string Template name
1294 * @return boolean True if template exists
1295 */
1296function template_exists($name)
1297  {
1298  global $CONFIG;
1299  $skin_path = $CONFIG['skin_path'];
1300
1301  // check template file
1302  return is_file("$skin_path/templates/$name.html");
1303  }
1304
1305
1306/**
1307 * Wrapper for rcmail_template::parse()
1308 * @deprecated
1309 */
1310function parse_template($name='main', $exit=true)
1311  {
1312  $GLOBALS['OUTPUT']->parse($name, $exit);
1313  }
1314
1315
1316/**
1317 * Create a HTML table based on the given data
1318 *
1319 * @param  array  Named table attributes
1320 * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
1321 * @param  array  List of cols to show
1322 * @param  string Name of the identifier col
1323 * @return string HTML table code
1324 */
1325function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1326  {
1327  global $DB;
1328 
1329  // allow the following attributes to be added to the <table> tag
1330  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1331 
1332  $table = '<table' . $attrib_str . ">\n";
1333   
1334  // add table title
1335  $table .= "<thead><tr>\n";
1336
1337  foreach ($a_show_cols as $col)
1338    $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1339
1340  $table .= "</tr></thead>\n<tbody>\n";
1341 
1342  $c = 0;
1343  if (!is_array($table_data))
1344    {
1345    while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1346      {
1347      $zebra_class = $c%2 ? 'even' : 'odd';
1348
1349      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1350
1351      // format each col
1352      foreach ($a_show_cols as $col)
1353        {
1354        $cont = Q($sql_arr[$col]);
1355        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1356        }
1357
1358      $table .= "</tr>\n";
1359      $c++;
1360      }
1361    }
1362  else
1363    {
1364    foreach ($table_data as $row_data)
1365      {
1366      $zebra_class = $c%2 ? 'even' : 'odd';
1367
1368      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1369
1370      // format each col
1371      foreach ($a_show_cols as $col)
1372        {
1373        $cont = Q($row_data[$col]);
1374        $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1375        }
1376
1377      $table .= "</tr>\n";
1378      $c++;
1379      }
1380    }
1381
1382  // complete message table
1383  $table .= "</tbody></table>\n";
1384 
1385  return $table;
1386  }
1387
1388
1389/**
1390 * Create an edit field for inclusion on a form
1391 *
1392 * @param string col field name
1393 * @param string value field value
1394 * @param array attrib HTML element attributes for field
1395 * @param string type HTML element type (default 'text')
1396 * @return string HTML field definition
1397 */
1398function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1399  {
1400  $fname = '_'.$col;
1401  $attrib['name'] = $fname;
1402 
1403  if ($type=='checkbox')
1404    {
1405    $attrib['value'] = '1';
1406    $input = new checkbox($attrib);
1407    }
1408  else if ($type=='textarea')
1409    {
1410    $attrib['cols'] = $attrib['size'];
1411    $input = new textarea($attrib);
1412    }
1413  else
1414    $input = new textfield($attrib);
1415
1416  // use value from post
1417  if (!empty($_POST[$fname]))
1418    $value = $_POST[$fname];
1419
1420  $out = $input->show($value);
1421         
1422  return $out;
1423  }
1424
1425
1426/**
1427 * Return the mail domain configured for the given host
1428 *
1429 * @param string IMAP host
1430 * @return string Resolved SMTP host
1431 */
1432function rcmail_mail_domain($host)
1433  {
1434  global $CONFIG;
1435
1436  $domain = $host;
1437  if (is_array($CONFIG['mail_domain']))
1438    {
1439    if (isset($CONFIG['mail_domain'][$host]))
1440      $domain = $CONFIG['mail_domain'][$host];
1441    }
1442  else if (!empty($CONFIG['mail_domain']))
1443    $domain = $CONFIG['mail_domain'];
1444
1445  return $domain;
1446  }
1447
1448
1449/**
1450 * Compose a valid attribute string for HTML tags
1451 *
1452 * @param array Named tag attributes
1453 * @param array List of allowed attributes
1454 * @return string HTML formatted attribute string
1455 */
1456function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1457  {
1458  // allow the following attributes to be added to the <iframe> tag
1459  $attrib_str = '';
1460  foreach ($allowed_attribs as $a)
1461    if (isset($attrib[$a]))
1462      $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
1463
1464  return $attrib_str;
1465  }
1466
1467
1468/**
1469 * Convert a HTML attribute string attributes to an associative array (name => value)
1470 *
1471 * @param string Input string
1472 * @return array Key-value pairs of parsed attributes
1473 */
1474function parse_attrib_string($str)
1475  {
1476  $attrib = array();
1477  preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1478
1479  // convert attributes to an associative array (name => value)
1480  if ($regs)
1481    foreach ($regs as $attr)
1482      $attrib[strtolower($attr[1])] = $attr[3];
1483
1484  return $attrib;
1485  }
1486
1487
1488/**
1489 * Convert the given date to a human readable form
1490 * This uses the date formatting properties from config
1491 *
1492 * @param mixed Date representation (string or timestamp)
1493 * @param string Date format to use
1494 * @return string Formatted date string
1495 */
1496function format_date($date, $format=NULL)
1497  {
1498  global $CONFIG, $sess_user_lang;
1499 
1500  $ts = NULL;
1501 
1502  if (is_numeric($date))
1503    $ts = $date;
1504  else if (!empty($date))
1505    $ts = @strtotime($date);
1506   
1507  if (empty($ts))
1508    return '';
1509   
1510  // get user's timezone
1511  $tz = $CONFIG['timezone'];
1512  if ($CONFIG['dst_active'])
1513    $tz++;
1514
1515  // convert time to user's timezone
1516  $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1517 
1518  // get current timestamp in user's timezone
1519  $now = time();  // local time
1520  $now -= (int)date('Z'); // make GMT time
1521  $now += ($tz * 3600); // user's time
1522  $now_date = getdate($now);
1523
1524  $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1525  $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1526
1527  // define date format depending on current time 
1528  if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1529    return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1530  else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1531    $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1532  else if (!$format)
1533    $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1534
1535
1536  // parse format string manually in order to provide localized weekday and month names
1537  // an alternative would be to convert the date() format string to fit with strftime()
1538  $out = '';
1539  for($i=0; $i<strlen($format); $i++)
1540    {
1541    if ($format{$i}=='\\')  // skip escape chars
1542      continue;
1543   
1544    // write char "as-is"
1545    if ($format{$i}==' ' || $format{$i-1}=='\\')
1546      $out .= $format{$i};
1547    // weekday (short)
1548    else if ($format{$i}=='D')
1549      $out .= rcube_label(strtolower(date('D', $timestamp)));
1550    // weekday long
1551    else if ($format{$i}=='l')
1552      $out .= rcube_label(strtolower(date('l', $timestamp)));
1553    // month name (short)
1554    else if ($format{$i}=='M')
1555      $out .= rcube_label(strtolower(date('M', $timestamp)));
1556    // month name (long)
1557    else if ($format{$i}=='F')
1558      $out .= rcube_label(strtolower(date('F', $timestamp)));
1559    else
1560      $out .= date($format{$i}, $timestamp);
1561    }
1562 
1563  return $out;
1564  }
1565
1566
1567/**
1568 * Compose a valid representaion of name and e-mail address
1569 *
1570 * @param string E-mail address
1571 * @param string Person name
1572 * @return string Formatted string
1573 */
1574function format_email_recipient($email, $name='')
1575  {
1576  if ($name && $name != $email)
1577    return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
1578  else
1579    return $email;
1580  }
1581
1582
1583
1584/****** debugging functions ********/
1585
1586
1587/**
1588 * Print or write debug messages
1589 *
1590 * @param mixed Debug message or data
1591 */
1592function console($msg)
1593  {
1594  if (!is_string($msg))
1595    $msg = var_export($msg, true);
1596
1597  if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1598    write_log('console', $msg);
1599  else if ($GLOBALS['REMOTE_REQUEST'])
1600    print "/*\n $msg \n*/\n";
1601  else
1602    {
1603    print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1604    print $msg;
1605    print "</pre></div>\n";
1606    }
1607  }
1608
1609
1610/**
1611 * Append a line to a logfile in the logs directory.
1612 * Date will be added automatically to the line.
1613 *
1614 * @param $name Name of logfile
1615 * @param $line Line to append
1616 */
1617function write_log($name, $line)
1618  {
1619  global $CONFIG, $INSTALL_PATH;
1620
1621  if (!is_string($line))
1622    $line = var_export($line, true);
1623 
1624  $log_entry = sprintf("[%s]: %s\n",
1625                 date("d-M-Y H:i:s O", mktime()),
1626                 $line);
1627                 
1628  if (empty($CONFIG['log_dir']))
1629    $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1630     
1631  // try to open specific log file for writing
1632  if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))   
1633    {
1634    fwrite($fp, $log_entry);
1635    fclose($fp);
1636    }
1637  }
1638
1639
1640/**
1641 * @access private
1642 */
1643function rcube_timer()
1644  {
1645  list($usec, $sec) = explode(" ", microtime());
1646  return ((float)$usec + (float)$sec);
1647  }
1648 
1649
1650/**
1651 * @access private
1652 */
1653function rcube_print_time($timer, $label='Timer')
1654  {
1655  static $print_count = 0;
1656 
1657  $print_count++;
1658  $now = rcube_timer();
1659  $diff = $now-$timer;
1660 
1661  if (empty($label))
1662    $label = 'Timer '.$print_count;
1663 
1664  console(sprintf("%s: %0.4f sec", $label, $diff));
1665  }
1666
1667
1668/**
1669 * Return the mailboxlist in HTML
1670 *
1671 * @param array Named parameters
1672 * @return string HTML code for the gui object
1673 */
1674function rcmail_mailbox_list($attrib)
1675  {
1676  global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1677  static $s_added_script = FALSE;
1678  static $a_mailboxes;
1679
1680  // add some labels to client
1681  rcube_add_label('purgefolderconfirm');
1682  rcube_add_label('deletemessagesconfirm');
1683 
1684// $mboxlist_start = rcube_timer();
1685 
1686  $type = $attrib['type'] ? $attrib['type'] : 'ul';
1687  $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1688                                  array('style', 'class', 'id');
1689                                 
1690  if ($type=='ul' && !$attrib['id'])
1691    $attrib['id'] = 'rcmboxlist';
1692
1693  // allow the following attributes to be added to the <ul> tag
1694  $attrib_str = create_attrib_string($attrib, $add_attrib);
1695 
1696  $out = '<' . $type . $attrib_str . ">\n";
1697 
1698  // add no-selection option
1699  if ($type=='select' && $attrib['noselection'])
1700    $out .= sprintf('<option value="0">%s</option>'."\n",
1701                    rcube_label($attrib['noselection']));
1702 
1703  // get mailbox list
1704  $mbox_name = $IMAP->get_mailbox_name();
1705 
1706  // for these mailboxes we have localized labels
1707  $special_mailboxes = array('inbox', 'sent', 'drafts', 'trash', 'junk');
1708
1709
1710  // build the folders tree
1711  if (empty($a_mailboxes))
1712    {
1713    // get mailbox list
1714    $a_folders = $IMAP->list_mailboxes();
1715    $delimiter = $IMAP->get_hierarchy_delimiter();
1716    $a_mailboxes = array();
1717
1718// rcube_print_time($mboxlist_start, 'list_mailboxes()');
1719
1720    foreach ($a_folders as $folder)
1721      rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1722    }
1723
1724// var_dump($a_mailboxes);
1725
1726  if ($type=='select')
1727    $out .= rcmail_render_folder_tree_select($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
1728   else
1729    $out .= rcmail_render_folder_tree_html($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
1730
1731// rcube_print_time($mboxlist_start, 'render_folder_tree()');
1732
1733
1734  if ($type=='ul')
1735    $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1736
1737  return $out . "</$type>";
1738  }
1739
1740
1741
1742
1743/**
1744 * Create a hierarchical array of the mailbox list
1745 * @access private
1746 */
1747function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1748  {
1749  $pos = strpos($folder, $delm);
1750  if ($pos !== false)
1751    {
1752    $subFolders = substr($folder, $pos+1);
1753    $currentFolder = substr($folder, 0, $pos);
1754    }
1755  else
1756    {
1757    $subFolders = false;
1758    $currentFolder = $folder;
1759    }
1760
1761  $path .= $currentFolder;
1762
1763  if (!isset($arrFolders[$currentFolder]))
1764    {
1765    $arrFolders[$currentFolder] = array('id' => $path,
1766                                        'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1767                                        'folders' => array());
1768    }
1769
1770  if (!empty($subFolders))
1771    rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1772  }
1773 
1774
1775/**
1776 * Return html for a structured list &lt;ul&gt; for the mailbox tree
1777 * @access private
1778 */
1779function rcmail_render_folder_tree_html(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
1780  {
1781  global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1782
1783  $idx = 0;
1784  $out = '';
1785  foreach ($arrFolders as $key => $folder)
1786    {
1787    $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1788    $title = '';
1789
1790    $folder_lc = strtolower($folder['id']);
1791    if (in_array($folder_lc, $special))
1792      $foldername = rcube_label($folder_lc);
1793    else
1794      {
1795      $foldername = $folder['name'];
1796
1797      // shorten the folder name to a given length
1798      if ($maxlength && $maxlength>1)
1799        {
1800        $fname = abbrevate_string($foldername, $maxlength);
1801        if ($fname != $foldername)
1802          $title = ' title="'.Q($foldername).'"';
1803        $foldername = $fname;
1804        }
1805      }
1806
1807    // add unread message count display
1808    if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox_name)))
1809      $foldername .= sprintf(' (%d)', $unread_count);
1810
1811    // make folder name safe for ids and class names
1812    $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1813    $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
1814
1815    // set special class for Sent, Drafts, Trash and Junk
1816    if ($folder['id']==$CONFIG['sent_mbox'])
1817      $class_name = 'sent';
1818    else if ($folder['id']==$CONFIG['drafts_mbox'])
1819      $class_name = 'drafts';
1820    else if ($folder['id']==$CONFIG['trash_mbox'])
1821      $class_name = 'trash';
1822    else if ($folder['id']==$CONFIG['junk_mbox'])
1823      $class_name = 'junk';
1824
1825    $js_name = htmlspecialchars(JQ($folder['id']));
1826    $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1827                    ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1828                    ' onmouseover="return %s.focus_folder(\'%s\')"' .
1829                    ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1830                    ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1831                    $folder_id,
1832                    $class_name,
1833                    $zebra_class,
1834                    $unread_count ? ' unread' : '',
1835                    $folder['id']==$mbox_name ? ' selected' : '',
1836                    Q(rcmail_url('', array('_mbox' => $folder['id']))),
1837                    JS_OBJECT_NAME,
1838                    $js_name,
1839                    JS_OBJECT_NAME,
1840                    $js_name,
1841                    JS_OBJECT_NAME,
1842                    $js_name,
1843                    JS_OBJECT_NAME,
1844                    $js_name,
1845                    $title,
1846                    Q($foldername));
1847
1848    if (!empty($folder['folders']))
1849      $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1850
1851    $out .= "</li>\n";
1852    $idx++;
1853    }
1854
1855  return $out;
1856  }
1857
1858
1859/**
1860 * Return html for a flat list <select> for the mailbox tree
1861 * @access private
1862 */
1863function rcmail_render_folder_tree_select(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
1864  {
1865  global $IMAP, $OUTPUT;
1866
1867  $idx = 0;
1868  $out = '';
1869  foreach ($arrFolders as $key=>$folder)
1870    {
1871    $folder_lc = strtolower($folder['id']);
1872    if (in_array($folder_lc, $special))
1873      $foldername = rcube_label($folder_lc);
1874    else
1875      {
1876      $foldername = $folder['name'];
1877     
1878      // shorten the folder name to a given length
1879      if ($maxlength && $maxlength>1)
1880        $foldername = abbrevate_string($foldername, $maxlength);
1881      }
1882
1883    $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1884                    htmlspecialchars($folder['id']),
1885                    str_repeat('&nbsp;', $nestLevel*4),
1886                    Q($foldername));
1887
1888    if (!empty($folder['folders']))
1889      $out .= rcmail_render_folder_tree_select($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1);
1890
1891    $idx++;
1892    }
1893
1894  return $out;
1895  }
1896
1897?>
Note: See TracBrowser for help on using the repository browser.