4 +-----------------------------------------------------------------------+
5 | program/include/rcmail.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
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 +-----------------------------------------------------------------------+
18 $Id: rcmail.php 328 2006-08-30 17:41:21Z thomasb $
24 * Application class of RoundCube Webmail
25 * implemented as singleton
31 static public $main_tasks = array('mail','settings','addressbook','login','logout','dummy');
33 static private $instance;
42 public $task = 'mail';
44 public $comm_path = './';
50 * This implements the 'singleton' design pattern
52 * @return object rcmail The one and only instance
54 static function get_instance()
56 if (!self::$instance) {
57 self::$instance = new rcmail();
58 self::$instance->startup(); // init AFTER object was linked with self::$instance
61 return self::$instance;
68 private function __construct()
71 $this->config = new rcube_config();
73 register_shutdown_function(array($this, 'shutdown'));
78 * Initial startup function
79 * to register session, create database and imap connections
81 * @todo Remove global vars $DB, $USER
83 private function startup()
85 $config_all = $this->config->all();
88 if ($this->config->get('log_driver') == 'syslog') {
89 $syslog_id = $this->config->get('syslog_id', 'roundcube');
90 $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
91 openlog($syslog_id, LOG_ODELAY, $syslog_facility);
94 // set task and action properties
95 $this->set_task(get_input_value('_task', RCUBE_INPUT_GPC));
96 $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
98 // connect to database
99 $GLOBALS['DB'] = $this->get_dbh();
101 // use database for storing session data
102 include_once('include/session.inc');
104 // set session domain
105 if (!empty($config_all['session_domain'])) {
106 ini_set('session.cookie_domain', $config_all['session_domain']);
108 // set session garbage collecting time according to session_lifetime
109 if (!empty($config_all['session_lifetime'])) {
110 ini_set('session.gc_maxlifetime', ($config_all['session_lifetime']) * 120);
113 // start PHP session (if not in CLI mode)
114 if ($_SERVER['REMOTE_ADDR'])
117 // set initial session vars
118 if (!isset($_SESSION['auth_time'])) {
119 $_SESSION['auth_time'] = time();
120 $_SESSION['temp'] = true;
123 // create user object
124 $this->set_user(new rcube_user($_SESSION['user_id']));
126 // reset some session parameters when changing task
127 if ($_SESSION['task'] != $this->task)
128 rcube_sess_unset('page');
130 // set current task to session
131 $_SESSION['task'] = $this->task;
133 // create IMAP object
134 if ($this->task == 'mail')
137 // create plugin API and load plugins
138 $this->plugins = rcube_plugin_api::get_instance();
143 * Setter for application task
145 * @param string Task to set
147 public function set_task($task)
149 $task = asciiwords($task);
150 $this->task = $task ? $task : 'mail';
151 $this->comm_path = $this->url(array('task' => $this->task));
154 $this->output->set_env('task', $this->task);
159 * Setter for system user object
161 * @param object rcube_user Current user instance
163 public function set_user($user)
165 if (is_object($user)) {
167 $GLOBALS['USER'] = $this->user;
169 // overwrite config with user preferences
170 $this->config->merge((array)$this->user->get_prefs());
173 $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
176 setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
178 // workaround for http://bugs.php.net/bug.php?id=18556
179 if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
180 setlocale(LC_CTYPE, 'en_US' . '.utf8');
185 * Check the given string and return a valid language code
187 * @param string Language code
188 * @return string Valid language code
190 private function language_prop($lang)
192 static $rcube_languages, $rcube_language_aliases;
194 // user HTTP_ACCEPT_LANGUAGE if no language is specified
195 if (empty($lang) || $lang == 'auto') {
196 $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
197 $lang = str_replace('-', '_', $accept_langs[0]);
200 if (empty($rcube_languages)) {
201 @include(INSTALL_PATH . 'program/localization/index.inc');
204 // check if we have an alias for that language
205 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
206 $lang = $rcube_language_aliases[$lang];
208 // try the first two chars
209 else if (!isset($rcube_languages[$lang])) {
210 $short = substr($lang, 0, 2);
212 // check if we have an alias for the short language code
213 if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
214 $lang = $rcube_language_aliases[$short];
216 // expand 'nn' to 'nn_NN'
217 else if (!isset($rcube_languages[$short])) {
218 $lang = $short.'_'.strtoupper($short);
222 if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
231 * Get the current database connection
233 * @return object rcube_mdb2 Database connection object
235 public function get_dbh()
238 $config_all = $this->config->all();
240 $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
241 $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
242 $this->db->set_debug((bool)$config_all['sql_debug']);
243 $this->db->db_connect('w');
251 * Return instance of the internal address book class
253 * @param boolean True if the address book needs to be writeable
254 * @return object rcube_contacts Address book object
256 public function get_address_book($id, $writeable = false)
259 $ldap_config = (array)$this->config->get('ldap_public');
260 $abook_type = strtolower($this->config->get('address_book_type'));
262 $plugin = $this->plugins->exec_hook('get_address_book', array('id' => $id, 'writeable' => $writeable));
264 // plugin returned instance of a rcube_addressbook
265 if ($plugin['instance'] instanceof rcube_addressbook) {
266 $contacts = $plugin['instance'];
268 else if ($id && $ldap_config[$id]) {
269 $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
271 else if ($id === '0') {
272 $contacts = new rcube_contacts($this->db, $this->user->ID);
274 else if ($abook_type == 'ldap') {
275 // Use the first writable LDAP address book.
276 foreach ($ldap_config as $id => $prop) {
277 if (!$writeable || $prop['writable']) {
278 $contacts = new rcube_ldap($prop, $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
284 $contacts = new rcube_contacts($this->db, $this->user->ID);
292 * Init output object for GUI and add common scripts.
293 * This will instantiate a rcmail_template object and set
294 * environment vars according to the current session and configuration
296 * @param boolean True if this request is loaded in a (i)frame
297 * @return object rcube_template Reference to HTML output object
299 public function load_gui($framed = false)
302 if (!($this->output instanceof rcube_template))
303 $this->output = new rcube_template($this->task, $framed);
305 // set keep-alive/check-recent interval
306 if ($keep_alive = $this->config->get('keep_alive')) {
307 // be sure that it's less than session lifetime
308 if ($session_lifetime = $this->config->get('session_lifetime'))
309 $keep_alive = min($keep_alive, $session_lifetime * 60 - 30);
310 $this->output->set_env('keep_alive', max(60, $keep_alive));
314 $this->comm_path .= '&_framed=1';
315 $this->output->set_env('framed', true);
318 $this->output->set_env('task', $this->task);
319 $this->output->set_env('action', $this->action);
320 $this->output->set_env('comm_path', $this->comm_path);
321 $this->output->set_charset(RCMAIL_CHARSET);
323 // add some basic label to client
324 $this->output->add_label('loading', 'servererror');
326 return $this->output;
331 * Create an output object for JSON responses
333 * @return object rcube_json_output Reference to JSON output object
335 public function init_json()
337 if (!($this->output instanceof rcube_json_output))
338 $this->output = new rcube_json_output($this->task);
340 return $this->output;
345 * Create SMTP object and connect to server
347 * @param boolean True if connection should be established
349 public function smtp_init($connect = false)
351 $this->smtp = new rcube_smtp();
354 $this->smtp->connect();
359 * Create global IMAP object and connect to server
361 * @param boolean True if connection should be established
362 * @todo Remove global $IMAP
364 public function imap_init($connect = false)
366 $this->imap = new rcube_imap($this->db);
367 $this->imap->debug_level = $this->config->get('debug_level');
368 $this->imap->skip_deleted = $this->config->get('skip_deleted');
369 $this->imap->index_sort = $this->config->get('index_sort', true);
371 // enable caching of imap data
372 if ($this->config->get('enable_caching')) {
373 $this->imap->set_caching(true);
376 // set pagesize from config
377 $this->imap->set_pagesize($this->config->get('pagesize', 50));
379 // Setting root and delimiter before iil_Connect can save time detecting them
380 // using NAMESPACE and LIST
382 'auth_method' => $this->config->get('imap_auth_type', 'check'),
383 'delimiter' => isset($_SESSION['imap_delimiter']) ? $_SESSION['imap_delimiter'] : $this->config->get('imap_delimiter'),
384 'rootdir' => isset($_SESSION['imap_root']) ? $_SESSION['imap_root'] : $this->config->get('imap_root'),
385 'debug_mode' => (bool) $this->config->get('imap_debug', 0),
388 $this->imap->set_options($options);
390 // set global object for backward compatibility
391 $GLOBALS['IMAP'] = $this->imap;
394 $this->imap_connect();
399 * Connect to IMAP server with stored session data
401 * @return bool True on success, false on error
403 public function imap_connect()
407 if ($_SESSION['imap_host'] && !$this->imap->conn) {
408 if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl']))) {
410 $this->output->show_message($this->imap->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
413 $this->set_imap_prop();
421 * Perfom login to the IMAP server and to the webmail service.
422 * This will also create a new user entry if auto_create_user is configured.
424 * @param string IMAP user name
425 * @param string IMAP password
426 * @param string IMAP host
427 * @return boolean True on success, False on failure
429 function login($username, $pass, $host=NULL)
432 $config = $this->config->all();
435 $host = $config['default_host'];
437 // Validate that selected host is in the list of configured hosts
438 if (is_array($config['default_host'])) {
440 foreach ($config['default_host'] as $key => $host_allowed) {
441 if (!is_numeric($key))
442 $host_allowed = $key;
443 if ($host == $host_allowed) {
451 else if (!empty($config['default_host']) && $host != $config['default_host'])
455 $a_host = parse_url($host);
456 if ($a_host['host']) {
457 $host = $a_host['host'];
458 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
459 if(!empty($a_host['port']))
460 $imap_port = $a_host['port'];
461 else if ($imap_ssl && $imap_ssl != 'tls')
465 $imap_port = $imap_port ? $imap_port : $config['default_port'];
467 /* Modify username with domain if required
468 Inspired by Marco <P0L0_notspam_binware.org>
470 // Check if we need to add domain
471 if (!empty($config['username_domain']) && !strpos($username, '@')) {
472 if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
473 $username .= '@'.$config['username_domain'][$host];
474 else if (is_string($config['username_domain']))
475 $username .= '@'.$config['username_domain'];
478 // try to resolve email address from virtuser table
479 if (strpos($username, '@'))
480 if ($virtuser = rcube_user::email2user($username))
481 $username = $virtuser;
483 // lowercase username if it's an e-mail address (#1484473)
484 if (strpos($username, '@'))
485 $username = mb_strtolower($username);
487 // user already registered -> overwrite username
488 if ($user = rcube_user::query($username, $host))
489 $username = $user->data['username'];
491 // exit if IMAP login failed
492 if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl)))
495 // user already registered -> update user's record
496 if (is_object($user)) {
499 // create new system user
500 else if ($config['auto_create_user']) {
501 if ($created = rcube_user::create($username, $host)) {
504 // get existing mailboxes (but why?)
505 // $a_mailboxes = $this->imap->list_mailboxes();
511 'message' => "Failed to create a user record. Maybe aborted by a plugin?"
519 'file' => RCMAIL_CONFIG_DIR."/main.inc.php",
520 'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
525 if (is_object($user) && $user->ID) {
526 $this->set_user($user);
529 $_SESSION['user_id'] = $user->ID;
530 $_SESSION['username'] = $user->data['username'];
531 $_SESSION['imap_host'] = $host;
532 $_SESSION['imap_port'] = $imap_port;
533 $_SESSION['imap_ssl'] = $imap_ssl;
534 $_SESSION['password'] = $this->encrypt($pass);
535 $_SESSION['login_time'] = mktime();
537 if ($_REQUEST['_timezone'] != '_default_')
538 $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
540 // force reloading complete list of subscribed mailboxes
541 $this->set_imap_prop();
542 $this->imap->clear_cache('mailboxes');
544 if ($config['create_default_folders'])
545 $this->imap->create_default_folders();
555 * Set root dir and last stored mailbox
556 * This must be done AFTER connecting to the server!
558 public function set_imap_prop()
560 $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
562 if ($default_folders = $this->config->get('default_imap_folders')) {
563 $this->imap->set_default_mailboxes($default_folders);
565 if (!empty($_SESSION['mbox'])) {
566 $this->imap->set_mailbox($_SESSION['mbox']);
568 if (isset($_SESSION['page'])) {
569 $this->imap->set_page($_SESSION['page']);
572 // cache IMAP root and delimiter in session for performance reasons
573 $_SESSION['imap_root'] = $this->imap->root_dir;
574 $_SESSION['imap_delimiter'] = $this->imap->delimiter;
579 * Auto-select IMAP host based on the posted login information
581 * @return string Selected IMAP host
583 public function autoselect_host()
585 $default_host = $this->config->get('default_host');
588 if (is_array($default_host)) {
589 $post_host = get_input_value('_host', RCUBE_INPUT_POST);
591 // direct match in default_host array
592 if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
596 // try to select host by mail domain
597 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
598 if (!empty($domain)) {
599 foreach ($default_host as $imap_host => $mail_domains) {
600 if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
607 // take the first entry if $host is still an array
609 $host = array_shift($default_host);
612 else if (empty($default_host)) {
613 $host = get_input_value('_host', RCUBE_INPUT_POST);
616 $host = $default_host;
623 * Get localized text in the desired language
625 * @param mixed Named parameters array or label name
626 * @return string Localized text
628 public function gettext($attrib, $domain=null)
630 // load localization files if not done yet
631 if (empty($this->texts))
632 $this->load_language();
634 // extract attributes
635 if (is_string($attrib))
636 $attrib = array('name' => $attrib);
638 $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
639 $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
641 $command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
642 $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
644 // check for text with domain
645 if ($domain && ($text_item = $this->texts[$domain.'.'.$alias]))
647 // text does not exist
648 else if (!($text_item = $this->texts[$alias])) {
655 'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
660 // make text item array
661 $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
663 // decide which text to use
665 $text = $a_text_item['single'];
668 $text = $a_text_item['multiple'];
671 if ($a_text_item['none'])
672 $text = $a_text_item['none'];
673 else if ($a_text_item['single'])
674 $text = $a_text_item['single'];
675 else if ($a_text_item['multiple'])
676 $text = $a_text_item['multiple'];
679 // default text is single
681 $text = $a_text_item['single'];
684 // replace vars in text
685 if (is_array($attrib['vars'])) {
686 foreach ($attrib['vars'] as $var_key => $var_value)
687 $a_replace_vars[$var_key{0}=='$' ? substr($var_key, 1) : $var_key] = $var_value;
691 $text = preg_replace('/\$\{?([_a-z]{1}[_a-z0-9]*)\}?/ei', '$a_replace_vars["\1"]', $text);
694 if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
695 return ucfirst($text);
696 else if ($attrib['uppercase'])
697 return strtoupper($text);
698 else if ($attrib['lowercase'])
699 return strtolower($text);
706 * Load a localization package
708 * @param string Language ID
710 public function load_language($lang = null, $add = array())
712 $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
714 // load localized texts
715 if (empty($this->texts) || $lang != $_SESSION['language']) {
716 $this->texts = array();
718 // get english labels (these should be complete)
719 @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
720 @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
722 if (is_array($labels))
723 $this->texts = $labels;
724 if (is_array($messages))
725 $this->texts = array_merge($this->texts, $messages);
727 // include user language files
728 if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
729 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
730 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
732 if (is_array($labels))
733 $this->texts = array_merge($this->texts, $labels);
734 if (is_array($messages))
735 $this->texts = array_merge($this->texts, $messages);
738 $_SESSION['language'] = $lang;
741 // append additional texts (from plugin)
742 if (is_array($add) && !empty($add))
743 $this->texts += $add;
748 * Read directory program/localization and return a list of available languages
750 * @return array List of available localizations
752 public function list_languages()
754 static $sa_languages = array();
756 if (!sizeof($sa_languages)) {
757 @include(INSTALL_PATH . 'program/localization/index.inc');
759 if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
760 while (($name = readdir($dh)) !== false) {
761 if ($name{0}=='.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
764 if ($label = $rcube_languages[$name])
765 $sa_languages[$name] = $label;
771 return $sa_languages;
776 * Check the auth hash sent by the client against the local session credentials
778 * @return boolean True if valid, False if not
780 function authenticate_session()
782 global $SESS_CLIENT_IP, $SESS_CHANGED;
784 // advanced session authentication
785 if ($this->config->get('double_auth')) {
787 $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
788 $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
790 // renew auth cookie every 5 minutes (only for GET requests)
791 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
792 $_SESSION['last_auth'] = $_SESSION['auth_time'];
793 $_SESSION['auth_time'] = $now;
794 rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
798 $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
801 // check session filetime
802 $lifetime = $this->config->get('session_lifetime');
803 if (!empty($lifetime) && isset($SESS_CHANGED) && $SESS_CHANGED + $lifetime*60 < time()) {
812 * Destroy session data and remove cookie
814 public function kill_session()
816 $this->plugins->exec_hook('kill_session');
819 $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
820 rcmail::setcookie('sessauth', '-del-', time() - 60);
821 $this->user->reset();
826 * Do server side actions on logout
828 public function logout_actions()
830 $config = $this->config->all();
832 // on logout action we're not connected to imap server
833 if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
834 if (!$this->authenticate_session())
837 $this->imap_init(true);
840 if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
841 $this->imap->clear_mailbox($config['trash_mbox']);
844 if ($config['logout_expunge']) {
845 $this->imap->expunge('INBOX');
851 * Function to be executed in script shutdown
852 * Registered with register_shutdown_function()
854 public function shutdown()
856 if (is_object($this->imap)) {
857 $this->imap->close();
858 $this->imap->write_cache();
861 if (is_object($this->smtp))
862 $this->smtp->disconnect();
864 if (is_object($this->contacts))
865 $this->contacts->close();
867 // before closing the database connection, write session data
868 if ($_SERVER['REMOTE_ADDR'])
869 session_write_close();
874 * Generate a unique token to be used in a form request
876 * @return string The request token
878 public function get_request_token()
882 if (!$_SESSION['request_tokens'][$key])
883 $_SESSION['request_tokens'][$key] = md5(uniqid($key . mt_rand(), true));
885 return $_SESSION['request_tokens'][$key];
890 * Check if the current request contains a valid token
892 * @param int Request method
893 * @return boolean True if request token is valid false if not
895 public function check_request($mode = RCUBE_INPUT_POST)
897 $token = get_input_value('_token', $mode);
898 return !empty($token) && $_SESSION['request_tokens'][$this->task] == $token;
903 * Create unique authorization hash
905 * @param string Session ID
906 * @param int Timestamp
907 * @return string The generated auth hash
909 private function get_auth_hash($sess_id, $ts)
911 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
914 $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
915 $_SERVER['HTTP_USER_AGENT']);
917 if (function_exists('sha1'))
918 return sha1($auth_string);
920 return md5($auth_string);
927 * @param string $clear clear text input
928 * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
929 * @param boolean $base64 whether or not to base64_encode() the result before returning
931 * @return string encrypted text
933 public function encrypt($clear, $key = 'des_key', $base64 = true)
938 * Add a single canary byte to the end of the clear text, which
939 * will help find out how much of padding will need to be removed
940 * upon decryption; see http://php.net/mcrypt_generic#68082
942 $clear = pack("a*H2", $clear, "80");
944 if (function_exists('mcrypt_module_open') &&
945 ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
947 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
948 mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
949 $cipher = $iv . mcrypt_generic($td, $clear);
950 mcrypt_generic_deinit($td);
951 mcrypt_module_close($td);
953 else if (function_exists('des'))
955 define('DES_IV_SIZE', 8);
957 for ($i = 0; $i < constant('DES_IV_SIZE'); $i++)
958 $iv .= sprintf("%c", mt_rand(0, 255));
959 $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
967 'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
971 return $base64 ? base64_encode($cipher) : $cipher;
975 * Decrypt 3DES-encrypted string
977 * @param string $cipher encrypted text
978 * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
979 * @param boolean $base64 whether or not input is base64-encoded
981 * @return string decrypted text
983 public function decrypt($cipher, $key = 'des_key', $base64 = true)
988 $cipher = $base64 ? base64_decode($cipher) : $cipher;
990 if (function_exists('mcrypt_module_open') &&
991 ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
993 $iv = substr($cipher, 0, mcrypt_enc_get_iv_size($td));
994 $cipher = substr($cipher, mcrypt_enc_get_iv_size($td));
995 mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
996 $clear = mdecrypt_generic($td, $cipher);
997 mcrypt_generic_deinit($td);
998 mcrypt_module_close($td);
1000 else if (function_exists('des'))
1002 define('DES_IV_SIZE', 8);
1003 $iv = substr($cipher, 0, constant('DES_IV_SIZE'));
1004 $cipher = substr($cipher, constant('DES_IV_SIZE'));
1005 $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1013 'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1018 * Trim PHP's padding and the canary byte; see note in
1019 * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1021 $clear = substr(rtrim($clear, "\0"), 0, -1);
1027 * Build a valid URL to this instance of RoundCube
1029 * @param mixed Either a string with the action or url parameters as key-value pairs
1030 * @return string Valid application URL
1032 public function url($p)
1035 $p = array('_action' => @func_get_arg(0));
1037 $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
1038 $p['_task'] = $task;
1043 foreach (array_reverse($p) as $key => $val)
1046 $par = $key[0] == '_' ? $key : '_'.$key;
1047 $url .= $delm.urlencode($par).'='.urlencode($val);
1056 * Helper method to set a cookie with the current path and host settings
1058 * @param string Cookie name
1059 * @param string Cookie value
1060 * @param string Expiration time
1062 public static function setcookie($name, $value, $exp = 0)
1064 $cookie = session_get_cookie_params();
1065 setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
1066 ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != 'off')));