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

HEADcourier-fixdev-browser-capabilitiespdorelease-0.8
Last change on this file since fec2d8e was fec2d8e, checked in by thomascube <thomas@…>, 15 months ago

Refactored IMAP cache expunge: delegate to storage object; don't rely on deprecated 'enable_caching' config option

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