source: github/program/include/rcmail.php @ 0c25968

HEADcourier-fixdev-browser-capabilitiespdo
Last change on this file since 0c25968 was 0c25968, checked in by alecpl <alec@…>, 14 months ago
  • Merge devel-framework branch, resolved conflicts
  • Property mode set to 100644
File size: 39.4 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcmail.php                                            |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2008-2012, The Roundcube Dev Team                       |
9 | Copyright (C) 2011-2012, Kolab Systems AG                             |
10 |                                                                       |
11 | Licensed under the GNU General Public License version 3 or            |
12 | any later version with exceptions for skins & plugins.                |
13 | See the README file for a full license statement.                     |
14 |                                                                       |
15 | PURPOSE:                                                              |
16 |   Application class providing core functions and holding              |
17 |   instances of all 'global' objects like db- and imap-connections     |
18 +-----------------------------------------------------------------------+
19 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
20 +-----------------------------------------------------------------------+
21
22 $Id$
23
24*/
25
26
27/**
28 * Application class of Roundcube Webmail
29 * implemented as singleton
30 *
31 * @package Core
32 */
33class rcmail extends rcube
34{
35  /**
36   * Main tasks.
37   *
38   * @var array
39   */
40  static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
41
42  /**
43   * Current task.
44   *
45   * @var string
46   */
47  public $task;
48
49  /**
50   * Current action.
51   *
52   * @var string
53   */
54  public $action = '';
55  public $comm_path = './';
56
57  private $address_books = array();
58  private $action_map = array();
59
60
61  /**
62   * This implements the 'singleton' design pattern
63   *
64   * @return rcmail The one and only instance
65   */
66  static function get_instance()
67  {
68    if (!self::$instance || !is_a(self::$instance, 'rcmail')) {
69      self::$instance = new rcmail();
70      self::$instance->startup();  // init AFTER object was linked with self::$instance
71    }
72
73    return self::$instance;
74  }
75
76
77  /**
78   * Initial startup function
79   * to register session, create database and imap connections
80   */
81  protected function startup()
82  {
83    $this->init(self::INIT_WITH_DB | self::INIT_WITH_PLUGINS);
84
85    // start session
86    $this->session_init();
87
88    // create user object
89    $this->set_user(new rcube_user($_SESSION['user_id']));
90
91    // configure session (after user config merge!)
92    $this->session_configure();
93
94    // set task and action properties
95    $this->set_task(rcube_ui::get_input_value('_task', rcube_ui::INPUT_GPC));
96    $this->action = asciiwords(rcube_ui::get_input_value('_action', rcube_ui::INPUT_GPC));
97
98    // reset some session parameters when changing task
99    if ($this->task != 'utils') {
100      if ($this->session && $_SESSION['task'] != $this->task)
101        $this->session->remove('page');
102      // set current task to session
103      $_SESSION['task'] = $this->task;
104    }
105
106    // init output class
107    if (!empty($_REQUEST['_remote']))
108      $GLOBALS['OUTPUT'] = $this->json_init();
109    else
110      $GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
111
112    // load plugins
113    $this->plugins->init($this, $this->task);
114    $this->plugins->load_plugins((array)$this->config->get('plugins', array()), array('filesystem_attachments', 'jqueryui'));
115  }
116
117
118  /**
119   * Setter for application task
120   *
121   * @param string Task to set
122   */
123  public function set_task($task)
124  {
125    $task = asciiwords($task);
126
127    if ($this->user && $this->user->ID)
128      $task = !$task ? 'mail' : $task;
129    else
130      $task = 'login';
131
132    $this->task = $task;
133    $this->comm_path = $this->url(array('task' => $this->task));
134
135    if ($this->output)
136      $this->output->set_env('task', $this->task);
137  }
138
139
140  /**
141   * Setter for system user object
142   *
143   * @param rcube_user Current user instance
144   */
145  public function set_user($user)
146  {
147    if (is_object($user)) {
148      $this->user = $user;
149
150      // overwrite config with user preferences
151      $this->config->set_user_prefs((array)$this->user->get_prefs());
152    }
153
154    $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
155
156    // set localization
157    setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
158
159    // workaround for http://bugs.php.net/bug.php?id=18556
160    if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
161      setlocale(LC_CTYPE, 'en_US' . '.utf8');
162  }
163
164
165  /**
166   * Return instance of the internal address book class
167   *
168   * @param string  Address book identifier
169   * @param boolean True if the address book needs to be writeable
170   *
171   * @return rcube_contacts Address book object
172   */
173  public function get_address_book($id, $writeable = false)
174  {
175    $contacts    = null;
176    $ldap_config = (array)$this->config->get('ldap_public');
177    $abook_type  = strtolower($this->config->get('address_book_type'));
178
179    // 'sql' is the alias for '0' used by autocomplete
180    if ($id == 'sql')
181        $id = '0';
182
183    // use existing instance
184    if (isset($this->address_books[$id]) && is_object($this->address_books[$id])
185      && is_a($this->address_books[$id], 'rcube_addressbook')
186      && (!$writeable || !$this->address_books[$id]->readonly)
187    ) {
188      $contacts = $this->address_books[$id];
189    }
190    else if ($id && $ldap_config[$id]) {
191      $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['storage_host']));
192    }
193    else if ($id === '0') {
194      $contacts = new rcube_contacts($this->db, $this->get_user_id());
195    }
196    else {
197      $plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
198
199      // plugin returned instance of a rcube_addressbook
200      if ($plugin['instance'] instanceof rcube_addressbook) {
201        $contacts = $plugin['instance'];
202      }
203      // get first source from the list
204      else if (!$id) {
205        $source = reset($this->get_address_sources($writeable));
206        if (!empty($source)) {
207          $contacts = $this->get_address_book($source['id']);
208          if ($contacts)
209            $id = $source['id'];
210        }
211      }
212    }
213
214    if (!$contacts) {
215      self::raise_error(array(
216        'code' => 700, 'type' => 'php',
217        'file' => __FILE__, 'line' => __LINE__,
218        'message' => "Addressbook source ($id) not found!"),
219        true, true);
220    }
221
222    // set configured sort order
223    if ($sort_col = $this->config->get('addressbook_sort_col'))
224        $contacts->set_sort_order($sort_col);
225
226    // add to the 'books' array for shutdown function
227    $this->address_books[$id] = $contacts;
228
229    return $contacts;
230  }
231
232
233  /**
234   * Return address books list
235   *
236   * @param boolean True if the address book needs to be writeable
237   *
238   * @return array  Address books array
239   */
240  public function get_address_sources($writeable = false)
241  {
242    $abook_type = strtolower($this->config->get('address_book_type'));
243    $ldap_config = $this->config->get('ldap_public');
244    $autocomplete = (array) $this->config->get('autocomplete_addressbooks');
245    $list = array();
246
247    // We are using the DB address book
248    if ($abook_type != 'ldap') {
249      if (!isset($this->address_books['0']))
250        $this->address_books['0'] = new rcube_contacts($this->db, $this->get_user_id());
251      $list['0'] = array(
252        'id'       => '0',
253        'name'     => $this->gettext('personaladrbook'),
254        'groups'   => $this->address_books['0']->groups,
255        'readonly' => $this->address_books['0']->readonly,
256        'autocomplete' => in_array('sql', $autocomplete),
257        'undelete' => $this->address_books['0']->undelete && $this->config->get('undo_timeout'),
258      );
259    }
260
261    if ($ldap_config) {
262      $ldap_config = (array) $ldap_config;
263      foreach ($ldap_config as $id => $prop) {
264        // handle misconfiguration
265        if (empty($prop) || !is_array($prop)) {
266          continue;
267        }
268        $list[$id] = array(
269          'id'       => $id,
270          'name'     => $prop['name'],
271          'groups'   => is_array($prop['groups']),
272          'readonly' => !$prop['writable'],
273          'hidden'   => $prop['hidden'],
274          'autocomplete' => in_array($id, $autocomplete)
275        );
276      }
277    }
278
279    $plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
280    $list = $plugin['sources'];
281
282    foreach ($list as $idx => $item) {
283      // register source for shutdown function
284      if (!is_object($this->address_books[$item['id']]))
285        $this->address_books[$item['id']] = $item;
286      // remove from list if not writeable as requested
287      if ($writeable && $item['readonly'])
288          unset($list[$idx]);
289    }
290
291    return $list;
292  }
293
294
295  /**
296   * Init output object for GUI and add common scripts.
297   * This will instantiate a rcmail_template object and set
298   * environment vars according to the current session and configuration
299   *
300   * @param boolean True if this request is loaded in a (i)frame
301   * @return rcube_output_html Reference to HTML output object
302   */
303  public function load_gui($framed = false)
304  {
305    // init output page
306    if (!($this->output instanceof rcube_output_html))
307      $this->output = new rcube_output_html($this->task, $framed);
308
309    // set keep-alive/check-recent interval
310    if ($this->session && ($keep_alive = $this->session->get_keep_alive())) {
311      $this->output->set_env('keep_alive', $keep_alive);
312    }
313
314    if ($framed) {
315      $this->comm_path .= '&_framed=1';
316      $this->output->set_env('framed', true);
317    }
318
319    $this->output->set_env('task', $this->task);
320    $this->output->set_env('action', $this->action);
321    $this->output->set_env('comm_path', $this->comm_path);
322    $this->output->set_charset(RCMAIL_CHARSET);
323
324    // add some basic labels to client
325    $this->output->add_label('loading', 'servererror');
326
327    return $this->output;
328  }
329
330
331  /**
332   * Create an output object for JSON responses
333   *
334   * @return rcube_output_json Reference to JSON output object
335   */
336  public function json_init()
337  {
338    if (!($this->output instanceof rcube_output_json))
339      $this->output = new rcube_output_json($this->task);
340
341    return $this->output;
342  }
343
344
345  /**
346   * Create session object and start the session.
347   */
348  public function session_init()
349  {
350    // session started (Installer?)
351    if (session_id())
352      return;
353
354    $sess_name   = $this->config->get('session_name');
355    $sess_domain = $this->config->get('session_domain');
356    $lifetime    = $this->config->get('session_lifetime', 0) * 60;
357
358    // set session domain
359    if ($sess_domain) {
360      ini_set('session.cookie_domain', $sess_domain);
361    }
362    // set session garbage collecting time according to session_lifetime
363    if ($lifetime) {
364      ini_set('session.gc_maxlifetime', $lifetime * 2);
365    }
366
367    ini_set('session.cookie_secure', rcube_ui::https_check());
368    ini_set('session.name', $sess_name ? $sess_name : 'roundcube_sessid');
369    ini_set('session.use_cookies', 1);
370    ini_set('session.use_only_cookies', 1);
371    ini_set('session.serialize_handler', 'php');
372
373    // use database for storing session data
374    $this->session = new rcube_session($this->get_dbh(), $this->config);
375
376    $this->session->register_gc_handler(array($this, 'temp_gc'));
377    $this->session->register_gc_handler(array($this, 'cache_gc'));
378
379    // start PHP session (if not in CLI mode)
380    if ($_SERVER['REMOTE_ADDR'])
381      session_start();
382
383    // set initial session vars
384    if (!$_SESSION['user_id'])
385      $_SESSION['temp'] = true;
386
387    // restore skin selection after logout
388    if ($_SESSION['temp'] && !empty($_SESSION['skin']))
389      $this->config->set('skin', $_SESSION['skin']);
390  }
391
392
393  /**
394   * Configure session object internals
395   */
396  public function session_configure()
397  {
398    if (!$this->session)
399      return;
400
401    $lifetime = $this->config->get('session_lifetime', 0) * 60;
402
403    // set keep-alive/check-recent interval
404    if ($keep_alive = $this->config->get('keep_alive')) {
405      // be sure that it's less than session lifetime
406      if ($lifetime)
407        $keep_alive = min($keep_alive, $lifetime - 30);
408      $keep_alive = max(60, $keep_alive);
409      $this->session->set_keep_alive($keep_alive);
410    }
411
412    $this->session->set_secret($this->config->get('des_key') . $_SERVER['HTTP_USER_AGENT']);
413    $this->session->set_ip_check($this->config->get('ip_check'));
414  }
415
416
417  /**
418   * Perfom login to the mail server and to the webmail service.
419   * This will also create a new user entry if auto_create_user is configured.
420   *
421   * @param string Mail storage (IMAP) user name
422   * @param string Mail storage (IMAP) password
423   * @param string Mail storage (IMAP) host
424   *
425   * @return boolean True on success, False on failure
426   */
427  function login($username, $pass, $host=NULL)
428  {
429    if (empty($username)) {
430      return false;
431    }
432
433    $config = $this->config->all();
434
435    if (!$host)
436      $host = $config['default_host'];
437
438    // Validate that selected host is in the list of configured hosts
439    if (is_array($config['default_host'])) {
440      $allowed = false;
441      foreach ($config['default_host'] as $key => $host_allowed) {
442        if (!is_numeric($key))
443          $host_allowed = $key;
444        if ($host == $host_allowed) {
445          $allowed = true;
446          break;
447        }
448      }
449      if (!$allowed)
450        return false;
451      }
452    else if (!empty($config['default_host']) && $host != self::parse_host($config['default_host']))
453      return false;
454
455    // parse $host URL
456    $a_host = parse_url($host);
457    if ($a_host['host']) {
458      $host = $a_host['host'];
459      $ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
460      if (!empty($a_host['port']))
461        $port = $a_host['port'];
462      else if ($ssl && $ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
463        $port = 993;
464    }
465
466    if (!$port) {
467        $port = $config['default_port'];
468    }
469
470    /* Modify username with domain if required
471       Inspired by Marco <P0L0_notspam_binware.org>
472    */
473    // Check if we need to add domain
474    if (!empty($config['username_domain']) && strpos($username, '@') === false) {
475      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
476        $username .= '@'.self::parse_host($config['username_domain'][$host], $host);
477      else if (is_string($config['username_domain']))
478        $username .= '@'.self::parse_host($config['username_domain'], $host);
479    }
480
481    // Convert username to lowercase. If storage backend
482    // is case-insensitive we need to store always the same username (#1487113)
483    if ($config['login_lc']) {
484      $username = mb_strtolower($username);
485    }
486
487    // try to resolve email address from virtuser table
488    if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
489      $username = $virtuser;
490    }
491
492    // Here we need IDNA ASCII
493    // Only rcube_contacts class is using domain names in Unicode
494    $host = rcube_idn_to_ascii($host);
495    if (strpos($username, '@')) {
496      // lowercase domain name
497      list($local, $domain) = explode('@', $username);
498      $username = $local . '@' . mb_strtolower($domain);
499      $username = rcube_idn_to_ascii($username);
500    }
501
502    // user already registered -> overwrite username
503    if ($user = rcube_user::query($username, $host))
504      $username = $user->data['username'];
505
506    if (!$this->storage)
507      $this->storage_init();
508
509    // try to log in
510    if (!($login = $this->storage->connect($host, $username, $pass, $port, $ssl))) {
511      // try with lowercase
512      $username_lc = mb_strtolower($username);
513      if ($username_lc != $username) {
514        // try to find user record again -> overwrite username
515        if (!$user && ($user = rcube_user::query($username_lc, $host)))
516          $username_lc = $user->data['username'];
517
518        if ($login = $this->storage->connect($host, $username_lc, $pass, $port, $ssl))
519          $username = $username_lc;
520      }
521    }
522
523    // exit if login failed
524    if (!$login) {
525      return false;
526    }
527
528    // user already registered -> update user's record
529    if (is_object($user)) {
530      // update last login timestamp
531      $user->touch();
532    }
533    // create new system user
534    else if ($config['auto_create_user']) {
535      if ($created = rcube_user::create($username, $host)) {
536        $user = $created;
537      }
538      else {
539        self::raise_error(array(
540          'code' => 620, 'type' => 'php',
541          'file' => __FILE__, 'line' => __LINE__,
542          'message' => "Failed to create a user record. Maybe aborted by a plugin?"
543          ), true, false);
544      }
545    }
546    else {
547      self::raise_error(array(
548        'code' => 621, 'type' => 'php',
549        'file' => __FILE__, 'line' => __LINE__,
550        'message' => "Access denied for new user $username. 'auto_create_user' is disabled"
551        ), true, false);
552    }
553
554    // login succeeded
555    if (is_object($user) && $user->ID) {
556      // Configure environment
557      $this->set_user($user);
558      $this->set_storage_prop();
559      $this->session_configure();
560
561      // fix some old settings according to namespace prefix
562      $this->fix_namespace_settings($user);
563
564      // create default folders on first login
565      if ($config['create_default_folders'] && (!empty($created) || empty($user->data['last_login']))) {
566        $this->storage->create_default_folders();
567      }
568
569      // set session vars
570      $_SESSION['user_id']      = $user->ID;
571      $_SESSION['username']     = $user->data['username'];
572      $_SESSION['storage_host'] = $host;
573      $_SESSION['storage_port'] = $port;
574      $_SESSION['storage_ssl']  = $ssl;
575      $_SESSION['password']     = $this->encrypt($pass);
576      $_SESSION['login_time']   = mktime();
577
578      if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
579        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
580      if (isset($_REQUEST['_dstactive']) && $_REQUEST['_dstactive'] != '_default_')
581        $_SESSION['dst_active'] = intval($_REQUEST['_dstactive']);
582
583      // force reloading complete list of subscribed mailboxes
584      $this->storage->clear_cache('mailboxes', true);
585
586      return true;
587    }
588
589    return false;
590  }
591
592
593  /**
594   * Auto-select IMAP host based on the posted login information
595   *
596   * @return string Selected IMAP host
597   */
598  public function autoselect_host()
599  {
600    $default_host = $this->config->get('default_host');
601    $host = null;
602
603    if (is_array($default_host)) {
604      $post_host = rcube_ui::get_input_value('_host', rcube_ui::INPUT_POST);
605
606      // direct match in default_host array
607      if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
608        $host = $post_host;
609      }
610
611      // try to select host by mail domain
612      list($user, $domain) = explode('@', rcube_ui::get_input_value('_user', rcube_ui::INPUT_POST));
613      if (!empty($domain)) {
614        foreach ($default_host as $storage_host => $mail_domains) {
615          if (is_array($mail_domains) && in_array_nocase($domain, $mail_domains)) {
616            $host = $storage_host;
617            break;
618          }
619          else if (stripos($storage_host, $domain) !== false || stripos(strval($mail_domains), $domain) !== false) {
620            $host = is_numeric($storage_host) ? $mail_domains : $storage_host;
621            break;
622          }
623        }
624      }
625
626      // take the first entry if $host is still not set
627      if (empty($host)) {
628        list($key, $val) = each($default_host);
629        $host = is_numeric($key) ? $val : $key;
630      }
631    }
632    else if (empty($default_host)) {
633      $host = rcube_ui::get_input_value('_host', rcube_ui::INPUT_POST);
634    }
635    else
636      $host = self::parse_host($default_host);
637
638    return $host;
639  }
640
641
642  /**
643   * Destroy session data and remove cookie
644   */
645  public function kill_session()
646  {
647    $this->plugins->exec_hook('session_destroy');
648
649    $this->session->kill();
650    $_SESSION = array('language' => $this->user->language, 'temp' => true, 'skin' => $this->config->get('skin'));
651    $this->user->reset();
652  }
653
654
655  /**
656   * Do server side actions on logout
657   */
658  public function logout_actions()
659  {
660    $config = $this->config->all();
661
662    // on logout action we're not connected to imap server
663    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
664      if (!$this->session->check_auth())
665        return;
666
667      $this->storage_connect();
668    }
669
670    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
671      $this->storage->clear_folder($config['trash_mbox']);
672    }
673
674    if ($config['logout_expunge']) {
675      $this->storage->expunge_folder('INBOX');
676    }
677
678    // Try to save unsaved user preferences
679    if (!empty($_SESSION['preferences'])) {
680      $this->user->save_prefs(unserialize($_SESSION['preferences']));
681    }
682  }
683
684
685  /**
686   * Garbage collector for cache entries.
687   * Set flag to expunge caches on shutdown
688   */
689  function cache_gc()
690  {
691    // because this gc function is called before storage is initialized,
692    // we just set a flag to expunge storage cache on shutdown.
693    $this->expunge_cache = true;
694  }
695
696
697  /**
698   * Generate a unique token to be used in a form request
699   *
700   * @return string The request token
701   */
702  public function get_request_token()
703  {
704    $sess_id = $_COOKIE[ini_get('session.name')];
705    if (!$sess_id) $sess_id = session_id();
706    $plugin = $this->plugins->exec_hook('request_token', array('value' => md5('RT' . $this->get_user_id() . $this->config->get('des_key') . $sess_id)));
707    return $plugin['value'];
708  }
709
710
711  /**
712   * Check if the current request contains a valid token
713   *
714   * @param int Request method
715   * @return boolean True if request token is valid false if not
716   */
717  public function check_request($mode = rcube_ui::INPUT_POST)
718  {
719    $token = rcube_ui::get_input_value('_token', $mode);
720    $sess_id = $_COOKIE[ini_get('session.name')];
721    return !empty($sess_id) && $token == $this->get_request_token();
722  }
723
724
725  /**
726   * Create unique authorization hash
727   *
728   * @param string Session ID
729   * @param int Timestamp
730   * @return string The generated auth hash
731   */
732  private function get_auth_hash($sess_id, $ts)
733  {
734    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
735      $sess_id,
736      $ts,
737      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
738      $_SERVER['HTTP_USER_AGENT']);
739
740    if (function_exists('sha1'))
741      return sha1($auth_string);
742    else
743      return md5($auth_string);
744  }
745
746
747  /**
748   * Build a valid URL to this instance of Roundcube
749   *
750   * @param mixed Either a string with the action or url parameters as key-value pairs
751   * @return string Valid application URL
752   */
753  public function url($p)
754  {
755    if (!is_array($p))
756      $p = array('_action' => @func_get_arg(0));
757
758    $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
759    $p['_task'] = $task;
760    unset($p['task']);
761
762    $url = './';
763    $delm = '?';
764    foreach (array_reverse($p) as $key => $val) {
765      if ($val !== '' && $val !== null) {
766        $par = $key[0] == '_' ? $key : '_'.$key;
767        $url .= $delm.urlencode($par).'='.urlencode($val);
768        $delm = '&';
769      }
770    }
771    return $url;
772  }
773
774
775  /**
776   * Function to be executed in script shutdown
777   */
778  public function shutdown()
779  {
780    parent::shutdown();
781
782    foreach ($this->address_books as $book) {
783      if (is_object($book) && is_a($book, 'rcube_addressbook'))
784        $book->close();
785    }
786
787    // before closing the database connection, write session data
788    if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
789      session_write_close();
790    }
791
792    // write performance stats to logs/console
793    if ($this->config->get('devel_mode')) {
794      if (function_exists('memory_get_usage'))
795        $mem = rcube_ui::show_bytes(memory_get_usage());
796      if (function_exists('memory_get_peak_usage'))
797        $mem .= '/'.rcube_ui::show_bytes(memory_get_peak_usage());
798
799      $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
800      if (defined('RCMAIL_START'))
801        self::print_timer(RCMAIL_START, $log);
802      else
803        self::console($log);
804    }
805  }
806
807  /**
808   * Helper method to set a cookie with the current path and host settings
809   *
810   * @param string Cookie name
811   * @param string Cookie value
812   * @param string Expiration time
813   */
814  public static function setcookie($name, $value, $exp = 0)
815  {
816    if (headers_sent())
817      return;
818
819    $cookie = session_get_cookie_params();
820
821    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
822      rcube_ui::https_check(), true);
823  }
824
825  /**
826   * Registers action aliases for current task
827   *
828   * @param array $map Alias-to-filename hash array
829   */
830  public function register_action_map($map)
831  {
832    if (is_array($map)) {
833      foreach ($map as $idx => $val) {
834        $this->action_map[$idx] = $val;
835      }
836    }
837  }
838
839  /**
840   * Returns current action filename
841   *
842   * @param array $map Alias-to-filename hash array
843   */
844  public function get_action_file()
845  {
846    if (!empty($this->action_map[$this->action])) {
847      return $this->action_map[$this->action];
848    }
849
850    return strtr($this->action, '-', '_') . '.inc';
851  }
852
853  /**
854   * Fixes some user preferences according to namespace handling change.
855   * Old Roundcube versions were using folder names with removed namespace prefix.
856   * Now we need to add the prefix on servers where personal namespace has prefix.
857   *
858   * @param rcube_user $user User object
859   */
860  private function fix_namespace_settings($user)
861  {
862    $prefix     = $this->storage->get_namespace('prefix');
863    $prefix_len = strlen($prefix);
864
865    if (!$prefix_len)
866      return;
867
868    $prefs = $this->config->all();
869    if (!empty($prefs['namespace_fixed']))
870      return;
871
872    // Build namespace prefix regexp
873    $ns     = $this->storage->get_namespace();
874    $regexp = array();
875
876    foreach ($ns as $entry) {
877      if (!empty($entry)) {
878        foreach ($entry as $item) {
879          if (strlen($item[0])) {
880            $regexp[] = preg_quote($item[0], '/');
881          }
882        }
883      }
884    }
885    $regexp = '/^('. implode('|', $regexp).')/';
886
887    // Fix preferences
888    $opts = array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox', 'archive_mbox');
889    foreach ($opts as $opt) {
890      if ($value = $prefs[$opt]) {
891        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
892          $prefs[$opt] = $prefix.$value;
893        }
894      }
895    }
896
897    if (!empty($prefs['default_folders'])) {
898      foreach ($prefs['default_folders'] as $idx => $name) {
899        if ($name != 'INBOX' && !preg_match($regexp, $name)) {
900          $prefs['default_folders'][$idx] = $prefix.$name;
901        }
902      }
903    }
904
905    if (!empty($prefs['search_mods'])) {
906      $folders = array();
907      foreach ($prefs['search_mods'] as $idx => $value) {
908        if ($idx != 'INBOX' && $idx != '*' && !preg_match($regexp, $idx)) {
909          $idx = $prefix.$idx;
910        }
911        $folders[$idx] = $value;
912      }
913      $prefs['search_mods'] = $folders;
914    }
915
916    if (!empty($prefs['message_threading'])) {
917      $folders = array();
918      foreach ($prefs['message_threading'] as $idx => $value) {
919        if ($idx != 'INBOX' && !preg_match($regexp, $idx)) {
920          $idx = $prefix.$idx;
921        }
922        $folders[$prefix.$idx] = $value;
923      }
924      $prefs['message_threading'] = $folders;
925    }
926
927    if (!empty($prefs['collapsed_folders'])) {
928      $folders     = explode('&&', $prefs['collapsed_folders']);
929      $count       = count($folders);
930      $folders_str = '';
931
932      if ($count) {
933          $folders[0]        = substr($folders[0], 1);
934          $folders[$count-1] = substr($folders[$count-1], 0, -1);
935      }
936
937      foreach ($folders as $value) {
938        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
939          $value = $prefix.$value;
940        }
941        $folders_str .= '&'.$value.'&';
942      }
943      $prefs['collapsed_folders'] = $folders_str;
944    }
945
946    $prefs['namespace_fixed'] = true;
947
948    // save updated preferences and reset imap settings (default folders)
949    $user->save_prefs($prefs);
950    $this->set_storage_prop();
951  }
952
953
954    /**
955     * Overwrite action variable
956     *
957     * @param string New action value
958     */
959    public function overwrite_action($action)
960    {
961        $this->action = $action;
962        $this->output->set_env('action', $action);
963    }
964
965
966    /**
967     * Send the given message using the configured method.
968     *
969     * @param object $message    Reference to Mail_MIME object
970     * @param string $from       Sender address string
971     * @param array  $mailto     Array of recipient address strings
972     * @param array  $smtp_error SMTP error array (reference)
973     * @param string $body_file  Location of file with saved message body (reference),
974     *                           used when delay_file_io is enabled
975     * @param array  $smtp_opts  SMTP options (e.g. DSN request)
976     *
977     * @return boolean Send status.
978     */
979    public function deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file = null, $smtp_opts = null)
980    {
981        $headers = $message->headers();
982
983        // send thru SMTP server using custom SMTP library
984        if ($this->config->get('smtp_server')) {
985            // generate list of recipients
986            $a_recipients = array($mailto);
987
988            if (strlen($headers['Cc']))
989                $a_recipients[] = $headers['Cc'];
990            if (strlen($headers['Bcc']))
991                $a_recipients[] = $headers['Bcc'];
992
993            // clean Bcc from header for recipients
994            $send_headers = $headers;
995            unset($send_headers['Bcc']);
996            // here too, it because txtHeaders() below use $message->_headers not only $send_headers
997            unset($message->_headers['Bcc']);
998
999            $smtp_headers = $message->txtHeaders($send_headers, true);
1000
1001            if ($message->getParam('delay_file_io')) {
1002                // use common temp dir
1003                $temp_dir = $this->config->get('temp_dir');
1004                $body_file = tempnam($temp_dir, 'rcmMsg');
1005                if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1006                    self::raise_error(array('code' => 650, 'type' => 'php',
1007                        'file' => __FILE__, 'line' => __LINE__,
1008                        'message' => "Could not create message: ".$mime_result->getMessage()),
1009                        TRUE, FALSE);
1010                    return false;
1011                }
1012                $msg_body = fopen($body_file, 'r');
1013            }
1014            else {
1015                $msg_body = $message->get();
1016            }
1017
1018            // send message
1019            if (!is_object($this->smtp)) {
1020                $this->smtp_init(true);
1021            }
1022
1023            $sent = $this->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $smtp_opts);
1024            $smtp_response = $this->smtp->get_response();
1025            $smtp_error = $this->smtp->get_error();
1026
1027            // log error
1028            if (!$sent) {
1029                self::raise_error(array('code' => 800, 'type' => 'smtp',
1030                    'line' => __LINE__, 'file' => __FILE__,
1031                    'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1032            }
1033        }
1034        // send mail using PHP's mail() function
1035        else {
1036            // unset some headers because they will be added by the mail() function
1037            $headers_enc = $message->headers($headers);
1038            $headers_php = $message->_headers;
1039            unset($headers_php['To'], $headers_php['Subject']);
1040
1041            // reset stored headers and overwrite
1042            $message->_headers = array();
1043            $header_str = $message->txtHeaders($headers_php);
1044
1045            // #1485779
1046            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1047                if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1048                    $headers_enc['To'] = implode(', ', $m[1]);
1049                }
1050            }
1051
1052            $msg_body = $message->get();
1053
1054            if (PEAR::isError($msg_body)) {
1055                self::raise_error(array('code' => 650, 'type' => 'php',
1056                    'file' => __FILE__, 'line' => __LINE__,
1057                    'message' => "Could not create message: ".$msg_body->getMessage()),
1058                    TRUE, FALSE);
1059            }
1060            else {
1061                $delim   = $this->config->header_delimiter();
1062                $to      = $headers_enc['To'];
1063                $subject = $headers_enc['Subject'];
1064                $header_str = rtrim($header_str);
1065
1066                if ($delim != "\r\n") {
1067                    $header_str = str_replace("\r\n", $delim, $header_str);
1068                    $msg_body   = str_replace("\r\n", $delim, $msg_body);
1069                    $to         = str_replace("\r\n", $delim, $to);
1070                    $subject    = str_replace("\r\n", $delim, $subject);
1071                }
1072
1073                if (ini_get('safe_mode'))
1074                    $sent = mail($to, $subject, $msg_body, $header_str);
1075                else
1076                    $sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
1077            }
1078        }
1079
1080        if ($sent) {
1081            $this->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1082
1083            // remove MDN headers after sending
1084            unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1085
1086            // get all recipients
1087            if ($headers['Cc'])
1088                $mailto .= $headers['Cc'];
1089            if ($headers['Bcc'])
1090                $mailto .= $headers['Bcc'];
1091            if (preg_match_all('/<([^@]+@[^>]+)>/', $mailto, $m))
1092                $mailto = implode(', ', array_unique($m[1]));
1093
1094            if ($this->config->get('smtp_log')) {
1095                self::write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1096                    $this->user->get_username(),
1097                    $_SERVER['REMOTE_ADDR'],
1098                    $mailto,
1099                    !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1100            }
1101        }
1102
1103        if (is_resource($msg_body)) {
1104            fclose($msg_body);
1105        }
1106
1107        $message->_headers = array();
1108        $message->headers($headers);
1109
1110        return $sent;
1111    }
1112
1113
1114    /**
1115     * Unique Message-ID generator.
1116     *
1117     * @return string Message-ID
1118     */
1119    public function gen_message_id()
1120    {
1121        $local_part  = md5(uniqid('rcmail'.mt_rand(),true));
1122        $domain_part = $this->user->get_username('domain');
1123
1124        // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
1125        if (!preg_match('/\.[a-z]+$/i', $domain_part)) {
1126            foreach (array($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']) as $host) {
1127                $host = preg_replace('/:[0-9]+$/', '', $host);
1128                if ($host && preg_match('/\.[a-z]+$/i', $host)) {
1129                    $domain_part = $host;
1130                }
1131            }
1132        }
1133
1134        return sprintf('<%s@%s>', $local_part, $domain_part);
1135    }
1136
1137
1138    /**
1139     * Returns RFC2822 formatted current date in user's timezone
1140     *
1141     * @return string Date
1142     */
1143    public function user_date()
1144    {
1145        // get user's timezone
1146        try {
1147            $tz   = new DateTimeZone($this->config->get('timezone'));
1148            $date = new DateTime('now', $tz);
1149        }
1150        catch (Exception $e) {
1151            $date = new DateTime();
1152        }
1153
1154        return $date->format('r');
1155    }
1156
1157
1158    /**
1159     * E-mail address validation.
1160     *
1161     * @param string $email Email address
1162     * @param boolean $dns_check True to check dns
1163     *
1164     * @return boolean True on success, False if address is invalid
1165     */
1166    public function check_email($email, $dns_check=true)
1167    {
1168        // Check for invalid characters
1169        if (preg_match('/[\x00-\x1F\x7F-\xFF]/', $email)) {
1170            return false;
1171        }
1172
1173        // Check for length limit specified by RFC 5321 (#1486453)
1174        if (strlen($email) > 254) {
1175            return false;
1176        }
1177
1178        $email_array = explode('@', $email);
1179
1180        // Check that there's one @ symbol
1181        if (count($email_array) < 2) {
1182            return false;
1183        }
1184
1185        $domain_part = array_pop($email_array);
1186        $local_part  = implode('@', $email_array);
1187
1188        // from PEAR::Validate
1189        $regexp = '&^(?:
1190                ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")|                                         #1 quoted name
1191                ([-\w!\#\$%\&\'*+~/^`|{}=]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}=]+)*))  #2 OR dot-atom (RFC5322)
1192                $&xi';
1193
1194        if (!preg_match($regexp, $local_part)) {
1195            return false;
1196        }
1197
1198        // Check domain part
1199        if (preg_match('/^\[*(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}\]*$/', $domain_part)) {
1200            return true; // IP address
1201        }
1202        else {
1203            // If not an IP address
1204            $domain_array = explode('.', $domain_part);
1205            // Not enough parts to be a valid domain
1206            if (sizeof($domain_array) < 2) {
1207                return false;
1208            }
1209
1210            foreach ($domain_array as $part) {
1211                if (!preg_match('/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]))$/', $part)) {
1212                    return false;
1213                }
1214            }
1215
1216            if (!$dns_check || !$this->config->get('email_dns_check')) {
1217                return true;
1218            }
1219
1220            if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) {
1221                $lookup = array();
1222                @exec("nslookup -type=MX " . escapeshellarg($domain_part) . " 2>&1", $lookup);
1223                foreach ($lookup as $line) {
1224                    if (strpos($line, 'MX preference')) {
1225                        return true;
1226                    }
1227                }
1228                return false;
1229            }
1230
1231            // find MX record(s)
1232            if (getmxrr($domain_part, $mx_records)) {
1233                return true;
1234            }
1235
1236            // find any DNS record
1237            if (checkdnsrr($domain_part, 'ANY')) {
1238                return true;
1239            }
1240        }
1241
1242        return false;
1243    }
1244
1245
1246    /**
1247     * Write login data (name, ID, IP address) to the 'userlogins' log file.
1248     */
1249    public function log_login()
1250    {
1251        if (!$this->config->get('log_logins')) {
1252            return;
1253        }
1254
1255        $user_name = $this->get_user_name();
1256        $user_id   = $this->get_user_id();
1257
1258        if (!$user_id) {
1259            return;
1260        }
1261
1262        self::write_log('userlogins',
1263            sprintf('Successful login for %s (ID: %d) from %s in session %s',
1264                $user_name, $user_id, self::remote_ip(), session_id()));
1265    }
1266
1267
1268    /**
1269     * Check whether the HTTP referer matches the current request
1270     *
1271     * @return boolean True if referer is the same host+path, false if not
1272     */
1273    public static function check_referer()
1274    {
1275        $uri = parse_url($_SERVER['REQUEST_URI']);
1276        $referer = parse_url(rcube_request_header('Referer'));
1277        return $referer['host'] == rcube_request_header('Host') && $referer['path'] == $uri['path'];
1278    }
1279
1280
1281    /**
1282     * Garbage collector function for temp files.
1283     * Remove temp files older than two days
1284     */
1285    public function temp_gc()
1286    {
1287        $tmp = unslashify($this->config->get('temp_dir'));
1288        $expire = mktime() - 172800;  // expire in 48 hours
1289
1290        if ($dir = opendir($tmp)) {
1291            while (($fname = readdir($dir)) !== false) {
1292                if ($fname{0} == '.') {
1293                    continue;
1294                }
1295
1296                if (filemtime($tmp.'/'.$fname) < $expire) {
1297                    @unlink($tmp.'/'.$fname);
1298                }
1299            }
1300
1301            closedir($dir);
1302        }
1303    }
1304
1305}
Note: See TracBrowser for help on using the repository browser.