thomascube
2010-12-17 db1a87cd6c506f2afbd1a37c64cb56ae11120b49
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                     |
A 8  | Copyright (C) 2008-2010, Roundcube Dev. - Switzerland                 |
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;
457373 117   private $books = array();
677e1f 118
A 119
197601 120   /**
T 121    * This implements the 'singleton' design pattern
122    *
5c461b 123    * @return rcmail The one and only instance
197601 124    */
T 125   static function get_instance()
126   {
127     if (!self::$instance) {
128       self::$instance = new rcmail();
129       self::$instance->startup();  // init AFTER object was linked with self::$instance
130     }
131
132     return self::$instance;
133   }
b62a0d 134
A 135
197601 136   /**
T 137    * Private constructor
138    */
139   private function __construct()
140   {
141     // load configuration
142     $this->config = new rcube_config();
b62a0d 143
197601 144     register_shutdown_function(array($this, 'shutdown'));
T 145   }
b62a0d 146
A 147
197601 148   /**
T 149    * Initial startup function
150    * to register session, create database and imap connections
151    *
152    * @todo Remove global vars $DB, $USER
153    */
154   private function startup()
155   {
b77d0d 156     // initialize syslog
A 157     if ($this->config->get('log_driver') == 'syslog') {
158       $syslog_id = $this->config->get('syslog_id', 'roundcube');
159       $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
160       openlog($syslog_id, LOG_ODELAY, $syslog_facility);
161     }
cc97ea 162
197601 163     // connect to database
T 164     $GLOBALS['DB'] = $this->get_dbh();
165
929a50 166     // start session
A 167     $this->session_init();
197601 168
T 169     // create user object
170     $this->set_user(new rcube_user($_SESSION['user_id']));
929a50 171
A 172     // configure session (after user config merge!)
173     $this->session_configure();
197601 174
9b94eb 175     // set task and action properties
A 176     $this->set_task(get_input_value('_task', RCUBE_INPUT_GPC));
177     $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
178
197601 179     // reset some session parameters when changing task
677e1f 180     if ($this->task != 'utils') {
A 181       if ($this->session && $_SESSION['task'] != $this->task)
182         $this->session->remove('page');
183       // set current task to session
184       $_SESSION['task'] = $this->task;
185     }
197601 186
48bc52 187     // init output class
A 188     if (!empty($_REQUEST['_remote']))
929a50 189       $GLOBALS['OUTPUT'] = $this->json_init();
48bc52 190     else
A 191       $GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
192
cc97ea 193     // create plugin API and load plugins
T 194     $this->plugins = rcube_plugin_api::get_instance();
48bc52 195
A 196     // init plugins
197     $this->plugins->init();
197601 198   }
b62a0d 199
A 200
197601 201   /**
T 202    * Setter for application task
203    *
204    * @param string Task to set
205    */
206   public function set_task($task)
207   {
1c932d 208     $task = asciiwords($task);
9b94eb 209
A 210     if ($this->user && $this->user->ID)
211       $task = !$task || $task == 'login' ? 'mail' : $task;
212     else
213       $task = 'login';
214
215     $this->task = $task;
1c932d 216     $this->comm_path = $this->url(array('task' => $this->task));
b62a0d 217
197601 218     if ($this->output)
1c932d 219       $this->output->set_env('task', $this->task);
197601 220   }
b62a0d 221
A 222
197601 223   /**
T 224    * Setter for system user object
225    *
5c461b 226    * @param rcube_user Current user instance
197601 227    */
T 228   public function set_user($user)
229   {
230     if (is_object($user)) {
231       $this->user = $user;
232       $GLOBALS['USER'] = $this->user;
b62a0d 233
197601 234       // overwrite config with user preferences
b545d3 235       $this->config->set_user_prefs((array)$this->user->get_prefs());
197601 236     }
b62a0d 237
c8ae24 238     $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
531abb 239
197601 240     // set localization
e80f50 241     setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
14de18 242
b62a0d 243     // workaround for http://bugs.php.net/bug.php?id=18556
A 244     if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
245       setlocale(LC_CTYPE, 'en_US' . '.utf8');
197601 246   }
b62a0d 247
A 248
197601 249   /**
T 250    * Check the given string and return a valid language code
251    *
252    * @param string Language code
253    * @return string Valid language code
254    */
255   private function language_prop($lang)
256   {
257     static $rcube_languages, $rcube_language_aliases;
b62a0d 258
c8ae24 259     // user HTTP_ACCEPT_LANGUAGE if no language is specified
T 260     if (empty($lang) || $lang == 'auto') {
261        $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
262        $lang = str_replace('-', '_', $accept_langs[0]);
263      }
b62a0d 264
197601 265     if (empty($rcube_languages)) {
T 266       @include(INSTALL_PATH . 'program/localization/index.inc');
267     }
b62a0d 268
197601 269     // check if we have an alias for that language
T 270     if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
271       $lang = $rcube_language_aliases[$lang];
272     }
273     // try the first two chars
c3ab75 274     else if (!isset($rcube_languages[$lang])) {
7e78b2 275       $short = substr($lang, 0, 2);
b62a0d 276
235086 277       // check if we have an alias for the short language code
T 278       if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
279         $lang = $rcube_language_aliases[$short];
280       }
c3ab75 281       // expand 'nn' to 'nn_NN'
T 282       else if (!isset($rcube_languages[$short])) {
235086 283         $lang = $short.'_'.strtoupper($short);
T 284       }
197601 285     }
T 286
1854c4 287     if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
197601 288       $lang = 'en_US';
T 289     }
290
291     return $lang;
292   }
b62a0d 293
A 294
197601 295   /**
T 296    * Get the current database connection
297    *
5c461b 298    * @return rcube_mdb2  Database connection object
197601 299    */
T 300   public function get_dbh()
301   {
302     if (!$this->db) {
303       $config_all = $this->config->all();
304
9e8e5f 305       $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
197601 306       $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
T 307       $this->db->set_debug((bool)$config_all['sql_debug']);
308     }
309
310     return $this->db;
311   }
b62a0d 312
A 313
197601 314   /**
ade8e1 315    * Return instance of the internal address book class
T 316    *
3704b7 317    * @param string  Address book identifier
ade8e1 318    * @param boolean True if the address book needs to be writeable
5c461b 319    * @return rcube_contacts Address book object
ade8e1 320    */
T 321   public function get_address_book($id, $writeable = false)
322   {
323     $contacts = null;
324     $ldap_config = (array)$this->config->get('ldap_public');
325     $abook_type = strtolower($this->config->get('address_book_type'));
cc97ea 326
e6ce00 327     $plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
b62a0d 328
cc97ea 329     // plugin returned instance of a rcube_addressbook
T 330     if ($plugin['instance'] instanceof rcube_addressbook) {
331       $contacts = $plugin['instance'];
332     }
333     else if ($id && $ldap_config[$id]) {
010274 334       $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
cc97ea 335     }
T 336     else if ($id === '0') {
337       $contacts = new rcube_contacts($this->db, $this->user->ID);
ade8e1 338     }
T 339     else if ($abook_type == 'ldap') {
340       // Use the first writable LDAP address book.
341       foreach ($ldap_config as $id => $prop) {
342         if (!$writeable || $prop['writable']) {
010274 343           $contacts = new rcube_ldap($prop, $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
ade8e1 344           break;
T 345         }
346       }
347     }
3704b7 348     else { // $id == 'sql'
ade8e1 349       $contacts = new rcube_contacts($this->db, $this->user->ID);
T 350     }
457373 351
A 352     // add to the 'books' array for shutdown function
353     if (!in_array($contacts, $this->books))
354       $this->books[] = $contacts;
b62a0d 355
ade8e1 356     return $contacts;
T 357   }
3704b7 358
A 359
360   /**
361    * Return address books list
362    *
363    * @param boolean True if the address book needs to be writeable
364    * @return array  Address books array
365    */
366   public function get_address_sources($writeable = false)
367   {
368     $abook_type = strtolower($this->config->get('address_book_type'));
7fdb9d 369     $ldap_config = $this->config->get('ldap_public');
A 370     $autocomplete = (array) $this->config->get('autocomplete_addressbooks');
3704b7 371     $list = array();
A 372
373     // We are using the DB address book
374     if ($abook_type != 'ldap') {
c0297f 375       $contacts = new rcube_contacts($this->db, null);
3704b7 376       $list['0'] = array(
A 377         'id' => 0,
a61bbb 378         'name' => rcube_label('personaladrbook'),
c0297f 379         'groups' => $contacts->groups,
3704b7 380         'readonly' => false,
a61bbb 381         'autocomplete' => in_array('sql', $autocomplete)
3704b7 382       );
A 383     }
384
7fdb9d 385     if ($ldap_config) {
A 386       $ldap_config = (array) $ldap_config;
3704b7 387       foreach ($ldap_config as $id => $prop)
A 388         $list[$id] = array(
a61bbb 389           'id' => $id,
T 390           'name' => $prop['name'],
391           'groups' => false,
392           'readonly' => !$prop['writable'],
393           'autocomplete' => in_array('sql', $autocomplete)
3704b7 394         );
A 395     }
396
e6ce00 397     $plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
3704b7 398     $list = $plugin['sources'];
A 399
400     if ($writeable && !empty($list)) {
401       foreach ($list as $idx => $item) {
402         if ($item['readonly']) {
c0297f 403           unset($list[$idx]);
3704b7 404         }
A 405       }
406     }
7fdb9d 407
3704b7 408     return $list;
A 409   }
b62a0d 410
A 411
ade8e1 412   /**
197601 413    * Init output object for GUI and add common scripts.
T 414    * This will instantiate a rcmail_template object and set
415    * environment vars according to the current session and configuration
0ece58 416    *
T 417    * @param boolean True if this request is loaded in a (i)frame
5c461b 418    * @return rcube_template Reference to HTML output object
197601 419    */
T 420   public function load_gui($framed = false)
421   {
422     // init output page
0ece58 423     if (!($this->output instanceof rcube_template))
T 424       $this->output = new rcube_template($this->task, $framed);
197601 425
95d90f 426     // set keep-alive/check-recent interval
bf67d6 427     if ($this->session && ($keep_alive = $this->session->get_keep_alive())) {
929a50 428       $this->output->set_env('keep_alive', $keep_alive);
95d90f 429     }
197601 430
T 431     if ($framed) {
432       $this->comm_path .= '&_framed=1';
433       $this->output->set_env('framed', true);
434     }
435
436     $this->output->set_env('task', $this->task);
437     $this->output->set_env('action', $this->action);
438     $this->output->set_env('comm_path', $this->comm_path);
79c45f 439     $this->output->set_charset(RCMAIL_CHARSET);
197601 440
T 441     // add some basic label to client
74d421 442     $this->output->add_label('loading', 'servererror');
b62a0d 443
197601 444     return $this->output;
T 445   }
b62a0d 446
A 447
197601 448   /**
T 449    * Create an output object for JSON responses
0ece58 450    *
5c461b 451    * @return rcube_json_output Reference to JSON output object
197601 452    */
929a50 453   public function json_init()
197601 454   {
0ece58 455     if (!($this->output instanceof rcube_json_output))
T 456       $this->output = new rcube_json_output($this->task);
b62a0d 457
197601 458     return $this->output;
2c3d81 459   }
A 460
461
462   /**
463    * Create SMTP object and connect to server
464    *
465    * @param boolean True if connection should be established
466    */
467   public function smtp_init($connect = false)
468   {
469     $this->smtp = new rcube_smtp();
b62a0d 470
2c3d81 471     if ($connect)
A 472       $this->smtp->connect();
197601 473   }
b62a0d 474
A 475
197601 476   /**
T 477    * Create global IMAP object and connect to server
478    *
479    * @param boolean True if connection should be established
480    * @todo Remove global $IMAP
481    */
1854c4 482   public function imap_init($connect = false)
197601 483   {
47d8d3 484     // already initialized
T 485     if (is_object($this->imap))
486       return;
b62a0d 487
197601 488     $this->imap = new rcube_imap($this->db);
T 489     $this->imap->debug_level = $this->config->get('debug_level');
490     $this->imap->skip_deleted = $this->config->get('skip_deleted');
491
492     // enable caching of imap data
493     if ($this->config->get('enable_caching')) {
494       $this->imap->set_caching(true);
495     }
496
497     // set pagesize from config
498     $this->imap->set_pagesize($this->config->get('pagesize', 50));
b62a0d 499
600981 500     // Setting root and delimiter before establishing the connection
b62a0d 501     // can save time detecting them using NAMESPACE and LIST
230f94 502     $options = array(
bdab2c 503       'auth_method' => $this->config->get('imap_auth_type', 'check'),
a1fe6b 504       'auth_cid'    => $this->config->get('imap_auth_cid'),
A 505       'auth_pw'     => $this->config->get('imap_auth_pw'),
f07d23 506       'debug_mode'  => (bool) $this->config->get('imap_debug', 0),
A 507       'force_caps'  => (bool) $this->config->get('imap_force_caps'),
508       'timeout'     => (int) $this->config->get('imap_timeout', 0),
230f94 509     );
76db10 510
230f94 511     $this->imap->set_options($options);
b62a0d 512
197601 513     // set global object for backward compatibility
T 514     $GLOBALS['IMAP'] = $this->imap;
48bc52 515
A 516     $hook = $this->plugins->exec_hook('imap_init', array('fetch_headers' => $this->imap->fetch_add_headers));
517     if ($hook['fetch_headers'])
518       $this->imap->fetch_add_headers = $hook['fetch_headers'];
b62a0d 519
47d8d3 520     // support this parameter for backward compatibility but log warning
T 521     if ($connect) {
1854c4 522       $this->imap_connect();
13ffa2 523       raise_error(array(
A 524         'code' => 800, 'type' => 'imap',
525         'file' => __FILE__, 'line' => __LINE__,
526         'message' => "rcube::imap_init(true) is deprecated, use rcube::imap_connect() instead"),
527         true, false);
47d8d3 528     }
1854c4 529   }
T 530
531
532   /**
533    * Connect to IMAP server with stored session data
534    *
535    * @return bool True on success, false on error
536    */
537   public function imap_connect()
538   {
48bc52 539     if (!$this->imap)
A 540       $this->imap_init();
b62a0d 541
59c216 542     if ($_SESSION['imap_host'] && !$this->imap->conn->connected()) {
A 543       if (!$this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])) {
1854c4 544         if ($this->output)
0f0c17 545           $this->output->show_message($this->imap->get_error_code() == -1 ? 'imaperror' : 'sessionerror', 'error');
1854c4 546       }
59c216 547       else {
A 548         $this->set_imap_prop();
549         return $this->imap->conn;
550       }
1854c4 551     }
T 552
59c216 553     return false;
929a50 554   }
A 555
556
557   /**
558    * Create session object and start the session.
559    */
560   public function session_init()
561   {
bf67d6 562     // session started (Installer?)
A 563     if (session_id())
564       return;
565
929a50 566     $lifetime = $this->config->get('session_lifetime', 0) * 60;
A 567
568     // set session domain
569     if ($domain = $this->config->get('session_domain')) {
570       ini_set('session.cookie_domain', $domain);
571     }
572     // set session garbage collecting time according to session_lifetime
573     if ($lifetime) {
574       ini_set('session.gc_maxlifetime', $lifetime * 2);
575     }
576
577     ini_set('session.cookie_secure', rcube_https_check());
578     ini_set('session.name', 'roundcube_sessid');
579     ini_set('session.use_cookies', 1);
b62a0d 580     ini_set('session.use_only_cookies', 1);
929a50 581     ini_set('session.serialize_handler', 'php');
A 582
583     // use database for storing session data
584     $this->session = new rcube_session($this->get_dbh(), $lifetime);
585
586     $this->session->register_gc_handler('rcmail_temp_gc');
587     if ($this->config->get('enable_caching'))
588       $this->session->register_gc_handler('rcmail_cache_gc');
589
590     // start PHP session (if not in CLI mode)
591     if ($_SERVER['REMOTE_ADDR'])
592       session_start();
593
594     // set initial session vars
595     if (!isset($_SESSION['auth_time'])) {
596       $_SESSION['auth_time'] = time();
597       $_SESSION['temp'] = true;
598     }
599   }
600
601
602   /**
603    * Configure session object internals
604    */
605   public function session_configure()
606   {
bf67d6 607     if (!$this->session)
A 608       return;
609
929a50 610     $lifetime = $this->config->get('session_lifetime', 0) * 60;
A 611
612     // set keep-alive/check-recent interval
613     if ($keep_alive = $this->config->get('keep_alive')) {
614       // be sure that it's less than session lifetime
615       if ($lifetime)
616         $keep_alive = min($keep_alive, $lifetime - 30);
617       $keep_alive = max(60, $keep_alive);
618       $this->session->set_keep_alive($keep_alive);
619     }
197601 620   }
T 621
622
623   /**
624    * Perfom login to the IMAP server and to the webmail service.
625    * This will also create a new user entry if auto_create_user is configured.
626    *
627    * @param string IMAP user name
628    * @param string IMAP password
629    * @param string IMAP host
630    * @return boolean True on success, False on failure
631    */
632   function login($username, $pass, $host=NULL)
633   {
634     $user = NULL;
635     $config = $this->config->all();
636
637     if (!$host)
638       $host = $config['default_host'];
639
640     // Validate that selected host is in the list of configured hosts
641     if (is_array($config['default_host'])) {
642       $allowed = false;
643       foreach ($config['default_host'] as $key => $host_allowed) {
644         if (!is_numeric($key))
645           $host_allowed = $key;
646         if ($host == $host_allowed) {
647           $allowed = true;
648           break;
649         }
650       }
651       if (!$allowed)
652         return false;
653       }
bb8721 654     else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
197601 655       return false;
T 656
657     // parse $host URL
658     $a_host = parse_url($host);
659     if ($a_host['host']) {
660       $host = $a_host['host'];
661       $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
e99991 662       if (!empty($a_host['port']))
f86e8f 663         $imap_port = $a_host['port'];
904809 664       else if ($imap_ssl && $imap_ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
f86e8f 665         $imap_port = 993;
197601 666     }
b62a0d 667
f86e8f 668     $imap_port = $imap_port ? $imap_port : $config['default_port'];
197601 669
b62a0d 670     /* Modify username with domain if required
197601 671        Inspired by Marco <P0L0_notspam_binware.org>
T 672     */
673     // Check if we need to add domain
c16fab 674     if (!empty($config['username_domain']) && strpos($username, '@') === false) {
197601 675       if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
6a642d 676         $username .= '@'.rcube_parse_host($config['username_domain'][$host]);
197601 677       else if (is_string($config['username_domain']))
6a642d 678         $username .= '@'.rcube_parse_host($config['username_domain']);
197601 679     }
T 680
db1a87 681     // Convert username to lowercase. If IMAP backend
T 682     // is case-insensitive we need to store always the same username (#1487113)
683     if ($config['login_lc']) {
684       $username = mb_strtolower($username);
685     }
686
942069 687     // try to resolve email address from virtuser table
db1a87 688     if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
T 689       $username = $virtuser;
690     }
197601 691
f1adbf 692     // Here we need IDNA ASCII
A 693     // Only rcube_contacts class is using domain names in Unicode
694     $host = idn_to_ascii($host);
695     if (strpos($username, '@')) {
8f94b1 696       // lowercase domain name
A 697       list($local, $domain) = explode('@', $username);
698       $username = $local . '@' . mb_strtolower($domain);
f1adbf 699       $username = idn_to_ascii($username);
A 700     }
701
197601 702     // user already registered -> overwrite username
T 703     if ($user = rcube_user::query($username, $host))
704       $username = $user->data['username'];
705
48bc52 706     if (!$this->imap)
A 707       $this->imap_init();
708
6d94ab 709     // try IMAP login
T 710     if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl))) {
f1adbf 711       // try with lowercase
6d94ab 712       $username_lc = mb_strtolower($username);
db1a87 713       if ($username_lc != $username) {
T 714         // try to find user record again -> overwrite username
715         if (!$user && ($user = rcube_user::query($username_lc, $host)))
716           $username_lc = $user->data['username'];
717
718         if ($imap_login = $this->imap->connect($host, $username_lc, $pass, $imap_port, $imap_ssl))
719           $username = $username_lc;
720       }
6d94ab 721     }
T 722
197601 723     // exit if IMAP login failed
6d94ab 724     if (!$imap_login)
197601 725       return false;
T 726
b5846e 727     $this->set_imap_prop();
A 728
197601 729     // user already registered -> update user's record
T 730     if (is_object($user)) {
b5846e 731       // create default folders on first login
A 732       if (!$user->data['last_login'] && $config['create_default_folders'])
733         $this->imap->create_default_folders();
197601 734       $user->touch();
T 735     }
736     // create new system user
737     else if ($config['auto_create_user']) {
738       if ($created = rcube_user::create($username, $host)) {
739         $user = $created;
b5846e 740         // create default folders on first login
A 741         if ($config['create_default_folders'])
742           $this->imap->create_default_folders();
197601 743       }
f879f4 744       else {
T 745         raise_error(array(
10eedb 746           'code' => 600, 'type' => 'php',
6d94ab 747           'file' => __FILE__, 'line' => __LINE__,
f879f4 748           'message' => "Failed to create a user record. Maybe aborted by a plugin?"
10eedb 749           ), true, false);
f879f4 750       }
197601 751     }
T 752     else {
753       raise_error(array(
10eedb 754         'code' => 600, 'type' => 'php',
A 755         'file' => __FILE__, 'line' => __LINE__,
197601 756         'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
T 757         ), true, false);
758     }
759
760     // login succeeded
761     if (is_object($user) && $user->ID) {
762       $this->set_user($user);
763
764       // set session vars
765       $_SESSION['user_id']   = $user->ID;
766       $_SESSION['username']  = $user->data['username'];
767       $_SESSION['imap_host'] = $host;
768       $_SESSION['imap_port'] = $imap_port;
769       $_SESSION['imap_ssl']  = $imap_ssl;
2471d3 770       $_SESSION['password']  = $this->encrypt($pass);
197601 771       $_SESSION['login_time'] = mktime();
b62a0d 772
A 773       if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
c8ae24 774         $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
197601 775
T 776       // force reloading complete list of subscribed mailboxes
777       $this->imap->clear_cache('mailboxes');
778
779       return true;
780     }
781
782     return false;
783   }
784
785
786   /**
787    * Set root dir and last stored mailbox
788    * This must be done AFTER connecting to the server!
789    */
790   public function set_imap_prop()
791   {
792     $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
793
794     if ($default_folders = $this->config->get('default_imap_folders')) {
795       $this->imap->set_default_mailboxes($default_folders);
796     }
448409 797     if (isset($_SESSION['mbox'])) {
197601 798       $this->imap->set_mailbox($_SESSION['mbox']);
T 799     }
800     if (isset($_SESSION['page'])) {
801       $this->imap->set_page($_SESSION['page']);
802     }
803   }
804
1854c4 805
T 806   /**
807    * Auto-select IMAP host based on the posted login information
808    *
809    * @return string Selected IMAP host
810    */
811   public function autoselect_host()
812   {
813     $default_host = $this->config->get('default_host');
257f88 814     $host = null;
b62a0d 815
257f88 816     if (is_array($default_host)) {
T 817       $post_host = get_input_value('_host', RCUBE_INPUT_POST);
b62a0d 818
257f88 819       // direct match in default_host array
T 820       if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
821         $host = $post_host;
822       }
b62a0d 823
257f88 824       // try to select host by mail domain
1854c4 825       list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
T 826       if (!empty($domain)) {
257f88 827         foreach ($default_host as $imap_host => $mail_domains) {
1854c4 828           if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
T 829             $host = $imap_host;
830             break;
831           }
832         }
833       }
834
835       // take the first entry if $host is still an array
257f88 836       if (empty($host)) {
T 837         $host = array_shift($default_host);
838       }
839     }
840     else if (empty($default_host)) {
841       $host = get_input_value('_host', RCUBE_INPUT_POST);
1854c4 842     }
eec34e 843     else
bb8721 844       $host = rcube_parse_host($default_host);
1854c4 845
T 846     return $host;
847   }
848
849
850   /**
851    * Get localized text in the desired language
852    *
853    * @param mixed Named parameters array or label name
854    * @return string Localized text
855    */
cc97ea 856   public function gettext($attrib, $domain=null)
1854c4 857   {
T 858     // load localization files if not done yet
859     if (empty($this->texts))
860       $this->load_language();
b62a0d 861
1854c4 862     // extract attributes
T 863     if (is_string($attrib))
864       $attrib = array('name' => $attrib);
865
866     $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
9898fe 867     $name = $attrib['name'] ? $attrib['name'] : '';
1854c4 868
cc97ea 869     // check for text with domain
9898fe 870     if ($domain && ($text_item = $this->texts[$domain.'.'.$name]))
cc97ea 871       ;
1854c4 872     // text does not exist
9898fe 873     else if (!($text_item = $this->texts[$name])) {
A 874       return "[$name]";
1854c4 875     }
T 876
b62a0d 877     // make text item array
1854c4 878     $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
T 879
880     // decide which text to use
881     if ($nr == 1) {
882       $text = $a_text_item['single'];
883     }
884     else if ($nr > 0) {
885       $text = $a_text_item['multiple'];
886     }
887     else if ($nr == 0) {
888       if ($a_text_item['none'])
889         $text = $a_text_item['none'];
890       else if ($a_text_item['single'])
891         $text = $a_text_item['single'];
892       else if ($a_text_item['multiple'])
893         $text = $a_text_item['multiple'];
894     }
895
896     // default text is single
897     if ($text == '') {
898       $text = $a_text_item['single'];
899     }
900
901     // replace vars in text
902     if (is_array($attrib['vars'])) {
903       foreach ($attrib['vars'] as $var_key => $var_value)
9898fe 904         $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
1854c4 905     }
T 906
907     // format output
908     if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
909       return ucfirst($text);
910     else if ($attrib['uppercase'])
2aa2b3 911       return mb_strtoupper($text);
1854c4 912     else if ($attrib['lowercase'])
2aa2b3 913       return mb_strtolower($text);
1854c4 914
T 915     return $text;
916   }
917
918
919   /**
920    * Load a localization package
921    *
922    * @param string Language ID
923    */
cc97ea 924   public function load_language($lang = null, $add = array())
1854c4 925   {
c8ae24 926     $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
b62a0d 927
1854c4 928     // load localized texts
T 929     if (empty($this->texts) || $lang != $_SESSION['language']) {
930       $this->texts = array();
931
932       // get english labels (these should be complete)
933       @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
934       @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
935
936       if (is_array($labels))
9d9f8d 937         $this->texts = $labels;
1854c4 938       if (is_array($messages))
9d9f8d 939         $this->texts = array_merge($this->texts, $messages);
1854c4 940
T 941       // include user language files
942       if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
943         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
944         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
945
946         if (is_array($labels))
947           $this->texts = array_merge($this->texts, $labels);
948         if (is_array($messages))
949           $this->texts = array_merge($this->texts, $messages);
950       }
b62a0d 951
1854c4 952       $_SESSION['language'] = $lang;
T 953     }
cc97ea 954
T 955     // append additional texts (from plugin)
956     if (is_array($add) && !empty($add))
957       $this->texts += $add;
1854c4 958   }
T 959
960
961   /**
962    * Read directory program/localization and return a list of available languages
963    *
964    * @return array List of available localizations
965    */
966   public function list_languages()
967   {
968     static $sa_languages = array();
969
970     if (!sizeof($sa_languages)) {
971       @include(INSTALL_PATH . 'program/localization/index.inc');
972
973       if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
974         while (($name = readdir($dh)) !== false) {
2aa2b3 975           if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
1854c4 976             continue;
T 977
978           if ($label = $rcube_languages[$name])
7d5178 979             $sa_languages[$name] = $label;
1854c4 980         }
T 981         closedir($dh);
982       }
983     }
984
985     return $sa_languages;
986   }
987
988
989   /**
990    * Check the auth hash sent by the client against the local session credentials
991    *
992    * @return boolean True if valid, False if not
993    */
994   function authenticate_session()
995   {
996     // advanced session authentication
997     if ($this->config->get('double_auth')) {
998       $now = time();
999       $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
1000                 $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
1001
1002       // renew auth cookie every 5 minutes (only for GET requests)
1003       if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
1004         $_SESSION['last_auth'] = $_SESSION['auth_time'];
1005         $_SESSION['auth_time'] = $now;
cefd1d 1006         rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
1854c4 1007       }
T 1008     }
1009     else {
929a50 1010       $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $this->session->get_ip() : true;
1854c4 1011     }
T 1012
1013     // check session filetime
1014     $lifetime = $this->config->get('session_lifetime');
929a50 1015     $sess_ts = $this->session->get_ts();
A 1016     if (!empty($lifetime) && !empty($sess_ts) && $sess_ts + $lifetime*60 < time()) {
1854c4 1017       $valid = false;
T 1018     }
1019
1020     return $valid;
1021   }
1022
1023
1024   /**
1025    * Destroy session data and remove cookie
1026    */
1027   public function kill_session()
1028   {
e6ce00 1029     $this->plugins->exec_hook('session_destroy');
b62a0d 1030
929a50 1031     $this->session->remove();
c8ae24 1032     $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
cefd1d 1033     rcmail::setcookie('sessauth', '-del-', time() - 60);
1854c4 1034     $this->user->reset();
T 1035   }
1036
1037
1038   /**
1039    * Do server side actions on logout
1040    */
1041   public function logout_actions()
1042   {
1043     $config = $this->config->all();
b62a0d 1044
A 1045     // on logout action we're not connected to imap server
1854c4 1046     if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
T 1047       if (!$this->authenticate_session())
1048         return;
1049
47d8d3 1050       $this->imap_connect();
1854c4 1051     }
T 1052
1053     if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1054       $this->imap->clear_mailbox($config['trash_mbox']);
1055     }
1056
1057     if ($config['logout_expunge']) {
1058       $this->imap->expunge('INBOX');
1059     }
1060   }
1061
1062
1063   /**
1064    * Function to be executed in script shutdown
1065    * Registered with register_shutdown_function()
1066    */
197601 1067   public function shutdown()
T 1068   {
59c216 1069     if (is_object($this->imap))
197601 1070       $this->imap->close();
T 1071
2c3d81 1072     if (is_object($this->smtp))
A 1073       $this->smtp->disconnect();
1074
457373 1075     foreach ($this->books as $book)
A 1076       if (is_object($book))
1077         $book->close();
197601 1078
T 1079     // before closing the database connection, write session data
75da0b 1080     if ($_SERVER['REMOTE_ADDR'])
A 1081       session_write_close();
2b35c5 1082
A 1083     // write performance stats to logs/console
1084     if ($this->config->get('devel_mode')) {
1085       if (function_exists('memory_get_usage'))
1086         $mem = show_bytes(memory_get_usage());
1087       if (function_exists('memory_get_peak_usage'))
1088         $mem .= '/'.show_bytes(memory_get_peak_usage());
1089
1090       $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
bf67d6 1091       if (defined('RCMAIL_START'))
A 1092         rcube_print_time(RCMAIL_START, $log);
1093       else
1094         console($log);
2b35c5 1095     }
197601 1096   }
b62a0d 1097
A 1098
1854c4 1099   /**
57f0c8 1100    * Generate a unique token to be used in a form request
T 1101    *
1102    * @return string The request token
1103    */
549933 1104   public function get_request_token()
57f0c8 1105   {
549933 1106     $key = $this->task;
b62a0d 1107
549933 1108     if (!$_SESSION['request_tokens'][$key])
b48d9b 1109       $_SESSION['request_tokens'][$key] = md5(uniqid($key . mt_rand(), true));
b62a0d 1110
549933 1111     return $_SESSION['request_tokens'][$key];
57f0c8 1112   }
b62a0d 1113
A 1114
57f0c8 1115   /**
T 1116    * Check if the current request contains a valid token
1117    *
549933 1118    * @param int Request method
57f0c8 1119    * @return boolean True if request token is valid false if not
T 1120    */
549933 1121   public function check_request($mode = RCUBE_INPUT_POST)
57f0c8 1122   {
T 1123     $token = get_input_value('_token', $mode);
549933 1124     return !empty($token) && $_SESSION['request_tokens'][$this->task] == $token;
57f0c8 1125   }
b62a0d 1126
A 1127
57f0c8 1128   /**
1854c4 1129    * Create unique authorization hash
T 1130    *
1131    * @param string Session ID
1132    * @param int Timestamp
1133    * @return string The generated auth hash
1134    */
1135   private function get_auth_hash($sess_id, $ts)
1136   {
1137     $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1138       $sess_id,
1139       $ts,
1140       $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1141       $_SERVER['HTTP_USER_AGENT']);
1142
1143     if (function_exists('sha1'))
1144       return sha1($auth_string);
1145     else
1146       return md5($auth_string);
1147   }
1148
2471d3 1149
1854c4 1150   /**
2471d3 1151    * Encrypt using 3DES
1854c4 1152    *
2471d3 1153    * @param string $clear clear text input
A 1154    * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1155    * @param boolean $base64 whether or not to base64_encode() the result before returning
1156    *
1157    * @return string encrypted text
1854c4 1158    */
2471d3 1159   public function encrypt($clear, $key = 'des_key', $base64 = true)
1854c4 1160   {
713a66 1161     if (!$clear)
A 1162       return '';
2471d3 1163     /*-
A 1164      * Add a single canary byte to the end of the clear text, which
1165      * will help find out how much of padding will need to be removed
1166      * upon decryption; see http://php.net/mcrypt_generic#68082
1167      */
1168     $clear = pack("a*H2", $clear, "80");
b62a0d 1169
2471d3 1170     if (function_exists('mcrypt_module_open') &&
A 1171         ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1172     {
564741 1173       $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
2471d3 1174       mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
A 1175       $cipher = $iv . mcrypt_generic($td, $clear);
1854c4 1176       mcrypt_generic_deinit($td);
T 1177       mcrypt_module_close($td);
1178     }
44155c 1179     else {
A 1180       @include_once('lib/des.inc');
1181
1182       if (function_exists('des')) {
1183         $des_iv_size = 8;
564741 1184         $iv = $this->create_iv($des_iv_size);
44155c 1185         $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
A 1186       }
1187       else {
1188         raise_error(array(
1189           'code' => 500, 'type' => 'php',
1190           'file' => __FILE__, 'line' => __LINE__,
1191           'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1192         ), true, true);
1193       }
1854c4 1194     }
44155c 1195
2471d3 1196     return $base64 ? base64_encode($cipher) : $cipher;
1854c4 1197   }
T 1198
1199   /**
2471d3 1200    * Decrypt 3DES-encrypted string
1854c4 1201    *
2471d3 1202    * @param string $cipher encrypted text
A 1203    * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1204    * @param boolean $base64 whether or not input is base64-encoded
1205    *
1206    * @return string decrypted text
1854c4 1207    */
2471d3 1208   public function decrypt($cipher, $key = 'des_key', $base64 = true)
1854c4 1209   {
713a66 1210     if (!$cipher)
A 1211       return '';
b62a0d 1212
2471d3 1213     $cipher = $base64 ? base64_decode($cipher) : $cipher;
A 1214
1215     if (function_exists('mcrypt_module_open') &&
1216         ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1217     {
db1a87 1218       $iv_size = mcrypt_enc_get_iv_size($td);
T 1219       $iv = substr($cipher, 0, $iv_size);
1220
1221       // session corruption? (#1485970)
1222       if (strlen($iv) < $iv_size)
1223         return '';
1224
1225       $cipher = substr($cipher, $iv_size);
2471d3 1226       mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
A 1227       $clear = mdecrypt_generic($td, $cipher);
1854c4 1228       mcrypt_generic_deinit($td);
T 1229       mcrypt_module_close($td);
1230     }
44155c 1231     else {
A 1232       @include_once('lib/des.inc');
b62a0d 1233
44155c 1234       if (function_exists('des')) {
A 1235         $des_iv_size = 8;
1236         $iv = substr($cipher, 0, $des_iv_size);
1237         $cipher = substr($cipher, $des_iv_size);
1238         $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1239       }
1240       else {
1241         raise_error(array(
1242           'code' => 500, 'type' => 'php',
1243           'file' => __FILE__, 'line' => __LINE__,
1244           'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1245         ), true, true);
1246       }
1854c4 1247     }
44155c 1248
2471d3 1249     /*-
A 1250      * Trim PHP's padding and the canary byte; see note in
1251      * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1252      */
1253     $clear = substr(rtrim($clear, "\0"), 0, -1);
b62a0d 1254
2471d3 1255     return $clear;
1854c4 1256   }
c719f3 1257
T 1258   /**
564741 1259    * Generates encryption initialization vector (IV)
A 1260    *
1261    * @param int Vector size
1262    * @return string Vector string
1263    */
1264   private function create_iv($size)
1265   {
1266     // mcrypt_create_iv() can be slow when system lacks entrophy
1267     // we'll generate IV vector manually
1268     $iv = '';
1269     for ($i = 0; $i < $size; $i++)
1270         $iv .= chr(mt_rand(0, 255));
1271     return $iv;
1272   }
1273
1274   /**
e019f2 1275    * Build a valid URL to this instance of Roundcube
c719f3 1276    *
T 1277    * @param mixed Either a string with the action or url parameters as key-value pairs
1278    * @return string Valid application URL
1279    */
1280   public function url($p)
1281   {
1282     if (!is_array($p))
fde466 1283       $p = array('_action' => @func_get_arg(0));
b62a0d 1284
1c932d 1285     $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
cc97ea 1286     $p['_task'] = $task;
1038a6 1287     unset($p['task']);
A 1288
cf1777 1289     $url = './';
T 1290     $delm = '?';
cc97ea 1291     foreach (array_reverse($p) as $key => $val)
cf1777 1292     {
T 1293       if (!empty($val)) {
cc97ea 1294         $par = $key[0] == '_' ? $key : '_'.$key;
cf1777 1295         $url .= $delm.urlencode($par).'='.urlencode($val);
T 1296         $delm = '&';
1297       }
1298     }
c719f3 1299     return $url;
T 1300   }
cefd1d 1301
T 1302
1303   /**
1304    * Helper method to set a cookie with the current path and host settings
1305    *
1306    * @param string Cookie name
1307    * @param string Cookie value
1308    * @param string Expiration time
1309    */
1310   public static function setcookie($name, $value, $exp = 0)
1311   {
317a7d 1312     if (headers_sent())
A 1313       return;
1314
cefd1d 1315     $cookie = session_get_cookie_params();
2273d4 1316
cefd1d 1317     setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
c96c5a 1318       rcube_https_check(), true);
cefd1d 1319   }
197601 1320 }
T 1321
1322