alecpl
2008-08-29 53bd8fae60e1663447efba9f44fc6b79b3a5c1de
commit | author | age
197601 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcmail.php                                            |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2008, RoundCube Dev. - Switzerland                      |
9  | Licensed under the GNU GPL                                            |
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
18  $Id: rcube_browser.php 328 2006-08-30 17:41:21Z thomasb $
19
20 */
21
22
23 /**
24  * Application class of RoundCube Webmail
25  * implemented as singleton
26  *
27  * @package Core
28  */
29 class rcmail
30 {
1854c4 31   static public $main_tasks = array('mail','settings','addressbook','login','logout');
197601 32   
T 33   static private $instance;
34   
35   public $config;
36   public $user;
37   public $db;
38   public $imap;
39   public $output;
40   public $task = 'mail';
41   public $action = '';
42   public $comm_path = './';
43   
44   private $texts;
45   
46   
47   /**
48    * This implements the 'singleton' design pattern
49    *
50    * @return object qvert The one and only instance
51    */
52   static function get_instance()
53   {
54     if (!self::$instance) {
55       self::$instance = new rcmail();
56       self::$instance->startup();  // init AFTER object was linked with self::$instance
57     }
58
59     return self::$instance;
60   }
61   
62   
63   /**
64    * Private constructor
65    */
66   private function __construct()
67   {
68     // load configuration
69     $this->config = new rcube_config();
70     
71     register_shutdown_function(array($this, 'shutdown'));
72   }
73   
74   
75   /**
76    * Initial startup function
77    * to register session, create database and imap connections
78    *
79    * @todo Remove global vars $DB, $USER
80    */
81   private function startup()
82   {
83     $config_all = $this->config->all();
84
b77d0d 85     // initialize syslog
A 86     if ($this->config->get('log_driver') == 'syslog') {
87       $syslog_id = $this->config->get('syslog_id', 'roundcube');
88       $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
89       openlog($syslog_id, LOG_ODELAY, $syslog_facility);
90     }
91                     
197601 92     // set task and action properties
T 93     $this->set_task(strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC)));
6ea6c9 94     $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
197601 95
T 96     // connect to database
97     $GLOBALS['DB'] = $this->get_dbh();
98
99     // use database for storing session data
100     include_once('include/session.inc');
101
102     // set session domain
103     if (!empty($config_all['session_domain'])) {
104       ini_set('session.cookie_domain', $config_all['session_domain']);
105     }
106     // set session garbage collecting time according to session_lifetime
107     if (!empty($config_all['session_lifetime'])) {
108       ini_set('session.gc_maxlifetime', ($config_all['session_lifetime']) * 120);
109     }
110
75da0b 111     // start PHP session (if not in CLI mode)
A 112     if ($_SERVER['REMOTE_ADDR'])
113       session_start();
197601 114
T 115     // set initial session vars
116     if (!isset($_SESSION['auth_time'])) {
117       $_SESSION['auth_time'] = time();
118       $_SESSION['temp'] = true;
119     }
120
121     // create user object
122     $this->set_user(new rcube_user($_SESSION['user_id']));
123
124     // reset some session parameters when changing task
125     if ($_SESSION['task'] != $this->task)
126       unset($_SESSION['page']);
127
128     // set current task to session
129     $_SESSION['task'] = $this->task;
130
131     // create IMAP object
132     if ($this->task == 'mail')
133       $this->imap_init();
134   }
135   
136   
137   /**
138    * Setter for application task
139    *
140    * @param string Task to set
141    */
142   public function set_task($task)
143   {
144     if (!in_array($task, self::$main_tasks))
145       $task = 'mail';
146     
147     $this->task = $task;
c719f3 148     $this->comm_path = $this->url(array('task' => $task));
197601 149     
T 150     if ($this->output)
151       $this->output->set_env('task', $task);
152   }
153   
154   
155   /**
156    * Setter for system user object
157    *
158    * @param object rcube_user Current user instance
159    */
160   public function set_user($user)
161   {
162     if (is_object($user)) {
163       $this->user = $user;
164       $GLOBALS['USER'] = $this->user;
165       
166       // overwrite config with user preferences
167       $this->config->merge((array)$this->user->get_prefs());
168     }
169     
170     $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language'));
531abb 171
197601 172     // set localization
531abb 173     setlocale(LC_ALL, $_SESSION['language'] . '.utf8');
197601 174   }
T 175   
176   
177   /**
178    * Check the given string and return a valid language code
179    *
180    * @param string Language code
181    * @return string Valid language code
182    */
183   private function language_prop($lang)
184   {
185     static $rcube_languages, $rcube_language_aliases;
186
187     if (empty($rcube_languages)) {
188       @include(INSTALL_PATH . 'program/localization/index.inc');
189     }
c3ab75 190     
197601 191     // check if we have an alias for that language
T 192     if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
193       $lang = $rcube_language_aliases[$lang];
194     }
195     // try the first two chars
c3ab75 196     else if (!isset($rcube_languages[$lang])) {
7e78b2 197       $short = substr($lang, 0, 2);
A 198      
235086 199       // check if we have an alias for the short language code
T 200       if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
201         $lang = $rcube_language_aliases[$short];
202       }
c3ab75 203       // expand 'nn' to 'nn_NN'
T 204       else if (!isset($rcube_languages[$short])) {
235086 205         $lang = $short.'_'.strtoupper($short);
T 206       }
197601 207     }
T 208
1854c4 209     if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
197601 210       $lang = 'en_US';
T 211     }
212
213     return $lang;
214   }
215   
216   
217   /**
218    * Get the current database connection
219    *
220    * @return object rcube_db  Database connection object
221    */
222   public function get_dbh()
223   {
224     if (!$this->db) {
225       $config_all = $this->config->all();
226
9e8e5f 227       $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
197601 228       $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
T 229       $this->db->set_debug((bool)$config_all['sql_debug']);
230       $this->db->db_connect('w');
231     }
232
233     return $this->db;
234   }
235   
236   
237   /**
238    * Init output object for GUI and add common scripts.
239    * This will instantiate a rcmail_template object and set
240    * environment vars according to the current session and configuration
0ece58 241    *
T 242    * @param boolean True if this request is loaded in a (i)frame
243    * @return object rcube_template Reference to HTML output object
197601 244    */
T 245   public function load_gui($framed = false)
246   {
247     // init output page
0ece58 248     if (!($this->output instanceof rcube_template))
T 249       $this->output = new rcube_template($this->task, $framed);
197601 250
d22455 251     foreach (array('flag_for_deletion','read_when_deleted') as $js_config_var) {
197601 252       $this->output->set_env($js_config_var, $this->config->get($js_config_var));
T 253     }
254
255     if ($framed) {
256       $this->comm_path .= '&_framed=1';
257       $this->output->set_env('framed', true);
258     }
259
260     $this->output->set_env('task', $this->task);
261     $this->output->set_env('action', $this->action);
262     $this->output->set_env('comm_path', $this->comm_path);
263     $this->output->set_charset($this->config->get('charset', RCMAIL_CHARSET));
264
265     // add some basic label to client
266     $this->output->add_label('loading');
267     
268     return $this->output;
269   }
270   
271   
272   /**
273    * Create an output object for JSON responses
0ece58 274    *
T 275    * @return object rcube_json_output Reference to JSON output object
197601 276    */
T 277   public function init_json()
278   {
0ece58 279     if (!($this->output instanceof rcube_json_output))
T 280       $this->output = new rcube_json_output($this->task);
197601 281     
T 282     return $this->output;
283   }
284   
285   
286   /**
287    * Create global IMAP object and connect to server
288    *
289    * @param boolean True if connection should be established
290    * @todo Remove global $IMAP
291    */
1854c4 292   public function imap_init($connect = false)
197601 293   {
T 294     $this->imap = new rcube_imap($this->db);
295     $this->imap->debug_level = $this->config->get('debug_level');
296     $this->imap->skip_deleted = $this->config->get('skip_deleted');
297
298     // enable caching of imap data
299     if ($this->config->get('enable_caching')) {
300       $this->imap->set_caching(true);
301     }
302
303     // set pagesize from config
304     $this->imap->set_pagesize($this->config->get('pagesize', 50));
1854c4 305   
197601 306     // set global object for backward compatibility
T 307     $GLOBALS['IMAP'] = $this->imap;
1854c4 308     
T 309     if ($connect)
310       $this->imap_connect();
311   }
312
313
314   /**
315    * Connect to IMAP server with stored session data
316    *
317    * @return bool True on success, false on error
318    */
319   public function imap_connect()
320   {
321     $conn = false;
322     
0ece58 323     if ($_SESSION['imap_host'] && !$this->imap->conn) {
75da0b 324       if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'], rcmail::get_instance()->config->get('imap_auth_type', 'check')))) {
1854c4 325         if ($this->output)
T 326           $this->output->show_message($this->imap->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
327       }
328
329       $this->set_imap_prop();
330     }
331
0ece58 332     return $conn;
197601 333   }
T 334
335
336   /**
337    * Perfom login to the IMAP server and to the webmail service.
338    * This will also create a new user entry if auto_create_user is configured.
339    *
340    * @param string IMAP user name
341    * @param string IMAP password
342    * @param string IMAP host
343    * @return boolean True on success, False on failure
344    */
345   function login($username, $pass, $host=NULL)
346   {
347     $user = NULL;
348     $config = $this->config->all();
349
350     if (!$host)
351       $host = $config['default_host'];
352
353     // Validate that selected host is in the list of configured hosts
354     if (is_array($config['default_host'])) {
355       $allowed = false;
356       foreach ($config['default_host'] as $key => $host_allowed) {
357         if (!is_numeric($key))
358           $host_allowed = $key;
359         if ($host == $host_allowed) {
360           $allowed = true;
361           break;
362         }
363       }
364       if (!$allowed)
365         return false;
366       }
367     else if (!empty($config['default_host']) && $host != $config['default_host'])
368       return false;
369
370     // parse $host URL
371     $a_host = parse_url($host);
372     if ($a_host['host']) {
373       $host = $a_host['host'];
374       $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
375       $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $config['default_port']);
376     }
377     else
378       $imap_port = $config['default_port'];
379
380
381     /* Modify username with domain if required  
382        Inspired by Marco <P0L0_notspam_binware.org>
383     */
384     // Check if we need to add domain
385     if (!empty($config['username_domain']) && !strpos($username, '@')) {
386       if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
387         $username .= '@'.$config['username_domain'][$host];
388       else if (is_string($config['username_domain']))
389         $username .= '@'.$config['username_domain'];
390     }
391
392     // try to resolve email address from virtuser table    
393     if (!empty($config['virtuser_file']) && strpos($username, '@'))
394       $username = rcube_user::email2user($username);
395
396     // lowercase username if it's an e-mail address (#1484473)
397     if (strpos($username, '@'))
398       $username = strtolower($username);
399
400     // user already registered -> overwrite username
401     if ($user = rcube_user::query($username, $host))
402       $username = $user->data['username'];
403
404     // exit if IMAP login failed
75da0b 405     if (!($imap_login  = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl, $config['imap_auth_type'])))
197601 406       return false;
T 407
408     // user already registered -> update user's record
409     if (is_object($user)) {
410       $user->touch();
411     }
412     // create new system user
413     else if ($config['auto_create_user']) {
414       if ($created = rcube_user::create($username, $host)) {
415         $user = $created;
416
417         // get existing mailboxes (but why?)
418         // $a_mailboxes = $this->imap->list_mailboxes();
419       }
420     }
421     else {
422       raise_error(array(
423         'code' => 600,
424         'type' => 'php',
425         'file' => "config/main.inc.php",
426         'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
427         ), true, false);
428     }
429
430     // login succeeded
431     if (is_object($user) && $user->ID) {
432       $this->set_user($user);
433
434       // set session vars
435       $_SESSION['user_id']   = $user->ID;
436       $_SESSION['username']  = $user->data['username'];
437       $_SESSION['imap_host'] = $host;
438       $_SESSION['imap_port'] = $imap_port;
439       $_SESSION['imap_ssl']  = $imap_ssl;
1854c4 440       $_SESSION['password']  = $this->encrypt_passwd($pass);
197601 441       $_SESSION['login_time'] = mktime();
T 442
443       // force reloading complete list of subscribed mailboxes
444       $this->set_imap_prop();
445       $this->imap->clear_cache('mailboxes');
446
447       if ($config['create_default_folders'])
448           $this->imap->create_default_folders();
449
450       return true;
451     }
452
453     return false;
454   }
455
456
457   /**
458    * Set root dir and last stored mailbox
459    * This must be done AFTER connecting to the server!
460    */
461   public function set_imap_prop()
462   {
463     $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
464
465     // set root dir from config
466     if ($imap_root = $this->config->get('imap_root')) {
467       $this->imap->set_rootdir($imap_root);
468     }
469     if ($default_folders = $this->config->get('default_imap_folders')) {
470       $this->imap->set_default_mailboxes($default_folders);
471     }
472     if (!empty($_SESSION['mbox'])) {
473       $this->imap->set_mailbox($_SESSION['mbox']);
474     }
475     if (isset($_SESSION['page'])) {
476       $this->imap->set_page($_SESSION['page']);
477     }
478   }
479
1854c4 480
T 481   /**
482    * Auto-select IMAP host based on the posted login information
483    *
484    * @return string Selected IMAP host
485    */
486   public function autoselect_host()
487   {
488     $default_host = $this->config->get('default_host');
257f88 489     $host = null;
1854c4 490     
257f88 491     if (is_array($default_host)) {
T 492       $post_host = get_input_value('_host', RCUBE_INPUT_POST);
493       
494       // direct match in default_host array
495       if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
496         $host = $post_host;
497       }
498       
499       // try to select host by mail domain
1854c4 500       list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
T 501       if (!empty($domain)) {
257f88 502         foreach ($default_host as $imap_host => $mail_domains) {
1854c4 503           if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
T 504             $host = $imap_host;
505             break;
506           }
507         }
508       }
509
510       // take the first entry if $host is still an array
257f88 511       if (empty($host)) {
T 512         $host = array_shift($default_host);
513       }
514     }
515     else if (empty($default_host)) {
516       $host = get_input_value('_host', RCUBE_INPUT_POST);
1854c4 517     }
eec34e 518     else
T 519       $host = $default_host;
1854c4 520
T 521     return $host;
522   }
523
524
525   /**
526    * Get localized text in the desired language
527    *
528    * @param mixed Named parameters array or label name
529    * @return string Localized text
530    */
531   public function gettext($attrib)
532   {
533     // load localization files if not done yet
534     if (empty($this->texts))
535       $this->load_language();
536     
537     // extract attributes
538     if (is_string($attrib))
539       $attrib = array('name' => $attrib);
540
541     $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
542     $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
543
544     $command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
545     $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
546
547     // text does not exist
548     if (!($text_item = $this->texts[$alias])) {
549       /*
550       raise_error(array(
551         'code' => 500,
552         'type' => 'php',
553         'line' => __LINE__,
554         'file' => __FILE__,
555         'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
556       */
557       return "[$alias]";
558     }
559
560     // make text item array 
561     $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
562
563     // decide which text to use
564     if ($nr == 1) {
565       $text = $a_text_item['single'];
566     }
567     else if ($nr > 0) {
568       $text = $a_text_item['multiple'];
569     }
570     else if ($nr == 0) {
571       if ($a_text_item['none'])
572         $text = $a_text_item['none'];
573       else if ($a_text_item['single'])
574         $text = $a_text_item['single'];
575       else if ($a_text_item['multiple'])
576         $text = $a_text_item['multiple'];
577     }
578
579     // default text is single
580     if ($text == '') {
581       $text = $a_text_item['single'];
582     }
583
584     // replace vars in text
585     if (is_array($attrib['vars'])) {
586       foreach ($attrib['vars'] as $var_key => $var_value)
587         $a_replace_vars[$var_key{0}=='$' ? substr($var_key, 1) : $var_key] = $var_value;
588     }
589
590     if ($a_replace_vars)
591       $text = preg_replace('/\$\{?([_a-z]{1}[_a-z0-9]*)\}?/ei', '$a_replace_vars["\1"]', $text);
592
593     // format output
594     if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
595       return ucfirst($text);
596     else if ($attrib['uppercase'])
597       return strtoupper($text);
598     else if ($attrib['lowercase'])
599       return strtolower($text);
600
601     return $text;
602   }
603
604
605   /**
606    * Load a localization package
607    *
608    * @param string Language ID
609    */
610   public function load_language($lang = null)
611   {
612     $lang = $lang ? $this->language_prop($lang) : $_SESSION['language'];
613     
614     // load localized texts
615     if (empty($this->texts) || $lang != $_SESSION['language']) {
616       $this->texts = array();
617
618       // get english labels (these should be complete)
619       @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
620       @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
621
622       if (is_array($labels))
9d9f8d 623         $this->texts = $labels;
1854c4 624       if (is_array($messages))
9d9f8d 625         $this->texts = array_merge($this->texts, $messages);
1854c4 626
T 627       // include user language files
628       if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
629         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
630         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
631
632         if (is_array($labels))
633           $this->texts = array_merge($this->texts, $labels);
634         if (is_array($messages))
635           $this->texts = array_merge($this->texts, $messages);
636       }
637       
638       $_SESSION['language'] = $lang;
639     }
640   }
641
642
643   /**
644    * Read directory program/localization and return a list of available languages
645    *
646    * @return array List of available localizations
647    */
648   public function list_languages()
649   {
650     static $sa_languages = array();
651
652     if (!sizeof($sa_languages)) {
653       @include(INSTALL_PATH . 'program/localization/index.inc');
654
655       if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
656         while (($name = readdir($dh)) !== false) {
657           if ($name{0}=='.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
658             continue;
659
660           if ($label = $rcube_languages[$name])
661             $sa_languages[$name] = $label ? $label : $name;
662         }
663         closedir($dh);
664       }
665     }
666
667     return $sa_languages;
668   }
669
670
671   /**
672    * Check the auth hash sent by the client against the local session credentials
673    *
674    * @return boolean True if valid, False if not
675    */
676   function authenticate_session()
677   {
678     global $SESS_CLIENT_IP, $SESS_CHANGED;
679
680     // advanced session authentication
681     if ($this->config->get('double_auth')) {
682       $now = time();
683       $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
684                 $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
685
686       // renew auth cookie every 5 minutes (only for GET requests)
687       if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
688         $_SESSION['last_auth'] = $_SESSION['auth_time'];
689         $_SESSION['auth_time'] = $now;
690         setcookie('sessauth', $this->get_auth_hash(session_id(), $now));
691       }
692     }
693     else {
694       $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
695     }
696
697     // check session filetime
698     $lifetime = $this->config->get('session_lifetime');
699     if (!empty($lifetime) && isset($SESS_CHANGED) && $SESS_CHANGED + $lifetime*60 < time()) {
700       $valid = false;
701     }
702
703     return $valid;
704   }
705
706
707   /**
708    * Destroy session data and remove cookie
709    */
710   public function kill_session()
711   {
712     $user_prefs = $this->user->get_prefs();
713     
714     if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col'] != $user_prefs['message_sort_col']) ||
715         (isset($_SESSION['sort_order']) && $_SESSION['sort_order'] != $user_prefs['message_sort_order'])) {
716       $this->user->save_prefs(array('message_sort_col' => $_SESSION['sort_col'], 'message_sort_order' => $_SESSION['sort_order']));
717     }
718
719     $_SESSION = array('language' => $USER->language, 'auth_time' => time(), 'temp' => true);
720     setcookie('sessauth', '-del-', time() - 60);
721     $this->user->reset();
722   }
723
724
725   /**
726    * Do server side actions on logout
727    */
728   public function logout_actions()
729   {
730     $config = $this->config->all();
731     
732     // on logout action we're not connected to imap server  
733     if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
734       if (!$this->authenticate_session())
735         return;
736
737       $this->imap_init(true);
738     }
739
740     if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
741       $this->imap->clear_mailbox($config['trash_mbox']);
742     }
743
744     if ($config['logout_expunge']) {
745       $this->imap->expunge('INBOX');
746     }
747   }
748
749
750   /**
751    * Function to be executed in script shutdown
752    * Registered with register_shutdown_function()
753    */
197601 754   public function shutdown()
T 755   {
756     if (is_object($this->imap)) {
757       $this->imap->close();
758       $this->imap->write_cache();
759     }
760
761     if (is_object($this->contacts))
762       $this->contacts->close();
763
764     // before closing the database connection, write session data
75da0b 765     if ($_SERVER['REMOTE_ADDR'])
A 766       session_write_close();
197601 767   }
T 768   
1854c4 769   
T 770   /**
771    * Create unique authorization hash
772    *
773    * @param string Session ID
774    * @param int Timestamp
775    * @return string The generated auth hash
776    */
777   private function get_auth_hash($sess_id, $ts)
778   {
779     $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
780       $sess_id,
781       $ts,
782       $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
783       $_SERVER['HTTP_USER_AGENT']);
784
785     if (function_exists('sha1'))
786       return sha1($auth_string);
787     else
788       return md5($auth_string);
789   }
790
791   /**
792    * Encrypt IMAP password using DES encryption
793    *
794    * @param string Password to encrypt
795    * @return string Encryprted string
796    */
26539d 797   public function encrypt_passwd($pass)
1854c4 798   {
T 799     if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
800       $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
801       mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
802       $cypher = mcrypt_generic($td, $pass);
803       mcrypt_generic_deinit($td);
804       mcrypt_module_close($td);
805     }
806     else if (function_exists('des')) {
807       $cypher = des($this->config->get_des_key(), $pass, 1, 0, NULL);
808     }
809     else {
810       $cypher = $pass;
811
812       raise_error(array(
813         'code' => 500,
814         'type' => 'php',
815         'file' => __FILE__,
816         'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
817         ), true, false);
818     }
819
820     return base64_encode($cypher);
821   }
822
823
824   /**
825    * Decrypt IMAP password using DES encryption
826    *
827    * @param string Encrypted password
828    * @return string Plain password
829    */
830   public function decrypt_passwd($cypher)
831   {
832     if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
833       $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
834       mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
835       $pass = mdecrypt_generic($td, base64_decode($cypher));
836       mcrypt_generic_deinit($td);
837       mcrypt_module_close($td);
838     }
839     else if (function_exists('des')) {
840       $pass = des($this->config->get_des_key(), base64_decode($cypher), 0, 0, NULL);
841     }
842     else {
843       $pass = base64_decode($cypher);
844     }
845
846     return preg_replace('/\x00/', '', $pass);
847   }
848
c719f3 849
T 850   /**
851    * Build a valid URL to this instance of RoundCube
852    *
853    * @param mixed Either a string with the action or url parameters as key-value pairs
854    * @return string Valid application URL
855    */
856   public function url($p)
857   {
858     if (!is_array($p))
fde466 859       $p = array('_action' => @func_get_arg(0));
c719f3 860     
fde466 861     if ($p['task'] && in_array($p['task'], rcmail::$main_tasks))
T 862       $url = './?_task='.$p['task'];
863     else
864       $url = $this->comm_path;
865     
866     unset($p['task']);
c719f3 867     foreach ($p as $par => $val)
e3fdcf 868       if (isset($val))
T 869         $url .= '&'.urlencode($par).'='.urlencode($val);
c719f3 870     
T 871     return $url;
872   }
197601 873 }
T 874
875