source: github/program/include/rcmail.php @ bd34cad

HEADcourier-fixdev-browser-capabilitiespdorelease-0.8
Last change on this file since bd34cad was bd34cad, checked in by alecpl <alec@…>, 18 months ago
  • Add option to set session name (#1486433)
  • Property mode set to 100644
File size: 49.0 KB
RevLine 
[197601e]1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcmail.php                                            |
6 |                                                                       |
[e019f2d]7 | This file is part of the Roundcube Webmail client                     |
[63e9927]8 | Copyright (C) 2008-2011, The Roundcube Dev Team                       |
[1a716d2]9 | Copyright (C) 2011, Kolab Systems AG                                  |
[197601e]10 | Licensed under the GNU GPL                                            |
11 |                                                                       |
12 | PURPOSE:                                                              |
13 |   Application class providing core functions and holding              |
14 |   instances of all 'global' objects like db- and imap-connections     |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17 +-----------------------------------------------------------------------+
18
[638fb8a]19 $Id$
[197601e]20
21*/
22
23
24/**
[e019f2d]25 * Application class of Roundcube Webmail
[197601e]26 * implemented as singleton
27 *
28 * @package Core
29 */
30class rcmail
31{
[5c461ba]32  /**
33   * Main tasks.
34   *
35   * @var array
36   */
[677e1f2]37  static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
38
[5c461ba]39  /**
40   * Singleton instace of rcmail
41   *
42   * @var rcmail
43   */
[197601e]44  static private $instance;
[677e1f2]45
[5c461ba]46  /**
47   * Stores instance of rcube_config.
48   *
49   * @var rcube_config
50   */
[197601e]51  public $config;
[5c461ba]52
53  /**
54   * Stores rcube_user instance.
55   *
56   * @var rcube_user
57   */
[197601e]58  public $user;
[5c461ba]59
60  /**
61   * Instace of database class.
62   *
63   * @var rcube_mdb2
64   */
[197601e]65  public $db;
[5c461ba]66
67  /**
[76d4019]68   * Instace of Memcache class.
69   *
70   * @var rcube_mdb2
71   */
72  public $memcache;
73
74  /**
[5c461ba]75   * Instace of rcube_session class.
76   *
77   * @var rcube_session
78   */
[929a508]79  public $session;
[5c461ba]80
81  /**
82   * Instance of rcube_smtp class.
83   *
84   * @var rcube_smtp
85   */
[2c3d81d]86  public $smtp;
[5c461ba]87
88  /**
89   * Instance of rcube_imap class.
90   *
91   * @var rcube_imap
92   */
[197601e]93  public $imap;
[5c461ba]94
95  /**
96   * Instance of rcube_template class.
97   *
98   * @var rcube_template
99   */
[197601e]100  public $output;
[5c461ba]101
102  /**
103   * Instance of rcube_plugin_api.
104   *
105   * @var rcube_plugin_api
106   */
[cc97ea0]107  public $plugins;
[5c461ba]108
109  /**
110   * Current task.
111   *
112   * @var string
113   */
[9b94eb6]114  public $task;
[5c461ba]115
116  /**
117   * Current action.
118   *
119   * @var string
120   */
[197601e]121  public $action = '';
122  public $comm_path = './';
[677e1f2]123
[197601e]124  private $texts;
[0501b63]125  private $address_books = array();
[5cf5ee6]126  private $caches = array();
[68d2d54]127  private $action_map = array();
[580adc8]128  private $shutdown_functions = array();
[677e1f2]129
130
[197601e]131  /**
132   * This implements the 'singleton' design pattern
133   *
[5c461ba]134   * @return rcmail The one and only instance
[197601e]135   */
136  static function get_instance()
137  {
138    if (!self::$instance) {
139      self::$instance = new rcmail();
140      self::$instance->startup();  // init AFTER object was linked with self::$instance
141    }
142
143    return self::$instance;
144  }
[b62a0d2]145
146
[197601e]147  /**
148   * Private constructor
149   */
150  private function __construct()
151  {
152    // load configuration
153    $this->config = new rcube_config();
[b62a0d2]154
[197601e]155    register_shutdown_function(array($this, 'shutdown'));
156  }
[b62a0d2]157
158
[197601e]159  /**
160   * Initial startup function
161   * to register session, create database and imap connections
162   *
163   * @todo Remove global vars $DB, $USER
164   */
165  private function startup()
166  {
[b77d0dd]167    // initialize syslog
168    if ($this->config->get('log_driver') == 'syslog') {
169      $syslog_id = $this->config->get('syslog_id', 'roundcube');
170      $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
171      openlog($syslog_id, LOG_ODELAY, $syslog_facility);
172    }
[cc97ea0]173
[197601e]174    // connect to database
175    $GLOBALS['DB'] = $this->get_dbh();
176
[929a508]177    // start session
178    $this->session_init();
[197601e]179
180    // create user object
181    $this->set_user(new rcube_user($_SESSION['user_id']));
182
[929a508]183    // configure session (after user config merge!)
184    $this->session_configure();
185
[9b94eb6]186    // set task and action properties
187    $this->set_task(get_input_value('_task', RCUBE_INPUT_GPC));
188    $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
189
[197601e]190    // reset some session parameters when changing task
[677e1f2]191    if ($this->task != 'utils') {
192      if ($this->session && $_SESSION['task'] != $this->task)
193        $this->session->remove('page');
194      // set current task to session
195      $_SESSION['task'] = $this->task;
196    }
[197601e]197
[48bc52e]198    // init output class
199    if (!empty($_REQUEST['_remote']))
[929a508]200      $GLOBALS['OUTPUT'] = $this->json_init();
[48bc52e]201    else
202      $GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
203
[cc97ea0]204    // create plugin API and load plugins
205    $this->plugins = rcube_plugin_api::get_instance();
[48bc52e]206
207    // init plugins
208    $this->plugins->init();
[197601e]209  }
[b62a0d2]210
211
[197601e]212  /**
213   * Setter for application task
214   *
215   * @param string Task to set
216   */
217  public function set_task($task)
218  {
[1c932d5]219    $task = asciiwords($task);
[9b94eb6]220
221    if ($this->user && $this->user->ID)
[c3be8ed]222      $task = !$task ? 'mail' : $task;
[9b94eb6]223    else
224      $task = 'login';
225
226    $this->task = $task;
[1c932d5]227    $this->comm_path = $this->url(array('task' => $this->task));
[b62a0d2]228
[197601e]229    if ($this->output)
[1c932d5]230      $this->output->set_env('task', $this->task);
[197601e]231  }
[b62a0d2]232
233
[197601e]234  /**
235   * Setter for system user object
236   *
[5c461ba]237   * @param rcube_user Current user instance
[197601e]238   */
239  public function set_user($user)
240  {
241    if (is_object($user)) {
242      $this->user = $user;
243      $GLOBALS['USER'] = $this->user;
[b62a0d2]244
[197601e]245      // overwrite config with user preferences
[b545d3e]246      $this->config->set_user_prefs((array)$this->user->get_prefs());
[197601e]247    }
[b62a0d2]248
[c8ae249]249    $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
[531abb1]250
[197601e]251    // set localization
[e80f502]252    setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
[14de18d]253
[b62a0d2]254    // workaround for http://bugs.php.net/bug.php?id=18556
255    if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
256      setlocale(LC_CTYPE, 'en_US' . '.utf8');
[197601e]257  }
[b62a0d2]258
259
[197601e]260  /**
261   * Check the given string and return a valid language code
262   *
263   * @param string Language code
264   * @return string Valid language code
265   */
266  private function language_prop($lang)
267  {
268    static $rcube_languages, $rcube_language_aliases;
[b62a0d2]269
[c8ae249]270    // user HTTP_ACCEPT_LANGUAGE if no language is specified
271    if (empty($lang) || $lang == 'auto') {
272       $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
273       $lang = str_replace('-', '_', $accept_langs[0]);
274     }
[b62a0d2]275
[197601e]276    if (empty($rcube_languages)) {
277      @include(INSTALL_PATH . 'program/localization/index.inc');
278    }
[b62a0d2]279
[197601e]280    // check if we have an alias for that language
281    if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
282      $lang = $rcube_language_aliases[$lang];
283    }
284    // try the first two chars
[c3ab7537]285    else if (!isset($rcube_languages[$lang])) {
[7e78b2e]286      $short = substr($lang, 0, 2);
[b62a0d2]287
[235086c]288      // check if we have an alias for the short language code
289      if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
290        $lang = $rcube_language_aliases[$short];
291      }
[c3ab7537]292      // expand 'nn' to 'nn_NN'
293      else if (!isset($rcube_languages[$short])) {
[235086c]294        $lang = $short.'_'.strtoupper($short);
295      }
[197601e]296    }
297
[1854c45]298    if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
[197601e]299      $lang = 'en_US';
300    }
301
302    return $lang;
303  }
[b62a0d2]304
305
[197601e]306  /**
307   * Get the current database connection
308   *
[5c461ba]309   * @return rcube_mdb2  Database connection object
[197601e]310   */
311  public function get_dbh()
312  {
313    if (!$this->db) {
314      $config_all = $this->config->all();
315
[9e8e5fa]316      $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
[197601e]317      $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
318      $this->db->set_debug((bool)$config_all['sql_debug']);
319    }
320
321    return $this->db;
322  }
[76d4019]323 
324 
325  /**
326   * Get global handle for memcache access
327   *
328   * @return object Memcache
329   */
330  public function get_memcache()
331  {
332    if (!isset($this->memcache)) {
333      // no memcache support in PHP
334      if (!class_exists('Memcache')) {
335        $this->memcache = false;
336        return false;
337      }
[7ad8e2c]338
[76d4019]339      $this->memcache = new Memcache;
[2103032]340      $this->mc_available = 0;
341     
342      // add alll configured hosts to pool
343      $pconnect = $this->config->get('memcache_pconnect', true);
[76d4019]344      foreach ($this->config->get('memcache_hosts', array()) as $host) {
345        list($host, $port) = explode(':', $host);
346        if (!$port) $port = 11211;
[2103032]347        $this->mc_available += intval($this->memcache->addServer($host, $port, $pconnect, 1, 1, 15, false, array($this, 'memcache_failure')));
[76d4019]348      }
[2103032]349     
350      // test connection and failover (will result in $this->mc_available == 0 on complete failure)
351      $this->memcache->increment('__CONNECTIONTEST__', 1);  // NOP if key doesn't exist
[7ad8e2c]352
[2103032]353      if (!$this->mc_available)
[76d4019]354        $this->memcache = false;
355    }
[7ad8e2c]356
[76d4019]357    return $this->memcache;
358  }
[2103032]359 
360  /**
361   * Callback for memcache failure
362   */
363  public function memcache_failure($host, $port)
364  {
365    static $seen = array();
366   
367    // only report once
368    if (!$seen["$host:$port"]++) {
369      $this->mc_available--;
370      raise_error(array('code' => 604, 'type' => 'db',
371        'line' => __LINE__, 'file' => __FILE__,
372        'message' => "Memcache failure on host $host:$port"),
373        true, false);
374    }
375  }
[b62a0d2]376
377
[197601e]378  /**
[5cf5ee6]379   * Initialize and get cache object
380   *
[c9f4e9b]381   * @param string $name   Cache identifier
382   * @param string $type   Cache type ('db', 'apc' or 'memcache')
383   * @param int    $ttl    Expiration time for cache items in seconds
384   * @param bool   $packed Enables/disables data serialization
[5cf5ee6]385   *
386   * @return rcube_cache Cache object
387   */
[c9f4e9b]388  public function get_cache($name, $type='db', $ttl=0, $packed=true)
[5cf5ee6]389  {
390    if (!isset($this->caches[$name])) {
[c9f4e9b]391      $this->caches[$name] = new rcube_cache($type, $_SESSION['user_id'], $name, $ttl, $packed);
[5cf5ee6]392    }
393
394    return $this->caches[$name];
395  }
396
397
398  /**
[ade8e11]399   * Return instance of the internal address book class
400   *
[3704b78]401   * @param string  Address book identifier
[ade8e11]402   * @param boolean True if the address book needs to be writeable
[7f7ed2d]403   *
[5c461ba]404   * @return rcube_contacts Address book object
[ade8e11]405   */
406  public function get_address_book($id, $writeable = false)
407  {
[b896b18]408    $contacts    = null;
[ade8e11]409    $ldap_config = (array)$this->config->get('ldap_public');
[b896b18]410    $abook_type  = strtolower($this->config->get('address_book_type'));
[cc97ea0]411
[f03d89e]412    // 'sql' is the alias for '0' used by autocomplete
413    if ($id == 'sql')
414        $id = '0';
415
[0501b63]416    // use existing instance
[9a835c7]417    if (isset($this->address_books[$id]) && is_object($this->address_books[$id])
418      && is_a($this->address_books[$id], 'rcube_addressbook')
419      && (!$writeable || !$this->address_books[$id]->readonly)
420    ) {
[0501b63]421      $contacts = $this->address_books[$id];
422    }
[cc97ea0]423    else if ($id && $ldap_config[$id]) {
[0102742]424      $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
[ade8e11]425    }
[cc97ea0]426    else if ($id === '0') {
427      $contacts = new rcube_contacts($this->db, $this->user->ID);
428    }
[b896b18]429    else {
430      $plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
431
432      // plugin returned instance of a rcube_addressbook
433      if ($plugin['instance'] instanceof rcube_addressbook) {
434        $contacts = $plugin['instance'];
435      }
[7f7ed2d]436      // get first source from the list
[5ed119e]437      else if (!$id) {
[7f7ed2d]438        $source = reset($this->get_address_sources($writeable));
439        if (!empty($source)) {
440          $contacts = $this->get_address_book($source['id']);
441          if ($contacts)
442            $id = $source['id'];
[5ed119e]443        }
[ade8e11]444      }
[5ed119e]445    }
446
447    if (!$contacts) {
448      raise_error(array(
[782d859]449        'code' => 700, 'type' => 'php',
[5ed119e]450        'file' => __FILE__, 'line' => __LINE__,
451        'message' => "Addressbook source ($id) not found!"),
452        true, true);
[ade8e11]453    }
[b62a0d2]454
[457373b]455    // add to the 'books' array for shutdown function
[0501b63]456    if (!isset($this->address_books[$id]))
457      $this->address_books[$id] = $contacts;
[457373b]458
[ade8e11]459    return $contacts;
460  }
[3704b78]461
462
463  /**
464   * Return address books list
465   *
466   * @param boolean True if the address book needs to be writeable
[5c9d1ff]467   *
[3704b78]468   * @return array  Address books array
469   */
470  public function get_address_sources($writeable = false)
471  {
472    $abook_type = strtolower($this->config->get('address_book_type'));
[7fdb9da]473    $ldap_config = $this->config->get('ldap_public');
474    $autocomplete = (array) $this->config->get('autocomplete_addressbooks');
[3704b78]475    $list = array();
476
477    // We are using the DB address book
478    if ($abook_type != 'ldap') {
[0501b63]479      if (!isset($this->address_books['0']))
480        $this->address_books['0'] = new rcube_contacts($this->db, $this->user->ID);
[3704b78]481      $list['0'] = array(
[5c9d1ff]482        'id'       => '0',
483        'name'     => rcube_label('personaladrbook'),
484        'groups'   => $this->address_books['0']->groups,
[8c263ee]485        'readonly' => $this->address_books['0']->readonly,
[d06e57f]486        'autocomplete' => in_array('sql', $autocomplete),
487        'undelete' => $this->address_books['0']->undelete && $this->config->get('undo_timeout'),
[3704b78]488      );
489    }
490
[7fdb9da]491    if ($ldap_config) {
492      $ldap_config = (array) $ldap_config;
[3704b78]493      foreach ($ldap_config as $id => $prop)
494        $list[$id] = array(
[5c9d1ff]495          'id'       => $id,
496          'name'     => $prop['name'],
497          'groups'   => is_array($prop['groups']),
[a61bbb2]498          'readonly' => !$prop['writable'],
[5c9d1ff]499          'hidden'   => $prop['hidden'],
500          'autocomplete' => in_array($id, $autocomplete)
[3704b78]501        );
502    }
503
[e6ce006]504    $plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
[3704b78]505    $list = $plugin['sources'];
506
[0501b63]507    foreach ($list as $idx => $item) {
508      // register source for shutdown function
509      if (!is_object($this->address_books[$item['id']]))
510        $this->address_books[$item['id']] = $item;
511      // remove from list if not writeable as requested
512      if ($writeable && $item['readonly'])
[c0297f4]513          unset($list[$idx]);
[3704b78]514    }
[8c263ee]515
[3704b78]516    return $list;
517  }
[b62a0d2]518
519
[ade8e11]520  /**
[197601e]521   * Init output object for GUI and add common scripts.
522   * This will instantiate a rcmail_template object and set
523   * environment vars according to the current session and configuration
[0ece58d]524   *
525   * @param boolean True if this request is loaded in a (i)frame
[5c461ba]526   * @return rcube_template Reference to HTML output object
[197601e]527   */
528  public function load_gui($framed = false)
529  {
530    // init output page
[0ece58d]531    if (!($this->output instanceof rcube_template))
532      $this->output = new rcube_template($this->task, $framed);
[197601e]533
[95d90f8]534    // set keep-alive/check-recent interval
[bf67d60]535    if ($this->session && ($keep_alive = $this->session->get_keep_alive())) {
[929a508]536      $this->output->set_env('keep_alive', $keep_alive);
[95d90f8]537    }
[197601e]538
539    if ($framed) {
540      $this->comm_path .= '&_framed=1';
541      $this->output->set_env('framed', true);
542    }
543
544    $this->output->set_env('task', $this->task);
545    $this->output->set_env('action', $this->action);
546    $this->output->set_env('comm_path', $this->comm_path);
[79c45f4]547    $this->output->set_charset(RCMAIL_CHARSET);
[197601e]548
[7f5a849]549    // add some basic labels to client
[74d421d5]550    $this->output->add_label('loading', 'servererror');
[b62a0d2]551
[197601e]552    return $this->output;
553  }
[b62a0d2]554
555
[197601e]556  /**
557   * Create an output object for JSON responses
[0ece58d]558   *
[5c461ba]559   * @return rcube_json_output Reference to JSON output object
[197601e]560   */
[929a508]561  public function json_init()
[197601e]562  {
[0ece58d]563    if (!($this->output instanceof rcube_json_output))
564      $this->output = new rcube_json_output($this->task);
[b62a0d2]565
[197601e]566    return $this->output;
567  }
[2c3d81d]568
569
570  /**
571   * Create SMTP object and connect to server
572   *
573   * @param boolean True if connection should be established
574   */
575  public function smtp_init($connect = false)
576  {
577    $this->smtp = new rcube_smtp();
[b62a0d2]578
[2c3d81d]579    if ($connect)
580      $this->smtp->connect();
581  }
[b62a0d2]582
583
[197601e]584  /**
585   * Create global IMAP object and connect to server
586   *
587   * @param boolean True if connection should be established
588   * @todo Remove global $IMAP
589   */
[1854c45]590  public function imap_init($connect = false)
[197601e]591  {
[47d8d39]592    // already initialized
593    if (is_object($this->imap))
594      return;
[b62a0d2]595
[5cf5ee6]596    $this->imap = new rcube_imap();
[197601e]597    $this->imap->skip_deleted = $this->config->get('skip_deleted');
598
599    // enable caching of imap data
[5cf5ee6]600    $imap_cache = $this->config->get('imap_cache');
601    $messages_cache = $this->config->get('messages_cache');
602    // for backward compatybility
603    if ($imap_cache === null && $messages_cache === null && $this->config->get('enable_caching')) {
604        $imap_cache     = 'db';
605        $messages_cache = true;
[197601e]606    }
[5cf5ee6]607    if ($imap_cache)
608        $this->imap->set_caching($imap_cache);
609    if ($messages_cache)
610        $this->imap->set_messages_caching(true);
[197601e]611
612    // set pagesize from config
613    $this->imap->set_pagesize($this->config->get('pagesize', 50));
[b62a0d2]614
[600981d]615    // Setting root and delimiter before establishing the connection
[b62a0d2]616    // can save time detecting them using NAMESPACE and LIST
[230f944]617    $options = array(
[e7e7947]618      'auth_type'   => $this->config->get('imap_auth_type', 'check'),
[a1fe6bd]619      'auth_cid'    => $this->config->get('imap_auth_cid'),
620      'auth_pw'     => $this->config->get('imap_auth_pw'),
[7f1da48]621      'debug'       => (bool) $this->config->get('imap_debug', 0),
[f07d238]622      'force_caps'  => (bool) $this->config->get('imap_force_caps'),
623      'timeout'     => (int) $this->config->get('imap_timeout', 0),
[230f944]624    );
[76db10d]625
[230f944]626    $this->imap->set_options($options);
[b62a0d2]627
[197601e]628    // set global object for backward compatibility
629    $GLOBALS['IMAP'] = $this->imap;
[48bc52e]630
631    $hook = $this->plugins->exec_hook('imap_init', array('fetch_headers' => $this->imap->fetch_add_headers));
632    if ($hook['fetch_headers'])
633      $this->imap->fetch_add_headers = $hook['fetch_headers'];
[b62a0d2]634
[47d8d39]635    // support this parameter for backward compatibility but log warning
636    if ($connect) {
[1854c45]637      $this->imap_connect();
[13ffa28]638      raise_error(array(
639        'code' => 800, 'type' => 'imap',
640        'file' => __FILE__, 'line' => __LINE__,
641        'message' => "rcube::imap_init(true) is deprecated, use rcube::imap_connect() instead"),
642        true, false);
[47d8d39]643    }
[1854c45]644  }
645
646
647  /**
648   * Connect to IMAP server with stored session data
649   *
650   * @return bool True on success, false on error
651   */
652  public function imap_connect()
653  {
[48bc52e]654    if (!$this->imap)
655      $this->imap_init();
[b62a0d2]656
[59c216f]657    if ($_SESSION['imap_host'] && !$this->imap->conn->connected()) {
658      if (!$this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])) {
[1854c45]659        if ($this->output)
[0f0c17a]660          $this->output->show_message($this->imap->get_error_code() == -1 ? 'imaperror' : 'sessionerror', 'error');
[1854c45]661      }
[59c216f]662      else {
663        $this->set_imap_prop();
664        return $this->imap->conn;
665      }
[1854c45]666    }
667
[59c216f]668    return false;
[197601e]669  }
670
671
672  /**
[929a508]673   * Create session object and start the session.
674   */
675  public function session_init()
676  {
[bf67d60]677    // session started (Installer?)
678    if (session_id())
679      return;
680
[bd34cad]681    $sess_name   = $this->config->get('session_name');
682    $sess_domain = $this->config->get('session_domain');
683    $lifetime    = $this->config->get('session_lifetime', 0) * 60;
684
[929a508]685    // set session domain
[bd34cad]686    if ($sess_domain) {
687      ini_set('session.cookie_domain', $sess_domain);
[929a508]688    }
689    // set session garbage collecting time according to session_lifetime
690    if ($lifetime) {
691      ini_set('session.gc_maxlifetime', $lifetime * 2);
692    }
693
694    ini_set('session.cookie_secure', rcube_https_check());
[bd34cad]695    ini_set('session.name', $sess_name ? $sess_name : 'roundcube_sessid');
[929a508]696    ini_set('session.use_cookies', 1);
[b62a0d2]697    ini_set('session.use_only_cookies', 1);
[929a508]698    ini_set('session.serialize_handler', 'php');
699
700    // use database for storing session data
[63e9927]701    $this->session = new rcube_session($this->get_dbh(), $this->config);
[929a508]702
703    $this->session->register_gc_handler('rcmail_temp_gc');
704    if ($this->config->get('enable_caching'))
705      $this->session->register_gc_handler('rcmail_cache_gc');
706
707    // start PHP session (if not in CLI mode)
708    if ($_SERVER['REMOTE_ADDR'])
709      session_start();
710
711    // set initial session vars
[cf2da2f]712    if (!$_SESSION['user_id'])
[929a508]713      $_SESSION['temp'] = true;
714  }
715
716
717  /**
718   * Configure session object internals
719   */
720  public function session_configure()
721  {
[bf67d60]722    if (!$this->session)
723      return;
724
[929a508]725    $lifetime = $this->config->get('session_lifetime', 0) * 60;
726
727    // set keep-alive/check-recent interval
728    if ($keep_alive = $this->config->get('keep_alive')) {
729      // be sure that it's less than session lifetime
730      if ($lifetime)
731        $keep_alive = min($keep_alive, $lifetime - 30);
732      $keep_alive = max(60, $keep_alive);
733      $this->session->set_keep_alive($keep_alive);
734    }
[f537504]735
[cf2da2f]736    $this->session->set_secret($this->config->get('des_key') . $_SERVER['HTTP_USER_AGENT']);
737    $this->session->set_ip_check($this->config->get('ip_check'));
[929a508]738  }
739
740
741  /**
[197601e]742   * Perfom login to the IMAP server and to the webmail service.
743   * This will also create a new user entry if auto_create_user is configured.
744   *
745   * @param string IMAP user name
746   * @param string IMAP password
747   * @param string IMAP host
748   * @return boolean True on success, False on failure
749   */
750  function login($username, $pass, $host=NULL)
751  {
752    $user = NULL;
753    $config = $this->config->all();
754
755    if (!$host)
756      $host = $config['default_host'];
757
758    // Validate that selected host is in the list of configured hosts
759    if (is_array($config['default_host'])) {
760      $allowed = false;
761      foreach ($config['default_host'] as $key => $host_allowed) {
762        if (!is_numeric($key))
763          $host_allowed = $key;
764        if ($host == $host_allowed) {
765          $allowed = true;
766          break;
767        }
768      }
769      if (!$allowed)
770        return false;
771      }
[bb8721aa]772    else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
[197601e]773      return false;
774
775    // parse $host URL
776    $a_host = parse_url($host);
777    if ($a_host['host']) {
778      $host = $a_host['host'];
779      $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
[e999919]780      if (!empty($a_host['port']))
[f86e8f5f]781        $imap_port = $a_host['port'];
[9048094]782      else if ($imap_ssl && $imap_ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
[f86e8f5f]783        $imap_port = 993;
[197601e]784    }
[b62a0d2]785
[f86e8f5f]786    $imap_port = $imap_port ? $imap_port : $config['default_port'];
[197601e]787
[b62a0d2]788    /* Modify username with domain if required
[197601e]789       Inspired by Marco <P0L0_notspam_binware.org>
790    */
791    // Check if we need to add domain
[c16fab1]792    if (!empty($config['username_domain']) && strpos($username, '@') === false) {
[197601e]793      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
[a76cbdd]794        $username .= '@'.rcube_parse_host($config['username_domain'][$host], $host);
[197601e]795      else if (is_string($config['username_domain']))
[a76cbdd]796        $username .= '@'.rcube_parse_host($config['username_domain'], $host);
[197601e]797    }
798
[e17553d]799    // Convert username to lowercase. If IMAP backend
800    // is case-insensitive we need to store always the same username (#1487113)
801    if ($config['login_lc']) {
802      $username = mb_strtolower($username);
803    }
804
[94206996]805    // try to resolve email address from virtuser table
[e17553d]806    if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
807      $username = $virtuser;
808    }
[197601e]809
[f1adbf17]810    // Here we need IDNA ASCII
811    // Only rcube_contacts class is using domain names in Unicode
[e8d5bdc]812    $host = rcube_idn_to_ascii($host);
[f1adbf17]813    if (strpos($username, '@')) {
[8f94b1a]814      // lowercase domain name
815      list($local, $domain) = explode('@', $username);
816      $username = $local . '@' . mb_strtolower($domain);
[e8d5bdc]817      $username = rcube_idn_to_ascii($username);
[f1adbf17]818    }
819
[197601e]820    // user already registered -> overwrite username
821    if ($user = rcube_user::query($username, $host))
822      $username = $user->data['username'];
823
[48bc52e]824    if (!$this->imap)
825      $this->imap_init();
826
[6d94ab3]827    // try IMAP login
828    if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl))) {
[f1adbf17]829      // try with lowercase
[6d94ab3]830      $username_lc = mb_strtolower($username);
[e17553d]831      if ($username_lc != $username) {
832        // try to find user record again -> overwrite username
833        if (!$user && ($user = rcube_user::query($username_lc, $host)))
834          $username_lc = $user->data['username'];
835
836        if ($imap_login = $this->imap->connect($host, $username_lc, $pass, $imap_port, $imap_ssl))
837          $username = $username_lc;
838      }
[6d94ab3]839    }
840
[197601e]841    // exit if IMAP login failed
[6d94ab3]842    if (!$imap_login)
[197601e]843      return false;
844
845    // user already registered -> update user's record
846    if (is_object($user)) {
[d08333e]847      // update last login timestamp
[197601e]848      $user->touch();
849    }
850    // create new system user
851    else if ($config['auto_create_user']) {
852      if ($created = rcube_user::create($username, $host)) {
853        $user = $created;
854      }
[f879f4e]855      else {
856        raise_error(array(
[782d859]857          'code' => 620, 'type' => 'php',
[6d94ab3]858          'file' => __FILE__, 'line' => __LINE__,
[f879f4e]859          'message' => "Failed to create a user record. Maybe aborted by a plugin?"
[10eedbe]860          ), true, false);
[f879f4e]861      }
[197601e]862    }
863    else {
864      raise_error(array(
[782d859]865        'code' => 621, 'type' => 'php',
[10eedbe]866        'file' => __FILE__, 'line' => __LINE__,
[782d859]867        'message' => "Access denied for new user $username. 'auto_create_user' is disabled"
[197601e]868        ), true, false);
869    }
870
871    // login succeeded
872    if (is_object($user) && $user->ID) {
[f537504]873      // Configure environment
[197601e]874      $this->set_user($user);
[f537504]875      $this->set_imap_prop();
[88ca38a]876      $this->session_configure();
[197601e]877
[f537504]878      // fix some old settings according to namespace prefix
879      $this->fix_namespace_settings($user);
880
881      // create default folders on first login
882      if ($config['create_default_folders'] && (!empty($created) || empty($user->data['last_login']))) {
883        $this->imap->create_default_folders();
884      }
885
[197601e]886      // set session vars
887      $_SESSION['user_id']   = $user->ID;
888      $_SESSION['username']  = $user->data['username'];
889      $_SESSION['imap_host'] = $host;
890      $_SESSION['imap_port'] = $imap_port;
891      $_SESSION['imap_ssl']  = $imap_ssl;
[2471d3a]892      $_SESSION['password']  = $this->encrypt($pass);
[197601e]893      $_SESSION['login_time'] = mktime();
[f537504]894
[b62a0d2]895      if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
[c8ae249]896        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
[65082b3]897      if (isset($_REQUEST['_dstactive']) && $_REQUEST['_dstactive'] != '_default_')
898        $_SESSION['dst_active'] = intval($_REQUEST['_dstactive']);
[197601e]899
900      // force reloading complete list of subscribed mailboxes
[ccc059f]901      $this->imap->clear_cache('mailboxes', true);
[197601e]902
903      return true;
904    }
905
906    return false;
907  }
908
909
910  /**
911   * Set root dir and last stored mailbox
912   * This must be done AFTER connecting to the server!
913   */
914  public function set_imap_prop()
915  {
916    $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
917
918    if ($default_folders = $this->config->get('default_imap_folders')) {
919      $this->imap->set_default_mailboxes($default_folders);
920    }
[4484097]921    if (isset($_SESSION['mbox'])) {
[197601e]922      $this->imap->set_mailbox($_SESSION['mbox']);
923    }
924    if (isset($_SESSION['page'])) {
925      $this->imap->set_page($_SESSION['page']);
926    }
927  }
928
[1854c45]929
930  /**
931   * Auto-select IMAP host based on the posted login information
932   *
933   * @return string Selected IMAP host
934   */
935  public function autoselect_host()
936  {
937    $default_host = $this->config->get('default_host');
[257f88c]938    $host = null;
[b62a0d2]939
[257f88c]940    if (is_array($default_host)) {
941      $post_host = get_input_value('_host', RCUBE_INPUT_POST);
[b62a0d2]942
[257f88c]943      // direct match in default_host array
944      if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
945        $host = $post_host;
946      }
[b62a0d2]947
[257f88c]948      // try to select host by mail domain
[1854c45]949      list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
950      if (!empty($domain)) {
[257f88c]951        foreach ($default_host as $imap_host => $mail_domains) {
[1854c45]952          if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
953            $host = $imap_host;
954            break;
955          }
956        }
957      }
958
959      // take the first entry if $host is still an array
[257f88c]960      if (empty($host)) {
961        $host = array_shift($default_host);
962      }
963    }
964    else if (empty($default_host)) {
965      $host = get_input_value('_host', RCUBE_INPUT_POST);
[1854c45]966    }
[eec34ef]967    else
[bb8721aa]968      $host = rcube_parse_host($default_host);
[1854c45]969
970    return $host;
971  }
972
973
974  /**
975   * Get localized text in the desired language
976   *
[8703b08]977   * @param mixed   $attrib  Named parameters array or label name
978   * @param string  $domain  Label domain (plugin) name
979   *
[1854c45]980   * @return string Localized text
981   */
[cc97ea0]982  public function gettext($attrib, $domain=null)
[1854c45]983  {
984    // load localization files if not done yet
985    if (empty($this->texts))
986      $this->load_language();
[b62a0d2]987
[1854c45]988    // extract attributes
989    if (is_string($attrib))
990      $attrib = array('name' => $attrib);
991
992    $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
[9898fe3]993    $name = $attrib['name'] ? $attrib['name'] : '';
[8703b08]994
[ae39c47]995    // attrib contain text values: use them from now
996    if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us']))
997        $this->texts[$name] = $setval;
[1854c45]998
[cc97ea0]999    // check for text with domain
[9898fe3]1000    if ($domain && ($text_item = $this->texts[$domain.'.'.$name]))
[cc97ea0]1001      ;
[1854c45]1002    // text does not exist
[9898fe3]1003    else if (!($text_item = $this->texts[$name])) {
1004      return "[$name]";
[1854c45]1005    }
1006
[b62a0d2]1007    // make text item array
[1854c45]1008    $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
1009
1010    // decide which text to use
1011    if ($nr == 1) {
1012      $text = $a_text_item['single'];
1013    }
1014    else if ($nr > 0) {
1015      $text = $a_text_item['multiple'];
1016    }
1017    else if ($nr == 0) {
1018      if ($a_text_item['none'])
1019        $text = $a_text_item['none'];
1020      else if ($a_text_item['single'])
1021        $text = $a_text_item['single'];
1022      else if ($a_text_item['multiple'])
1023        $text = $a_text_item['multiple'];
1024    }
1025
1026    // default text is single
1027    if ($text == '') {
1028      $text = $a_text_item['single'];
1029    }
1030
1031    // replace vars in text
1032    if (is_array($attrib['vars'])) {
1033      foreach ($attrib['vars'] as $var_key => $var_value)
[9898fe3]1034        $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
[1854c45]1035    }
1036
1037    // format output
1038    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
1039      return ucfirst($text);
1040    else if ($attrib['uppercase'])
[2aa2b33]1041      return mb_strtoupper($text);
[1854c45]1042    else if ($attrib['lowercase'])
[2aa2b33]1043      return mb_strtolower($text);
[1854c45]1044
1045    return $text;
1046  }
1047
1048
1049  /**
[8703b08]1050   * Check if the given text label exists
1051   *
1052   * @param string  $name       Label name
1053   * @param string  $domain     Label domain (plugin) name or '*' for all domains
1054   * @param string  $ref_domain Sets domain name if label is found
[07b95dc]1055   *
1056   * @return boolean True if text exists (either in the current language or in en_US)
1057   */
[8703b08]1058  public function text_exists($name, $domain = null, &$ref_domain = null)
[07b95dc]1059  {
1060    // load localization files if not done yet
1061    if (empty($this->texts))
1062      $this->load_language();
1063
[8703b08]1064    if (isset($this->texts[$name])) {
1065        $ref_domain = '';
1066        return true;
1067    }
1068
1069    // any of loaded domains (plugins)
1070    if ($domain == '*') {
1071      foreach ($this->plugins->loaded_plugins() as $domain)
1072        if (isset($this->texts[$domain.'.'.$name])) {
1073          $ref_domain = $domain;
1074          return true;
1075        }
1076    }
1077    // specified domain
1078    else if ($domain) {
1079      $ref_domain = $domain;
1080      return isset($this->texts[$domain.'.'.$name]);
1081    }
1082
1083    return false;
[07b95dc]1084  }
1085
1086  /**
[1854c45]1087   * Load a localization package
1088   *
1089   * @param string Language ID
1090   */
[cc97ea0]1091  public function load_language($lang = null, $add = array())
[1854c45]1092  {
[c8ae249]1093    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
[b62a0d2]1094
[1854c45]1095    // load localized texts
1096    if (empty($this->texts) || $lang != $_SESSION['language']) {
1097      $this->texts = array();
1098
[7c9850d]1099      // handle empty lines after closing PHP tag in localization files
1100      ob_start();
1101
[1854c45]1102      // get english labels (these should be complete)
1103      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
1104      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
1105
1106      if (is_array($labels))
[9d9f8dc]1107        $this->texts = $labels;
[1854c45]1108      if (is_array($messages))
[9d9f8dc]1109        $this->texts = array_merge($this->texts, $messages);
[1854c45]1110
1111      // include user language files
1112      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
1113        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
1114        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
1115
1116        if (is_array($labels))
1117          $this->texts = array_merge($this->texts, $labels);
1118        if (is_array($messages))
1119          $this->texts = array_merge($this->texts, $messages);
1120      }
[b62a0d2]1121
[7c9850d]1122      ob_end_clean();
1123
[1854c45]1124      $_SESSION['language'] = $lang;
1125    }
[cc97ea0]1126
1127    // append additional texts (from plugin)
1128    if (is_array($add) && !empty($add))
1129      $this->texts += $add;
[1854c45]1130  }
1131
1132
1133  /**
1134   * Read directory program/localization and return a list of available languages
1135   *
1136   * @return array List of available localizations
1137   */
1138  public function list_languages()
1139  {
1140    static $sa_languages = array();
1141
1142    if (!sizeof($sa_languages)) {
1143      @include(INSTALL_PATH . 'program/localization/index.inc');
1144
1145      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
1146        while (($name = readdir($dh)) !== false) {
[2aa2b33]1147          if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
[1854c45]1148            continue;
1149
1150          if ($label = $rcube_languages[$name])
[7d51781]1151            $sa_languages[$name] = $label;
[1854c45]1152        }
1153        closedir($dh);
1154      }
1155    }
1156
1157    return $sa_languages;
1158  }
1159
1160
1161  /**
1162   * Destroy session data and remove cookie
1163   */
1164  public function kill_session()
1165  {
[e6ce006]1166    $this->plugins->exec_hook('session_destroy');
[b62a0d2]1167
[cf2da2f]1168    $this->session->kill();
1169    $_SESSION = array('language' => $this->user->language, 'temp' => true);
[1854c45]1170    $this->user->reset();
1171  }
1172
1173
1174  /**
1175   * Do server side actions on logout
1176   */
1177  public function logout_actions()
1178  {
1179    $config = $this->config->all();
[b62a0d2]1180
1181    // on logout action we're not connected to imap server
[1854c45]1182    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
[cf2da2f]1183      if (!$this->session->check_auth())
[1854c45]1184        return;
1185
[47d8d39]1186      $this->imap_connect();
[1854c45]1187    }
1188
1189    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1190      $this->imap->clear_mailbox($config['trash_mbox']);
1191    }
1192
1193    if ($config['logout_expunge']) {
1194      $this->imap->expunge('INBOX');
1195    }
[40a1860]1196
1197    // Try to save unsaved user preferences
1198    if (!empty($_SESSION['preferences'])) {
1199      $this->user->save_prefs(unserialize($_SESSION['preferences']));
1200    }
[1854c45]1201  }
1202
1203
1204  /**
1205   * Function to be executed in script shutdown
1206   * Registered with register_shutdown_function()
1207   */
[197601e]1208  public function shutdown()
1209  {
[580adc8]1210    foreach ($this->shutdown_functions as $function)
1211      call_user_func($function);
1212
[2c3d81d]1213    if (is_object($this->smtp))
1214      $this->smtp->disconnect();
1215
[0501b63]1216    foreach ($this->address_books as $book) {
[9a835c7]1217      if (is_object($book) && is_a($book, 'rcube_addressbook'))
[457373b]1218        $book->close();
[0501b63]1219    }
[197601e]1220
[5cf5ee6]1221    foreach ($this->caches as $cache) {
1222        if (is_object($cache))
1223            $cache->close();
1224    }
1225
[dd07e79]1226    if (is_object($this->imap))
1227      $this->imap->close();
1228
[197601e]1229    // before closing the database connection, write session data
[609c5e9]1230    if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
[4591de7]1231      $this->session->cleanup();
[75da0b6]1232      session_write_close();
[4591de7]1233    }
[2b35c5d]1234
1235    // write performance stats to logs/console
1236    if ($this->config->get('devel_mode')) {
1237      if (function_exists('memory_get_usage'))
1238        $mem = show_bytes(memory_get_usage());
1239      if (function_exists('memory_get_peak_usage'))
1240        $mem .= '/'.show_bytes(memory_get_peak_usage());
1241
1242      $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
[bf67d60]1243      if (defined('RCMAIL_START'))
1244        rcube_print_time(RCMAIL_START, $log);
1245      else
1246        console($log);
[2b35c5d]1247    }
[197601e]1248  }
[b62a0d2]1249
1250
[1854c45]1251  /**
[580adc8]1252   * Registers shutdown function to be executed on shutdown.
1253   * The functions will be executed before destroying any
1254   * objects like smtp, imap, session, etc.
1255   *
1256   * @param callback Function callback
1257   */
1258  public function add_shutdown_function($function)
1259  {
1260    $this->shutdown_functions[] = $function;
1261  }
1262
1263
1264  /**
[57f0c81]1265   * Generate a unique token to be used in a form request
1266   *
1267   * @return string The request token
1268   */
[5499336]1269  public function get_request_token()
[57f0c81]1270  {
[ec045b0]1271    $sess_id = $_COOKIE[ini_get('session.name')];
[c9f2c47]1272    if (!$sess_id) $sess_id = session_id();
[abdf314]1273    $plugin = $this->plugins->exec_hook('request_token', array('value' => md5('RT' . $this->user->ID . $this->config->get('des_key') . $sess_id)));
[ef27a6a]1274    return $plugin['value'];
[57f0c81]1275  }
[b62a0d2]1276
1277
[57f0c81]1278  /**
1279   * Check if the current request contains a valid token
1280   *
[5499336]1281   * @param int Request method
[57f0c81]1282   * @return boolean True if request token is valid false if not
1283   */
[5499336]1284  public function check_request($mode = RCUBE_INPUT_POST)
[57f0c81]1285  {
1286    $token = get_input_value('_token', $mode);
[ec045b0]1287    $sess_id = $_COOKIE[ini_get('session.name')];
1288    return !empty($sess_id) && $token == $this->get_request_token();
[57f0c81]1289  }
[b62a0d2]1290
1291
[57f0c81]1292  /**
[1854c45]1293   * Create unique authorization hash
1294   *
1295   * @param string Session ID
1296   * @param int Timestamp
1297   * @return string The generated auth hash
1298   */
1299  private function get_auth_hash($sess_id, $ts)
1300  {
1301    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1302      $sess_id,
1303      $ts,
1304      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1305      $_SERVER['HTTP_USER_AGENT']);
1306
1307    if (function_exists('sha1'))
1308      return sha1($auth_string);
1309    else
1310      return md5($auth_string);
1311  }
1312
[2471d3a]1313
[1854c45]1314  /**
[2471d3a]1315   * Encrypt using 3DES
1316   *
1317   * @param string $clear clear text input
1318   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1319   * @param boolean $base64 whether or not to base64_encode() the result before returning
[1854c45]1320   *
[2471d3a]1321   * @return string encrypted text
[1854c45]1322   */
[2471d3a]1323  public function encrypt($clear, $key = 'des_key', $base64 = true)
[1854c45]1324  {
[713a66fc]1325    if (!$clear)
1326      return '';
[2471d3a]1327    /*-
1328     * Add a single canary byte to the end of the clear text, which
1329     * will help find out how much of padding will need to be removed
1330     * upon decryption; see http://php.net/mcrypt_generic#68082
1331     */
1332    $clear = pack("a*H2", $clear, "80");
[b62a0d2]1333
[2471d3a]1334    if (function_exists('mcrypt_module_open') &&
1335        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1336    {
[564741f]1337      $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
[2471d3a]1338      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1339      $cipher = $iv . mcrypt_generic($td, $clear);
[1854c45]1340      mcrypt_generic_deinit($td);
1341      mcrypt_module_close($td);
1342    }
[44155cd]1343    else {
[926948e]1344      @include_once 'des.inc';
[44155cd]1345
1346      if (function_exists('des')) {
1347        $des_iv_size = 8;
[564741f]1348        $iv = $this->create_iv($des_iv_size);
[44155cd]1349        $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
1350      }
1351      else {
1352        raise_error(array(
1353          'code' => 500, 'type' => 'php',
1354          'file' => __FILE__, 'line' => __LINE__,
1355          'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1356        ), true, true);
1357      }
[1854c45]1358    }
[44155cd]1359
[2471d3a]1360    return $base64 ? base64_encode($cipher) : $cipher;
[1854c45]1361  }
1362
1363  /**
[2471d3a]1364   * Decrypt 3DES-encrypted string
1365   *
1366   * @param string $cipher encrypted text
1367   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1368   * @param boolean $base64 whether or not input is base64-encoded
[1854c45]1369   *
[2471d3a]1370   * @return string decrypted text
[1854c45]1371   */
[2471d3a]1372  public function decrypt($cipher, $key = 'des_key', $base64 = true)
[1854c45]1373  {
[713a66fc]1374    if (!$cipher)
1375      return '';
[b62a0d2]1376
[2471d3a]1377    $cipher = $base64 ? base64_decode($cipher) : $cipher;
1378
1379    if (function_exists('mcrypt_module_open') &&
1380        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1381    {
[9016a84]1382      $iv_size = mcrypt_enc_get_iv_size($td);
1383      $iv = substr($cipher, 0, $iv_size);
1384
1385      // session corruption? (#1485970)
1386      if (strlen($iv) < $iv_size)
1387        return '';
1388
1389      $cipher = substr($cipher, $iv_size);
[2471d3a]1390      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1391      $clear = mdecrypt_generic($td, $cipher);
[1854c45]1392      mcrypt_generic_deinit($td);
1393      mcrypt_module_close($td);
1394    }
[44155cd]1395    else {
[926948e]1396      @include_once 'des.inc';
[b62a0d2]1397
[44155cd]1398      if (function_exists('des')) {
1399        $des_iv_size = 8;
1400        $iv = substr($cipher, 0, $des_iv_size);
1401        $cipher = substr($cipher, $des_iv_size);
1402        $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1403      }
1404      else {
1405        raise_error(array(
1406          'code' => 500, 'type' => 'php',
1407          'file' => __FILE__, 'line' => __LINE__,
1408          'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1409        ), true, true);
1410      }
[1854c45]1411    }
[44155cd]1412
[2471d3a]1413    /*-
1414     * Trim PHP's padding and the canary byte; see note in
1415     * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1416     */
1417    $clear = substr(rtrim($clear, "\0"), 0, -1);
[b62a0d2]1418
[2471d3a]1419    return $clear;
[1854c45]1420  }
1421
[c719f3c]1422  /**
[564741f]1423   * Generates encryption initialization vector (IV)
1424   *
1425   * @param int Vector size
1426   * @return string Vector string
1427   */
1428  private function create_iv($size)
1429  {
1430    // mcrypt_create_iv() can be slow when system lacks entrophy
1431    // we'll generate IV vector manually
1432    $iv = '';
1433    for ($i = 0; $i < $size; $i++)
1434        $iv .= chr(mt_rand(0, 255));
1435    return $iv;
1436  }
1437
1438  /**
[e019f2d]1439   * Build a valid URL to this instance of Roundcube
[c719f3c]1440   *
1441   * @param mixed Either a string with the action or url parameters as key-value pairs
1442   * @return string Valid application URL
1443   */
1444  public function url($p)
1445  {
1446    if (!is_array($p))
[fde466c]1447      $p = array('_action' => @func_get_arg(0));
[b62a0d2]1448
[1c932d5]1449    $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
[cc97ea0]1450    $p['_task'] = $task;
[1038a66e]1451    unset($p['task']);
1452
[cf17773]1453    $url = './';
1454    $delm = '?';
[77406bb]1455    foreach (array_reverse($p) as $key => $val) {
1456      if ($val !== '') {
[cc97ea0]1457        $par = $key[0] == '_' ? $key : '_'.$key;
[cf17773]1458        $url .= $delm.urlencode($par).'='.urlencode($val);
1459        $delm = '&';
1460      }
1461    }
[c719f3c]1462    return $url;
1463  }
[cefd1d8]1464
1465
1466  /**
[0501b63]1467   * Use imagemagick or GD lib to read image properties
1468   *
1469   * @param string Absolute file path
1470   * @return mixed Hash array with image props like type, width, height or False on error
1471   */
1472  public static function imageprops($filepath)
1473  {
1474    $rcmail = rcmail::get_instance();
1475    if ($cmd = $rcmail->config->get('im_identify_path', false)) {
1476      list(, $type, $size) = explode(' ', strtolower(rcmail::exec($cmd. ' 2>/dev/null {in}', array('in' => $filepath))));
1477      if ($size)
1478        list($width, $height) = explode('x', $size);
1479    }
1480    else if (function_exists('getimagesize')) {
1481      $imsize = @getimagesize($filepath);
1482      $width = $imsize[0];
1483      $height = $imsize[1];
1484      $type = preg_replace('!image/!', '', $imsize['mime']);
1485    }
1486
1487    return $type ? array('type' => $type, 'width' => $width, 'height' => $height) : false;
1488  }
1489
1490
1491  /**
1492   * Convert an image to a given size and type using imagemagick (ensures input is an image)
1493   *
1494   * @param $p['in']  Input filename (mandatory)
1495   * @param $p['out'] Output filename (mandatory)
1496   * @param $p['size']  Width x height of resulting image, e.g. "160x60"
1497   * @param $p['type']  Output file type, e.g. "jpg"
1498   * @param $p['-opts'] Custom command line options to ImageMagick convert
1499   * @return Success of convert as true/false
1500   */
1501  public static function imageconvert($p)
1502  {
1503    $result = false;
1504    $rcmail = rcmail::get_instance();
1505    $convert  = $rcmail->config->get('im_convert_path', false);
1506    $identify = $rcmail->config->get('im_identify_path', false);
[4351f7c]1507
[0501b63]1508    // imagemagick is required for this
1509    if (!$convert)
1510        return false;
1511
1512    if (!(($imagetype = @exif_imagetype($p['in'])) && ($type = image_type_to_extension($imagetype, false))))
1513      list(, $type) = explode(' ', strtolower(rcmail::exec($identify . ' 2>/dev/null {in}', $p))); # for things like eps
1514
1515    $type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
1516    $p += array('type' => $type, 'types' => "bmp,eps,gif,jp2,jpg,png,svg,tif", 'quality' => 75);
1517    $p['-opts'] = array('-resize' => $p['size'].'>') + (array)$p['-opts'];
1518
1519    if (in_array($type, explode(',', $p['types']))) # Valid type?
1520      $result = rcmail::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace RGB -quality {quality} {-opts} {in} {type}:{out}', $p) === "";
1521
1522    return $result;
1523  }
1524
1525
1526  /**
1527   * Construct shell command, execute it and return output as string.
1528   * Keywords {keyword} are replaced with arguments
1529   *
1530   * @param $cmd Format string with {keywords} to be replaced
1531   * @param $values (zero, one or more arrays can be passed)
1532   * @return output of command. shell errors not detectable
1533   */
1534  public static function exec(/* $cmd, $values1 = array(), ... */)
1535  {
1536    $args = func_get_args();
1537    $cmd = array_shift($args);
1538    $values = $replacements = array();
1539
1540    // merge values into one array
1541    foreach ($args as $arg)
1542      $values += (array)$arg;
1543
1544    preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
1545    foreach ($matches as $tags) {
1546      list(, $tag, $option, $key) = $tags;
1547      $parts = array();
1548
1549      if ($option) {
1550        foreach ((array)$values["-$key"] as $key => $value) {
1551          if ($value === true || $value === false || $value === null)
1552            $parts[] = $value ? $key : "";
1553          else foreach ((array)$value as $val)
1554            $parts[] = "$key " . escapeshellarg($val);
1555        }
1556      }
1557      else {
1558        foreach ((array)$values[$key] as $value)
1559          $parts[] = escapeshellarg($value);
1560      }
1561
1562      $replacements[$tag] = join(" ", $parts);
1563    }
1564
1565    // use strtr behaviour of going through source string once
1566    $cmd = strtr($cmd, $replacements);
[f537504]1567
[0501b63]1568    return (string)shell_exec($cmd);
1569  }
1570
1571
1572  /**
[cefd1d8]1573   * Helper method to set a cookie with the current path and host settings
1574   *
1575   * @param string Cookie name
1576   * @param string Cookie value
1577   * @param string Expiration time
1578   */
1579  public static function setcookie($name, $value, $exp = 0)
1580  {
[317a7d9]1581    if (headers_sent())
1582      return;
1583
[cefd1d8]1584    $cookie = session_get_cookie_params();
[2273d41]1585
[cefd1d8]1586    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
[c96c5a9]1587      rcube_https_check(), true);
[cefd1d8]1588  }
[197601e]1589
[68d2d54]1590  /**
1591   * Registers action aliases for current task
1592   *
1593   * @param array $map Alias-to-filename hash array
1594   */
1595  public function register_action_map($map)
1596  {
1597    if (is_array($map)) {
1598      foreach ($map as $idx => $val) {
1599        $this->action_map[$idx] = $val;
1600      }
1601    }
1602  }
[f537504]1603
[68d2d54]1604  /**
1605   * Returns current action filename
1606   *
1607   * @param array $map Alias-to-filename hash array
1608   */
1609  public function get_action_file()
1610  {
1611    if (!empty($this->action_map[$this->action])) {
1612      return $this->action_map[$this->action];
1613    }
1614
1615    return strtr($this->action, '-', '_') . '.inc';
1616  }
[197601e]1617
[d08333e]1618  /**
1619   * Fixes some user preferences according to namespace handling change.
1620   * Old Roundcube versions were using folder names with removed namespace prefix.
1621   * Now we need to add the prefix on servers where personal namespace has prefix.
1622   *
1623   * @param rcube_user $user User object
1624   */
1625  private function fix_namespace_settings($user)
1626  {
1627    $prefix     = $this->imap->get_namespace('prefix');
1628    $prefix_len = strlen($prefix);
1629
1630    if (!$prefix_len)
1631      return;
1632
[f537504]1633    $prefs = $this->config->all();
1634    if (!empty($prefs['namespace_fixed']))
[d08333e]1635      return;
1636
1637    // Build namespace prefix regexp
1638    $ns     = $this->imap->get_namespace();
1639    $regexp = array();
1640
1641    foreach ($ns as $entry) {
1642      if (!empty($entry)) {
1643        foreach ($entry as $item) {
1644          if (strlen($item[0])) {
1645            $regexp[] = preg_quote($item[0], '/');
1646          }
1647        }
1648      }
1649    }
1650    $regexp = '/^('. implode('|', $regexp).')/';
1651
1652    // Fix preferences
1653    $opts = array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox', 'archive_mbox');
1654    foreach ($opts as $opt) {
1655      if ($value = $prefs[$opt]) {
1656        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1657          $prefs[$opt] = $prefix.$value;
1658        }
1659      }
1660    }
1661
1662    if (!empty($prefs['default_imap_folders'])) {
1663      foreach ($prefs['default_imap_folders'] as $idx => $name) {
1664        if ($name != 'INBOX' && !preg_match($regexp, $name)) {
1665          $prefs['default_imap_folders'][$idx] = $prefix.$name;
1666        }
1667      }
1668    }
1669
1670    if (!empty($prefs['search_mods'])) {
1671      $folders = array();
1672      foreach ($prefs['search_mods'] as $idx => $value) {
1673        if ($idx != 'INBOX' && $idx != '*' && !preg_match($regexp, $idx)) {
1674          $idx = $prefix.$idx;
1675        }
1676        $folders[$idx] = $value;
1677      }
1678      $prefs['search_mods'] = $folders;
1679    }
1680
1681    if (!empty($prefs['message_threading'])) {
1682      $folders = array();
1683      foreach ($prefs['message_threading'] as $idx => $value) {
1684        if ($idx != 'INBOX' && !preg_match($regexp, $idx)) {
1685          $idx = $prefix.$idx;
1686        }
1687        $folders[$prefix.$idx] = $value;
1688      }
1689      $prefs['message_threading'] = $folders;
1690    }
1691
1692    if (!empty($prefs['collapsed_folders'])) {
1693      $folders     = explode('&&', $prefs['collapsed_folders']);
1694      $count       = count($folders);
1695      $folders_str = '';
1696
1697      if ($count) {
1698          $folders[0]        = substr($folders[0], 1);
1699          $folders[$count-1] = substr($folders[$count-1], 0, -1);
1700      }
1701
1702      foreach ($folders as $value) {
1703        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1704          $value = $prefix.$value;
1705        }
1706        $folders_str .= '&'.$value.'&';
1707      }
1708      $prefs['collapsed_folders'] = $folders_str;
1709    }
1710
1711    $prefs['namespace_fixed'] = true;
1712
1713    // save updated preferences and reset imap settings (default folders)
1714    $user->save_prefs($prefs);
1715    $this->set_imap_prop();
1716  }
1717
[68d2d54]1718}
Note: See TracBrowser for help on using the repository browser.