thomascube
2011-04-15 ef27a6a72375c92850c4ed17fa7476c6fb188d37
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                     |
f5e7b3 8  | Copyright (C) 2008-2010, 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,
3704b7 386         'readonly' => false,
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     }
0501b6 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     $lifetime = $this->config->get('session_lifetime', 0) * 60;
A 574
575     // set session domain
576     if ($domain = $this->config->get('session_domain')) {
577       ini_set('session.cookie_domain', $domain);
578     }
579     // set session garbage collecting time according to session_lifetime
580     if ($lifetime) {
581       ini_set('session.gc_maxlifetime', $lifetime * 2);
582     }
583
584     ini_set('session.cookie_secure', rcube_https_check());
585     ini_set('session.name', 'roundcube_sessid');
586     ini_set('session.use_cookies', 1);
b62a0d 587     ini_set('session.use_only_cookies', 1);
929a50 588     ini_set('session.serialize_handler', 'php');
A 589
590     // use database for storing session data
591     $this->session = new rcube_session($this->get_dbh(), $lifetime);
592
593     $this->session->register_gc_handler('rcmail_temp_gc');
594     if ($this->config->get('enable_caching'))
595       $this->session->register_gc_handler('rcmail_cache_gc');
596
597     // start PHP session (if not in CLI mode)
598     if ($_SERVER['REMOTE_ADDR'])
599       session_start();
600
601     // set initial session vars
cf2da2 602     if (!$_SESSION['user_id'])
929a50 603       $_SESSION['temp'] = true;
A 604   }
605
606
607   /**
608    * Configure session object internals
609    */
610   public function session_configure()
611   {
bf67d6 612     if (!$this->session)
A 613       return;
614
929a50 615     $lifetime = $this->config->get('session_lifetime', 0) * 60;
A 616
617     // set keep-alive/check-recent interval
618     if ($keep_alive = $this->config->get('keep_alive')) {
619       // be sure that it's less than session lifetime
620       if ($lifetime)
621         $keep_alive = min($keep_alive, $lifetime - 30);
622       $keep_alive = max(60, $keep_alive);
623       $this->session->set_keep_alive($keep_alive);
624     }
cf2da2 625     
T 626     $this->session->set_secret($this->config->get('des_key') . $_SERVER['HTTP_USER_AGENT']);
627     $this->session->set_ip_check($this->config->get('ip_check'));
197601 628   }
T 629
630
631   /**
632    * Perfom login to the IMAP server and to the webmail service.
633    * This will also create a new user entry if auto_create_user is configured.
634    *
635    * @param string IMAP user name
636    * @param string IMAP password
637    * @param string IMAP host
638    * @return boolean True on success, False on failure
639    */
640   function login($username, $pass, $host=NULL)
641   {
642     $user = NULL;
643     $config = $this->config->all();
644
645     if (!$host)
646       $host = $config['default_host'];
647
648     // Validate that selected host is in the list of configured hosts
649     if (is_array($config['default_host'])) {
650       $allowed = false;
651       foreach ($config['default_host'] as $key => $host_allowed) {
652         if (!is_numeric($key))
653           $host_allowed = $key;
654         if ($host == $host_allowed) {
655           $allowed = true;
656           break;
657         }
658       }
659       if (!$allowed)
660         return false;
661       }
bb8721 662     else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
197601 663       return false;
T 664
665     // parse $host URL
666     $a_host = parse_url($host);
667     if ($a_host['host']) {
668       $host = $a_host['host'];
669       $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
e99991 670       if (!empty($a_host['port']))
f86e8f 671         $imap_port = $a_host['port'];
904809 672       else if ($imap_ssl && $imap_ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
f86e8f 673         $imap_port = 993;
197601 674     }
b62a0d 675
f86e8f 676     $imap_port = $imap_port ? $imap_port : $config['default_port'];
197601 677
b62a0d 678     /* Modify username with domain if required
197601 679        Inspired by Marco <P0L0_notspam_binware.org>
T 680     */
681     // Check if we need to add domain
c16fab 682     if (!empty($config['username_domain']) && strpos($username, '@') === false) {
197601 683       if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
a76cbd 684         $username .= '@'.rcube_parse_host($config['username_domain'][$host], $host);
197601 685       else if (is_string($config['username_domain']))
a76cbd 686         $username .= '@'.rcube_parse_host($config['username_domain'], $host);
197601 687     }
T 688
e17553 689     // Convert username to lowercase. If IMAP backend
A 690     // is case-insensitive we need to store always the same username (#1487113)
691     if ($config['login_lc']) {
692       $username = mb_strtolower($username);
693     }
694
942069 695     // try to resolve email address from virtuser table
e17553 696     if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
A 697       $username = $virtuser;
698     }
197601 699
f1adbf 700     // Here we need IDNA ASCII
A 701     // Only rcube_contacts class is using domain names in Unicode
e8d5bd 702     $host = rcube_idn_to_ascii($host);
f1adbf 703     if (strpos($username, '@')) {
8f94b1 704       // lowercase domain name
A 705       list($local, $domain) = explode('@', $username);
706       $username = $local . '@' . mb_strtolower($domain);
e8d5bd 707       $username = rcube_idn_to_ascii($username);
f1adbf 708     }
A 709
197601 710     // user already registered -> overwrite username
T 711     if ($user = rcube_user::query($username, $host))
712       $username = $user->data['username'];
713
48bc52 714     if (!$this->imap)
A 715       $this->imap_init();
716
6d94ab 717     // try IMAP login
T 718     if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl))) {
f1adbf 719       // try with lowercase
6d94ab 720       $username_lc = mb_strtolower($username);
e17553 721       if ($username_lc != $username) {
A 722         // try to find user record again -> overwrite username
723         if (!$user && ($user = rcube_user::query($username_lc, $host)))
724           $username_lc = $user->data['username'];
725
726         if ($imap_login = $this->imap->connect($host, $username_lc, $pass, $imap_port, $imap_ssl))
727           $username = $username_lc;
728       }
6d94ab 729     }
T 730
197601 731     // exit if IMAP login failed
6d94ab 732     if (!$imap_login)
197601 733       return false;
T 734
b5846e 735     $this->set_imap_prop();
A 736
197601 737     // user already registered -> update user's record
T 738     if (is_object($user)) {
b5846e 739       // create default folders on first login
A 740       if (!$user->data['last_login'] && $config['create_default_folders'])
741         $this->imap->create_default_folders();
197601 742       $user->touch();
T 743     }
744     // create new system user
745     else if ($config['auto_create_user']) {
746       if ($created = rcube_user::create($username, $host)) {
747         $user = $created;
b5846e 748         // create default folders on first login
A 749         if ($config['create_default_folders'])
750           $this->imap->create_default_folders();
197601 751       }
f879f4 752       else {
T 753         raise_error(array(
10eedb 754           'code' => 600, 'type' => 'php',
6d94ab 755           'file' => __FILE__, 'line' => __LINE__,
f879f4 756           'message' => "Failed to create a user record. Maybe aborted by a plugin?"
10eedb 757           ), true, false);
f879f4 758       }
197601 759     }
T 760     else {
761       raise_error(array(
10eedb 762         'code' => 600, 'type' => 'php',
A 763         'file' => __FILE__, 'line' => __LINE__,
197601 764         'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
T 765         ), true, false);
766     }
767
768     // login succeeded
769     if (is_object($user) && $user->ID) {
770       $this->set_user($user);
88ca38 771       $this->session_configure();
197601 772
T 773       // set session vars
774       $_SESSION['user_id']   = $user->ID;
775       $_SESSION['username']  = $user->data['username'];
776       $_SESSION['imap_host'] = $host;
777       $_SESSION['imap_port'] = $imap_port;
778       $_SESSION['imap_ssl']  = $imap_ssl;
2471d3 779       $_SESSION['password']  = $this->encrypt($pass);
197601 780       $_SESSION['login_time'] = mktime();
cf2da2 781       
b62a0d 782       if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
c8ae24 783         $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
197601 784
T 785       // force reloading complete list of subscribed mailboxes
786       $this->imap->clear_cache('mailboxes');
787
788       return true;
789     }
790
791     return false;
792   }
793
794
795   /**
796    * Set root dir and last stored mailbox
797    * This must be done AFTER connecting to the server!
798    */
799   public function set_imap_prop()
800   {
801     $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
802
803     if ($default_folders = $this->config->get('default_imap_folders')) {
804       $this->imap->set_default_mailboxes($default_folders);
805     }
448409 806     if (isset($_SESSION['mbox'])) {
197601 807       $this->imap->set_mailbox($_SESSION['mbox']);
T 808     }
809     if (isset($_SESSION['page'])) {
810       $this->imap->set_page($_SESSION['page']);
811     }
812   }
813
1854c4 814
T 815   /**
816    * Auto-select IMAP host based on the posted login information
817    *
818    * @return string Selected IMAP host
819    */
820   public function autoselect_host()
821   {
822     $default_host = $this->config->get('default_host');
257f88 823     $host = null;
b62a0d 824
257f88 825     if (is_array($default_host)) {
T 826       $post_host = get_input_value('_host', RCUBE_INPUT_POST);
b62a0d 827
257f88 828       // direct match in default_host array
T 829       if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
830         $host = $post_host;
831       }
b62a0d 832
257f88 833       // try to select host by mail domain
1854c4 834       list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
T 835       if (!empty($domain)) {
257f88 836         foreach ($default_host as $imap_host => $mail_domains) {
1854c4 837           if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
T 838             $host = $imap_host;
839             break;
840           }
841         }
842       }
843
844       // take the first entry if $host is still an array
257f88 845       if (empty($host)) {
T 846         $host = array_shift($default_host);
847       }
848     }
849     else if (empty($default_host)) {
850       $host = get_input_value('_host', RCUBE_INPUT_POST);
1854c4 851     }
eec34e 852     else
bb8721 853       $host = rcube_parse_host($default_host);
1854c4 854
T 855     return $host;
856   }
857
858
859   /**
860    * Get localized text in the desired language
861    *
862    * @param mixed Named parameters array or label name
863    * @return string Localized text
864    */
cc97ea 865   public function gettext($attrib, $domain=null)
1854c4 866   {
T 867     // load localization files if not done yet
868     if (empty($this->texts))
869       $this->load_language();
b62a0d 870
1854c4 871     // extract attributes
T 872     if (is_string($attrib))
873       $attrib = array('name' => $attrib);
874
875     $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
9898fe 876     $name = $attrib['name'] ? $attrib['name'] : '';
ae39c4 877     
T 878     // attrib contain text values: use them from now
879     if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us']))
880         $this->texts[$name] = $setval;
1854c4 881
cc97ea 882     // check for text with domain
9898fe 883     if ($domain && ($text_item = $this->texts[$domain.'.'.$name]))
cc97ea 884       ;
1854c4 885     // text does not exist
9898fe 886     else if (!($text_item = $this->texts[$name])) {
A 887       return "[$name]";
1854c4 888     }
T 889
b62a0d 890     // make text item array
1854c4 891     $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
T 892
893     // decide which text to use
894     if ($nr == 1) {
895       $text = $a_text_item['single'];
896     }
897     else if ($nr > 0) {
898       $text = $a_text_item['multiple'];
899     }
900     else if ($nr == 0) {
901       if ($a_text_item['none'])
902         $text = $a_text_item['none'];
903       else if ($a_text_item['single'])
904         $text = $a_text_item['single'];
905       else if ($a_text_item['multiple'])
906         $text = $a_text_item['multiple'];
907     }
908
909     // default text is single
910     if ($text == '') {
911       $text = $a_text_item['single'];
912     }
913
914     // replace vars in text
915     if (is_array($attrib['vars'])) {
916       foreach ($attrib['vars'] as $var_key => $var_value)
9898fe 917         $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
1854c4 918     }
T 919
920     // format output
921     if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
922       return ucfirst($text);
923     else if ($attrib['uppercase'])
2aa2b3 924       return mb_strtoupper($text);
1854c4 925     else if ($attrib['lowercase'])
2aa2b3 926       return mb_strtolower($text);
1854c4 927
T 928     return $text;
929   }
930
931
932   /**
07b95d 933    * Check if the given text lable exists
T 934    *
935    * @param string Label name
936    * @return boolean True if text exists (either in the current language or in en_US)
937    */
938   public function text_exists($name, $domain=null)
939   {
940     // load localization files if not done yet
941     if (empty($this->texts))
942       $this->load_language();
943
944     // check for text with domain first
945     return ($domain && isset($this->texts[$domain.'.'.$name])) || isset($this->texts[$name]);
946   }
947
948   /**
1854c4 949    * Load a localization package
T 950    *
951    * @param string Language ID
952    */
cc97ea 953   public function load_language($lang = null, $add = array())
1854c4 954   {
c8ae24 955     $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
b62a0d 956
1854c4 957     // load localized texts
T 958     if (empty($this->texts) || $lang != $_SESSION['language']) {
959       $this->texts = array();
960
7c9850 961       // handle empty lines after closing PHP tag in localization files
A 962       ob_start();
963
1854c4 964       // get english labels (these should be complete)
T 965       @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
966       @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
967
968       if (is_array($labels))
9d9f8d 969         $this->texts = $labels;
1854c4 970       if (is_array($messages))
9d9f8d 971         $this->texts = array_merge($this->texts, $messages);
1854c4 972
T 973       // include user language files
974       if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
975         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
976         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
977
978         if (is_array($labels))
979           $this->texts = array_merge($this->texts, $labels);
980         if (is_array($messages))
981           $this->texts = array_merge($this->texts, $messages);
982       }
b62a0d 983
7c9850 984       ob_end_clean();
A 985
1854c4 986       $_SESSION['language'] = $lang;
T 987     }
cc97ea 988
T 989     // append additional texts (from plugin)
990     if (is_array($add) && !empty($add))
991       $this->texts += $add;
1854c4 992   }
T 993
994
995   /**
996    * Read directory program/localization and return a list of available languages
997    *
998    * @return array List of available localizations
999    */
1000   public function list_languages()
1001   {
1002     static $sa_languages = array();
1003
1004     if (!sizeof($sa_languages)) {
1005       @include(INSTALL_PATH . 'program/localization/index.inc');
1006
1007       if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
1008         while (($name = readdir($dh)) !== false) {
2aa2b3 1009           if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
1854c4 1010             continue;
T 1011
1012           if ($label = $rcube_languages[$name])
7d5178 1013             $sa_languages[$name] = $label;
1854c4 1014         }
T 1015         closedir($dh);
1016       }
1017     }
1018
1019     return $sa_languages;
1020   }
1021
1022
1023   /**
1024    * Destroy session data and remove cookie
1025    */
1026   public function kill_session()
1027   {
e6ce00 1028     $this->plugins->exec_hook('session_destroy');
b62a0d 1029
cf2da2 1030     $this->session->kill();
T 1031     $_SESSION = array('language' => $this->user->language, 'temp' => true);
1854c4 1032     $this->user->reset();
T 1033   }
1034
1035
1036   /**
1037    * Do server side actions on logout
1038    */
1039   public function logout_actions()
1040   {
1041     $config = $this->config->all();
b62a0d 1042
A 1043     // on logout action we're not connected to imap server
1854c4 1044     if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
cf2da2 1045       if (!$this->session->check_auth())
1854c4 1046         return;
T 1047
47d8d3 1048       $this->imap_connect();
1854c4 1049     }
T 1050
1051     if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1052       $this->imap->clear_mailbox($config['trash_mbox']);
1053     }
1054
1055     if ($config['logout_expunge']) {
1056       $this->imap->expunge('INBOX');
1057     }
1058   }
1059
1060
1061   /**
1062    * Function to be executed in script shutdown
1063    * Registered with register_shutdown_function()
1064    */
197601 1065   public function shutdown()
T 1066   {
2c3d81 1067     if (is_object($this->smtp))
A 1068       $this->smtp->disconnect();
1069
0501b6 1070     foreach ($this->address_books as $book) {
T 1071       if (!is_object($book))  // maybe an address book instance wasn't fetched using get_address_book() yet
1072         $book = $this->get_address_book($book['id']);
1073       if (is_a($book, 'rcube_addressbook'))
457373 1074         $book->close();
0501b6 1075     }
197601 1076
dd07e7 1077     if (is_object($this->imap))
A 1078       $this->imap->close();
1079
197601 1080     // before closing the database connection, write session data
4591de 1081     if ($_SERVER['REMOTE_ADDR']) {
T 1082       $this->session->cleanup();
75da0b 1083       session_write_close();
4591de 1084     }
2b35c5 1085
A 1086     // write performance stats to logs/console
1087     if ($this->config->get('devel_mode')) {
1088       if (function_exists('memory_get_usage'))
1089         $mem = show_bytes(memory_get_usage());
1090       if (function_exists('memory_get_peak_usage'))
1091         $mem .= '/'.show_bytes(memory_get_peak_usage());
1092
1093       $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
bf67d6 1094       if (defined('RCMAIL_START'))
A 1095         rcube_print_time(RCMAIL_START, $log);
1096       else
1097         console($log);
2b35c5 1098     }
197601 1099   }
b62a0d 1100
A 1101
1854c4 1102   /**
57f0c8 1103    * Generate a unique token to be used in a form request
T 1104    *
1105    * @return string The request token
1106    */
549933 1107   public function get_request_token()
57f0c8 1108   {
ec045b 1109     $sess_id = $_COOKIE[ini_get('session.name')];
c9f2c4 1110     if (!$sess_id) $sess_id = session_id();
ef27a6 1111     $plugin = $this->plugins->exec_hook('request_token', array('value' => md5('RT' . $this->task . $this->config->get('des_key') . $sess_id)));
T 1112     return $plugin['value'];
57f0c8 1113   }
b62a0d 1114
A 1115
57f0c8 1116   /**
T 1117    * Check if the current request contains a valid token
1118    *
549933 1119    * @param int Request method
57f0c8 1120    * @return boolean True if request token is valid false if not
T 1121    */
549933 1122   public function check_request($mode = RCUBE_INPUT_POST)
57f0c8 1123   {
T 1124     $token = get_input_value('_token', $mode);
ec045b 1125     $sess_id = $_COOKIE[ini_get('session.name')];
T 1126     return !empty($sess_id) && $token == $this->get_request_token();
57f0c8 1127   }
b62a0d 1128
A 1129
57f0c8 1130   /**
1854c4 1131    * Create unique authorization hash
T 1132    *
1133    * @param string Session ID
1134    * @param int Timestamp
1135    * @return string The generated auth hash
1136    */
1137   private function get_auth_hash($sess_id, $ts)
1138   {
1139     $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1140       $sess_id,
1141       $ts,
1142       $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1143       $_SERVER['HTTP_USER_AGENT']);
1144
1145     if (function_exists('sha1'))
1146       return sha1($auth_string);
1147     else
1148       return md5($auth_string);
1149   }
1150
2471d3 1151
1854c4 1152   /**
2471d3 1153    * Encrypt using 3DES
1854c4 1154    *
2471d3 1155    * @param string $clear clear text input
A 1156    * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1157    * @param boolean $base64 whether or not to base64_encode() the result before returning
1158    *
1159    * @return string encrypted text
1854c4 1160    */
2471d3 1161   public function encrypt($clear, $key = 'des_key', $base64 = true)
1854c4 1162   {
713a66 1163     if (!$clear)
A 1164       return '';
2471d3 1165     /*-
A 1166      * Add a single canary byte to the end of the clear text, which
1167      * will help find out how much of padding will need to be removed
1168      * upon decryption; see http://php.net/mcrypt_generic#68082
1169      */
1170     $clear = pack("a*H2", $clear, "80");
b62a0d 1171
2471d3 1172     if (function_exists('mcrypt_module_open') &&
A 1173         ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1174     {
564741 1175       $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
2471d3 1176       mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
A 1177       $cipher = $iv . mcrypt_generic($td, $clear);
1854c4 1178       mcrypt_generic_deinit($td);
T 1179       mcrypt_module_close($td);
1180     }
44155c 1181     else {
A 1182       @include_once('lib/des.inc');
1183
1184       if (function_exists('des')) {
1185         $des_iv_size = 8;
564741 1186         $iv = $this->create_iv($des_iv_size);
44155c 1187         $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
A 1188       }
1189       else {
1190         raise_error(array(
1191           'code' => 500, 'type' => 'php',
1192           'file' => __FILE__, 'line' => __LINE__,
1193           'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1194         ), true, true);
1195       }
1854c4 1196     }
44155c 1197
2471d3 1198     return $base64 ? base64_encode($cipher) : $cipher;
1854c4 1199   }
T 1200
1201   /**
2471d3 1202    * Decrypt 3DES-encrypted string
1854c4 1203    *
2471d3 1204    * @param string $cipher encrypted text
A 1205    * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1206    * @param boolean $base64 whether or not input is base64-encoded
1207    *
1208    * @return string decrypted text
1854c4 1209    */
2471d3 1210   public function decrypt($cipher, $key = 'des_key', $base64 = true)
1854c4 1211   {
713a66 1212     if (!$cipher)
A 1213       return '';
b62a0d 1214
2471d3 1215     $cipher = $base64 ? base64_decode($cipher) : $cipher;
A 1216
1217     if (function_exists('mcrypt_module_open') &&
1218         ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1219     {
9016a8 1220       $iv_size = mcrypt_enc_get_iv_size($td);
A 1221       $iv = substr($cipher, 0, $iv_size);
1222
1223       // session corruption? (#1485970)
1224       if (strlen($iv) < $iv_size)
1225         return '';
1226
1227       $cipher = substr($cipher, $iv_size);
2471d3 1228       mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
A 1229       $clear = mdecrypt_generic($td, $cipher);
1854c4 1230       mcrypt_generic_deinit($td);
T 1231       mcrypt_module_close($td);
1232     }
44155c 1233     else {
A 1234       @include_once('lib/des.inc');
b62a0d 1235
44155c 1236       if (function_exists('des')) {
A 1237         $des_iv_size = 8;
1238         $iv = substr($cipher, 0, $des_iv_size);
1239         $cipher = substr($cipher, $des_iv_size);
1240         $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1241       }
1242       else {
1243         raise_error(array(
1244           'code' => 500, 'type' => 'php',
1245           'file' => __FILE__, 'line' => __LINE__,
1246           'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1247         ), true, true);
1248       }
1854c4 1249     }
44155c 1250
2471d3 1251     /*-
A 1252      * Trim PHP's padding and the canary byte; see note in
1253      * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1254      */
1255     $clear = substr(rtrim($clear, "\0"), 0, -1);
b62a0d 1256
2471d3 1257     return $clear;
1854c4 1258   }
c719f3 1259
T 1260   /**
564741 1261    * Generates encryption initialization vector (IV)
A 1262    *
1263    * @param int Vector size
1264    * @return string Vector string
1265    */
1266   private function create_iv($size)
1267   {
1268     // mcrypt_create_iv() can be slow when system lacks entrophy
1269     // we'll generate IV vector manually
1270     $iv = '';
1271     for ($i = 0; $i < $size; $i++)
1272         $iv .= chr(mt_rand(0, 255));
1273     return $iv;
1274   }
1275
1276   /**
e019f2 1277    * Build a valid URL to this instance of Roundcube
c719f3 1278    *
T 1279    * @param mixed Either a string with the action or url parameters as key-value pairs
1280    * @return string Valid application URL
1281    */
1282   public function url($p)
1283   {
1284     if (!is_array($p))
fde466 1285       $p = array('_action' => @func_get_arg(0));
b62a0d 1286
1c932d 1287     $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
cc97ea 1288     $p['_task'] = $task;
1038a6 1289     unset($p['task']);
A 1290
cf1777 1291     $url = './';
T 1292     $delm = '?';
cc97ea 1293     foreach (array_reverse($p) as $key => $val)
cf1777 1294     {
T 1295       if (!empty($val)) {
cc97ea 1296         $par = $key[0] == '_' ? $key : '_'.$key;
cf1777 1297         $url .= $delm.urlencode($par).'='.urlencode($val);
T 1298         $delm = '&';
1299       }
1300     }
c719f3 1301     return $url;
T 1302   }
cefd1d 1303
T 1304
1305   /**
0501b6 1306    * Use imagemagick or GD lib to read image properties
T 1307    *
1308    * @param string Absolute file path
1309    * @return mixed Hash array with image props like type, width, height or False on error
1310    */
1311   public static function imageprops($filepath)
1312   {
1313     $rcmail = rcmail::get_instance();
1314     if ($cmd = $rcmail->config->get('im_identify_path', false)) {
1315       list(, $type, $size) = explode(' ', strtolower(rcmail::exec($cmd. ' 2>/dev/null {in}', array('in' => $filepath))));
1316       if ($size)
1317         list($width, $height) = explode('x', $size);
1318     }
1319     else if (function_exists('getimagesize')) {
1320       $imsize = @getimagesize($filepath);
1321       $width = $imsize[0];
1322       $height = $imsize[1];
1323       $type = preg_replace('!image/!', '', $imsize['mime']);
1324     }
1325
1326     return $type ? array('type' => $type, 'width' => $width, 'height' => $height) : false;
1327   }
1328
1329
1330   /**
1331    * Convert an image to a given size and type using imagemagick (ensures input is an image)
1332    *
1333    * @param $p['in']  Input filename (mandatory)
1334    * @param $p['out'] Output filename (mandatory)
1335    * @param $p['size']  Width x height of resulting image, e.g. "160x60"
1336    * @param $p['type']  Output file type, e.g. "jpg"
1337    * @param $p['-opts'] Custom command line options to ImageMagick convert
1338    * @return Success of convert as true/false
1339    */
1340   public static function imageconvert($p)
1341   {
1342     $result = false;
1343     $rcmail = rcmail::get_instance();
1344     $convert  = $rcmail->config->get('im_convert_path', false);
1345     $identify = $rcmail->config->get('im_identify_path', false);
1346     
1347     // imagemagick is required for this
1348     if (!$convert)
1349         return false;
1350
1351     if (!(($imagetype = @exif_imagetype($p['in'])) && ($type = image_type_to_extension($imagetype, false))))
1352       list(, $type) = explode(' ', strtolower(rcmail::exec($identify . ' 2>/dev/null {in}', $p))); # for things like eps
1353
1354     $type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
1355     $p += array('type' => $type, 'types' => "bmp,eps,gif,jp2,jpg,png,svg,tif", 'quality' => 75);
1356     $p['-opts'] = array('-resize' => $p['size'].'>') + (array)$p['-opts'];
1357
1358     if (in_array($type, explode(',', $p['types']))) # Valid type?
1359       $result = rcmail::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace RGB -quality {quality} {-opts} {in} {type}:{out}', $p) === "";
1360
1361     return $result;
1362   }
1363
1364
1365   /**
1366    * Construct shell command, execute it and return output as string.
1367    * Keywords {keyword} are replaced with arguments
1368    *
1369    * @param $cmd Format string with {keywords} to be replaced
1370    * @param $values (zero, one or more arrays can be passed)
1371    * @return output of command. shell errors not detectable
1372    */
1373   public static function exec(/* $cmd, $values1 = array(), ... */)
1374   {
1375     $args = func_get_args();
1376     $cmd = array_shift($args);
1377     $values = $replacements = array();
1378
1379     // merge values into one array
1380     foreach ($args as $arg)
1381       $values += (array)$arg;
1382
1383     preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
1384     foreach ($matches as $tags) {
1385       list(, $tag, $option, $key) = $tags;
1386       $parts = array();
1387
1388       if ($option) {
1389         foreach ((array)$values["-$key"] as $key => $value) {
1390           if ($value === true || $value === false || $value === null)
1391             $parts[] = $value ? $key : "";
1392           else foreach ((array)$value as $val)
1393             $parts[] = "$key " . escapeshellarg($val);
1394         }
1395       }
1396       else {
1397         foreach ((array)$values[$key] as $value)
1398           $parts[] = escapeshellarg($value);
1399       }
1400
1401       $replacements[$tag] = join(" ", $parts);
1402     }
1403
1404     // use strtr behaviour of going through source string once
1405     $cmd = strtr($cmd, $replacements);
1406     
1407     return (string)shell_exec($cmd);
1408   }
1409
1410
1411   /**
cefd1d 1412    * Helper method to set a cookie with the current path and host settings
T 1413    *
1414    * @param string Cookie name
1415    * @param string Cookie value
1416    * @param string Expiration time
1417    */
1418   public static function setcookie($name, $value, $exp = 0)
1419   {
317a7d 1420     if (headers_sent())
A 1421       return;
1422
cefd1d 1423     $cookie = session_get_cookie_params();
2273d4 1424
cefd1d 1425     setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
c96c5a 1426       rcube_https_check(), true);
cefd1d 1427   }
68d2d5 1428
A 1429   /**
1430    * Registers action aliases for current task
1431    *
1432    * @param array $map Alias-to-filename hash array
1433    */
1434   public function register_action_map($map)
1435   {
1436     if (is_array($map)) {
1437       foreach ($map as $idx => $val) {
1438         $this->action_map[$idx] = $val;
1439       }
1440     }
1441   }
1442   
1443   /**
1444    * Returns current action filename
1445    *
1446    * @param array $map Alias-to-filename hash array
1447    */
1448   public function get_action_file()
1449   {
1450     if (!empty($this->action_map[$this->action])) {
1451       return $this->action_map[$this->action];
1452     }
1453
1454     return strtr($this->action, '-', '_') . '.inc';
1455   }
1456
197601 1457 }