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