source: subversion/trunk/roundcubemail/installer/rcube_install.php @ 4410

Last change on this file since 4410 was 4410, checked in by thomasb, 2 years ago

Bumbed version; Roundcube development is not Switzerland only

File size: 18.3 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | rcube_install.php                                                     |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail package                    |
8 | Copyright (C) 2008-2009, The Roundcube Dev Team                       |
9 | Licensed under the GNU Public License                                 |
10 +-----------------------------------------------------------------------+
11
12 $Id:  $
13
14*/
15
16
17/**
18 * Class to control the installation process of the Roundcube Webmail package
19 *
20 * @category Install
21 * @package  Roundcube
22 * @author Thomas Bruederli
23 */
24class rcube_install
25{
26  var $step;
27  var $is_post = false;
28  var $failures = 0;
29  var $config = array();
30  var $configured = false;
31  var $last_error = null;
32  var $email_pattern = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9])';
33  var $bool_config_props = array();
34
35  var $obsolete_config = array('db_backend');
36  var $replaced_config = array(
37    'skin_path' => 'skin',
38    'locale_string' => 'language',
39    'multiple_identities' => 'identities_level',
40    'addrbook_show_images' => 'show_images',
41    'imap_root' => 'imap_ns_personal',
42  );
43 
44  // these config options are required for a working system
45  var $required_config = array('db_dsnw', 'db_table_contactgroups', 'db_table_contactgroupmembers', 'des_key');
46 
47  /**
48   * Constructor
49   */
50  function rcube_install()
51  {
52    $this->step = intval($_REQUEST['_step']);
53    $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
54  }
55 
56  /**
57   * Singleton getter
58   */
59  function get_instance()
60  {
61    static $inst;
62   
63    if (!$inst)
64      $inst = new rcube_install();
65   
66    return $inst;
67  }
68 
69  /**
70   * Read the default config files and store properties
71   */
72  function load_defaults()
73  {
74    $this->_load_config('.php.dist');
75  }
76
77
78  /**
79   * Read the local config files and store properties
80   */
81  function load_config()
82  {
83    $this->config = array();
84    $this->_load_config('.php');
85    $this->configured = !empty($this->config);
86  }
87
88  /**
89   * Read the default config file and store properties
90   * @access private
91   */
92  function _load_config($suffix)
93  {
94    @include RCMAIL_CONFIG_DIR . '/main.inc' . $suffix;
95    if (is_array($rcmail_config)) {
96      $this->config += $rcmail_config;
97    }
98     
99    @include RCMAIL_CONFIG_DIR . '/db.inc'. $suffix;
100    if (is_array($rcmail_config)) {
101      $this->config += $rcmail_config;
102    }
103  }
104 
105 
106  /**
107   * Getter for a certain config property
108   *
109   * @param string Property name
110   * @param string Default value
111   * @return string The property value
112   */
113  function getprop($name, $default = '')
114  {
115    $value = $this->config[$name];
116   
117    if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
118      $value = rcube_install::random_key(24);
119   
120    return $value !== null && $value !== '' ? $value : $default;
121  }
122 
123 
124  /**
125   * Take the default config file and replace the parameters
126   * with the submitted form data
127   *
128   * @param string Which config file (either 'main' or 'db')
129   * @return string The complete config file content
130   */
131  function create_config($which, $force = false)
132  {
133    $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
134   
135    if (!$out)
136      return '[Warning: could not read the config template file]';
137
138    foreach ($this->config as $prop => $default) {
139      $value = (isset($_POST["_$prop"]) || $this->bool_config_props[$prop]) ? $_POST["_$prop"] : $default;
140     
141      // convert some form data
142      if ($prop == 'debug_level') {
143        $val = 0;
144        if (is_array($value))
145          foreach ($value as $dbgval)
146            $val += intval($dbgval);
147        $value = $val;
148      }
149      else if ($which == 'db' && $prop == 'db_dsnw' && !empty($_POST['_dbtype'])) {
150        if ($_POST['_dbtype'] == 'sqlite')
151          $value = sprintf('%s://%s?mode=0646', $_POST['_dbtype'], $_POST['_dbname']{0} == '/' ? '/' . $_POST['_dbname'] : $_POST['_dbname']);
152        else
153          $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'], 
154            rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
155      }
156      else if ($prop == 'smtp_auth_type' && $value == '0') {
157        $value = '';
158      }
159      else if ($prop == 'default_host' && is_array($value)) {
160        $value = rcube_install::_clean_array($value);
161        if (count($value) <= 1)
162          $value = $value[0];
163      }
164      else if ($prop == 'pagesize') {
165        $value = max(2, intval($value));
166      }
167      else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
168        $value = '%u';
169      }
170      else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
171        $value = '%p';
172      }
173      else if ($prop == 'default_imap_folders') {
174            $value = Array();
175            foreach ($this->config['default_imap_folders'] as $_folder) {
176              switch($_folder) {
177              case 'Drafts': $_folder = $this->config['drafts_mbox']; break;
178              case 'Sent':   $_folder = $this->config['sent_mbox']; break;
179              case 'Junk':   $_folder = $this->config['junk_mbox']; break;
180              case 'Trash':  $_folder = $this->config['trash_mbox']; break;
181          }
182            if (!in_array($_folder, $value))
183              $value[] = $_folder;
184        }
185      }
186      else if (is_bool($default)) {
187        $value = (bool)$value;
188      }
189      else if (is_numeric($value)) {
190        $value = intval($value);
191      }
192     
193      // skip this property
194      if (!$force && ($value == $default))
195        continue;
196
197      // save change
198      $this->config[$prop] = $value;
199
200      // replace the matching line in config file
201      $out = preg_replace(
202        '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
203        "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
204        $out);
205    }
206
207    return trim($out);
208  }
209
210
211  /**
212   * Check the current configuration for missing properties
213   * and deprecated or obsolete settings
214   *
215   * @return array List with problems detected
216   */
217  function check_config()
218  {
219    $this->config = array();
220    $this->load_defaults();
221    $defaults = $this->config;
222   
223    $this->load_config();
224    if (!$this->configured)
225      return null;
226   
227    $out = $seen = array();
228    $required = array_flip($this->required_config);
229   
230    // iterate over the current configuration
231    foreach ($this->config as $prop => $value) {
232      if ($replacement = $this->replaced_config[$prop]) {
233        $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
234        $seen[$replacement] = true;
235      }
236      else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
237        $out['obsolete'][] = array('prop' => $prop);
238        $seen[$prop] = true;
239      }
240    }
241   
242    // iterate over default config
243    foreach ($defaults as $prop => $value) {
244      if (!isset($seen[$prop]) && !isset($this->config[$prop]) && isset($required[$prop]))
245        $out['missing'][] = array('prop' => $prop);
246    }
247
248    // check config dependencies and contradictions
249    if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
250      if (!extension_loaded('pspell')) {
251        $out['dependencies'][] = array('prop' => 'spellcheck_engine',
252          'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
253      }
254      else if (!empty($this->config['spellcheck_languages'])) {
255        foreach ($this->config['spellcheck_languages'] as $lang => $descr)
256          if (!pspell_new($lang))
257            $out['dependencies'][] = array('prop' => 'spellcheck_languages',
258              'explain' => "You are missing pspell support for language $lang ($descr)");
259      }
260    }
261   
262    if ($this->config['log_driver'] == 'syslog') {
263      if (!function_exists('openlog')) {
264        $out['dependencies'][] = array('prop' => 'log_driver',
265          'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
266      }
267      if (empty($this->config['syslog_id'])) {
268        $out['dependencies'][] = array('prop' => 'syslog_id',
269          'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
270      }
271    }
272   
273    // check ldap_public sources having global_search enabled
274    if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
275      foreach ($this->config['ldap_public'] as $ldap_public) {
276        if ($ldap_public['global_search']) {
277          $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
278          break;
279        }
280      }
281    }
282   
283    return $out;
284  }
285 
286 
287  /**
288   * Merge the current configuration with the defaults
289   * and copy replaced values to the new options.
290   */
291  function merge_config()
292  {
293    $current = $this->config;
294    $this->config = array();
295    $this->load_defaults();
296   
297    foreach ($this->replaced_config as $prop => $replacement)
298      if (isset($current[$prop])) {
299        if ($prop == 'skin_path')
300          $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
301        else if ($prop == 'multiple_identities')
302          $this->config[$replacement] = $current[$prop] ? 2 : 0;
303        else
304          $this->config[$replacement] = $current[$prop];
305       
306        unset($current[$prop]);
307    }
308   
309    foreach ($this->obsolete_config as $prop) {
310      unset($current[$prop]);
311    }
312   
313    // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
314    if (is_array($current['ldap_public'])) {
315      foreach ($current['ldap_public'] as $key => $ldap_public) {
316        if ($ldap_public['global_search']) {
317          $this->config['autocomplete_addressbooks'][] = $key;
318          unset($current['ldap_public'][$key]['global_search']);
319        }
320      }
321    }
322   
323    $this->config  = array_merge($this->config, $current);
324   
325    foreach ((array)$current['ldap_public'] as $key => $values) {
326      $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
327    }
328  }
329 
330  /**
331   * Compare the local database schema with the reference schema
332   * required for this version of Roundcube
333   *
334   * @param boolean True if the schema schould be updated
335   * @return boolean True if the schema is up-to-date, false if not or an error occured
336   */
337  function db_schema_check($DB, $update = false)
338  {
339    if (!$this->configured)
340      return false;
341   
342    // simple ad hand-made db schema
343    $db_schema = array(
344      'users' => array(),
345      'identities' => array(),
346      'contacts' => array(),
347      'contactgroups' => array(),
348      'contactgroupmembers' => array(),
349      'cache' => array(),
350      'messages' => array(),
351      'session' => array(),
352    );
353   
354    $errors = array();
355   
356    // check list of tables
357    $existing_tables = $DB->list_tables();
358
359    foreach ($db_schema as $table => $cols) {
360      $table = !empty($this->config['db_table_'.$table]) ? $this->config['db_table_'.$table] : $table;
361      if (!in_array($table, $existing_tables))
362        $errors[] = "Missing table ".$table;
363      // TODO: check cols and indices
364    }
365   
366    return !empty($errors) ? $errors : false;
367  }
368 
369  /**
370   * Compare the local database schema with the reference schema
371   * required for this version of Roundcube
372   *
373   * @param boolean True if the schema schould be updated
374   * @return boolean True if the schema is up-to-date, false if not or an error occured
375   */
376  function mdb2_schema_check($update = false)
377  {
378    if (!$this->configured)
379      return false;
380   
381    $options = array(
382      'use_transactions' => false,
383      'log_line_break' => "\n",
384      'idxname_format' => '%s',
385      'debug' => false,
386      'quote_identifier' => true,
387      'force_defaults' => false,
388      'portability' => true
389    );
390   
391    $dsnw = $this->config['db_dsnw'];
392    $schema = MDB2_Schema::factory($dsnw, $options);
393    $schema->db->supported['transactions'] = false;
394   
395    if (PEAR::isError($schema)) {
396      $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
397      return false;
398    }
399    else {
400      $definition = $schema->getDefinitionFromDatabase();
401      $definition['charset'] = 'utf8';
402     
403      if (PEAR::isError($definition)) {
404        $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
405        return false;
406      }
407     
408      // load reference schema
409      $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']);
410
411      $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml';
412     
413      if (is_readable($ref_schema)) {
414        $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
415       
416        if (PEAR::isError($reference)) {
417          $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
418        }
419        else {
420          $diff = $schema->compareDefinitions($reference, $definition);
421         
422          if (empty($diff)) {
423            return true;
424          }
425          else if ($update) {
426            // update database schema with the diff from the above check
427            $success = $schema->alterDatabase($reference, $definition, $diff);
428           
429            if (PEAR::isError($success)) {
430              $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
431            }
432            else
433              return true;
434          }
435          echo '<pre>'; var_dump($diff); echo '</pre>';
436          return false;
437        }
438      }
439      else
440        $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
441        return false;
442    }
443   
444    return false;
445  }
446 
447 
448  /**
449   * Getter for the last error message
450   *
451   * @return string Error message or null if none exists
452   */
453  function get_error()
454  {
455      return $this->last_error['message'];
456  }
457 
458 
459  /**
460   * Return a list with all imap hosts configured
461   *
462   * @return array Clean list with imap hosts
463   */
464  function get_hostlist()
465  {
466    $default_hosts = (array)$this->getprop('default_host');
467    $out = array();
468   
469    foreach ($default_hosts as $key => $name) {
470      if (!empty($name))
471        $out[] = rcube_parse_host(is_numeric($key) ? $name : $key);
472    }
473   
474    return $out;
475  }
476 
477 
478  /**
479   * Display OK status
480   *
481   * @param string Test name
482   * @param string Confirm message
483   */
484  function pass($name, $message = '')
485  {
486    echo Q($name) . ':&nbsp; <span class="success">OK</span>';
487    $this->_showhint($message);
488  }
489 
490 
491  /**
492   * Display an error status and increase failure count
493   *
494   * @param string Test name
495   * @param string Error message
496   * @param string URL for details
497   */
498  function fail($name, $message = '', $url = '')
499  {
500    $this->failures++;
501   
502    echo Q($name) . ':&nbsp; <span class="fail">NOT OK</span>';
503    $this->_showhint($message, $url);
504  }
505
506
507  /**
508   * Display an error status for optional settings/features
509   *
510   * @param string Test name
511   * @param string Error message
512   * @param string URL for details
513   */
514  function optfail($name, $message = '', $url = '')
515  {
516    echo Q($name) . ':&nbsp; <span class="na">NOT OK</span>';
517    $this->_showhint($message, $url);
518  }
519 
520 
521  /**
522   * Display warning status
523   *
524   * @param string Test name
525   * @param string Warning message
526   * @param string URL for details
527   */
528  function na($name, $message = '', $url = '')
529  {
530    echo Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
531    $this->_showhint($message, $url);
532  }
533 
534 
535  function _showhint($message, $url = '')
536  {
537    $hint = Q($message);
538   
539    if ($url)
540      $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
541     
542    if ($hint)
543      echo '<span class="indent">(' . $hint . ')</span>';
544  }
545 
546 
547  static function _clean_array($arr)
548  {
549    $out = array();
550   
551    foreach (array_unique($arr) as $k => $val) {
552      if (!empty($val)) {
553        if (is_numeric($k))
554          $out[] = $val;
555        else
556          $out[$k] = $val;
557      }
558    }
559   
560    return $out;
561  }
562 
563 
564  static function _dump_var($var) {
565    if (is_array($var)) {
566      if (empty($var)) {
567        return 'array()';
568      }
569      else {  // check if all keys are numeric
570        $isnum = true;
571        foreach ($var as $key => $value) {
572          if (!is_numeric($key)) {
573            $isnum = false;
574            break;
575          }
576        }
577       
578        if ($isnum)
579          return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
580      }
581    }
582   
583    return var_export($var, true);
584  }
585 
586 
587  /**
588   * Initialize the database with the according schema
589   *
590   * @param object rcube_db Database connection
591   * @return boolen True on success, False on error
592   */
593  function init_db($DB)
594  {
595    $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql');
596    $engine = isset($db_map[$DB->db_provider]) ? $db_map[$DB->db_provider] : $DB->db_provider;
597   
598    // read schema file from /SQL/*
599    $fname = "../SQL/$engine.initial.sql";
600    if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
601      $buff = '';
602      foreach ($lines as $i => $line) {
603        if (preg_match('/^--/', $line))
604          continue;
605         
606        $buff .= $line . "\n";
607        if (preg_match('/;$/', trim($line))) {
608          $DB->query($buff);
609          $buff = '';
610          if ($this->get_error())
611            break;
612        }
613      }
614    }
615    else {
616      $this->fail('DB Schema', "Cannot read the schema file: $fname");
617      return false;
618    }
619   
620    if ($err = $this->get_error()) {
621      $this->fail('DB Schema', "Error creating database schema: $err");
622      return false;
623    }
624
625    return true;
626  }
627 
628  /**
629   * Handler for Roundcube errors
630   */
631  function raise_error($p)
632  {
633      $this->last_error = $p;
634  }
635 
636 
637  /**
638   * Generarte a ramdom string to be used as encryption key
639   *
640   * @param int Key length
641   * @return string The generated random string
642   * @static
643   */
644  function random_key($length)
645  {
646    $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
647    $out = '';
648   
649    for ($i=0; $i < $length; $i++)
650      $out .= $alpha{rand(0, strlen($alpha)-1)};
651   
652    return $out;
653  }
654 
655}
656
Note: See TracBrowser for help on using the repository browser.