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

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