4 +-----------------------------------------------------------------------+
7 | This file is part of the Roundcube Webmail package |
8 | Copyright (C) 2008-2009, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU Public License |
10 +-----------------------------------------------------------------------+
18 * Class to control the installation process of the Roundcube Webmail package
22 * @author Thomas Bruederli
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();
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',
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');
50 function rcube_install()
52 $this->step = intval($_REQUEST['_step']);
53 $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
59 function get_instance()
64 $inst = new rcube_install();
70 * Read the default config files and store properties
72 function load_defaults()
74 $this->_load_config('.php.dist');
79 * Read the local config files and store properties
81 function load_config()
83 $this->config = array();
84 $this->_load_config('.php');
85 $this->configured = !empty($this->config);
89 * Read the default config file and store properties
92 function _load_config($suffix)
94 @include RCMAIL_CONFIG_DIR . '/main.inc' . $suffix;
95 if (is_array($rcmail_config)) {
96 $this->config += $rcmail_config;
99 @include RCMAIL_CONFIG_DIR . '/db.inc'. $suffix;
100 if (is_array($rcmail_config)) {
101 $this->config += $rcmail_config;
107 * Getter for a certain config property
109 * @param string Property name
110 * @param string Default value
111 * @return string The property value
113 function getprop($name, $default = '')
115 $value = $this->config[$name];
117 if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
118 $value = rcube_install::random_key(24);
120 return $value !== null && $value !== '' ? $value : $default;
125 * Take the default config file and replace the parameters
126 * with the submitted form data
128 * @param string Which config file (either 'main' or 'db')
129 * @return string The complete config file content
131 function create_config($which, $force = false)
133 $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
136 return '[Warning: could not read the config template file]';
138 foreach ($this->config as $prop => $default) {
139 $value = (isset($_POST["_$prop"]) || $this->bool_config_props[$prop]) ? $_POST["_$prop"] : $default;
141 // convert some form data
142 if ($prop == 'debug_level') {
144 if (is_array($value))
145 foreach ($value as $dbgval)
146 $val += intval($dbgval);
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']);
153 $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'],
154 rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
156 else if ($prop == 'smtp_auth_type' && $value == '0') {
159 else if ($prop == 'default_host' && is_array($value)) {
160 $value = rcube_install::_clean_array($value);
161 if (count($value) <= 1)
164 else if ($prop == 'pagesize') {
165 $value = max(2, intval($value));
167 else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
170 else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
173 else if ($prop == 'default_imap_folders') {
175 foreach ($this->config['default_imap_folders'] as $_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;
182 if (!in_array($_folder, $value))
186 else if (is_bool($default)) {
187 $value = (bool)$value;
189 else if (is_numeric($value)) {
190 $value = intval($value);
193 // skip this property
194 if (!$force && ($value == $default))
198 $this->config[$prop] = $value;
200 // replace the matching line in config file
202 '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
203 "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
212 * Check the current configuration for missing properties
213 * and deprecated or obsolete settings
215 * @return array List with problems detected
217 function check_config()
219 $this->config = array();
220 $this->load_defaults();
221 $defaults = $this->config;
223 $this->load_config();
224 if (!$this->configured)
227 $out = $seen = array();
228 $required = array_flip($this->required_config);
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;
236 else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
237 $out['obsolete'][] = array('prop' => $prop);
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);
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.');
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)");
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.');
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');
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');
288 * Merge the current configuration with the defaults
289 * and copy replaced values to the new options.
291 function merge_config()
293 $current = $this->config;
294 $this->config = array();
295 $this->load_defaults();
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;
304 $this->config[$replacement] = $current[$prop];
306 unset($current[$prop]);
309 foreach ($this->obsolete_config as $prop) {
310 unset($current[$prop]);
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']);
323 $this->config = array_merge($this->config, $current);
325 foreach ((array)$current['ldap_public'] as $key => $values) {
326 $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
331 * Compare the local database schema with the reference schema
332 * required for this version of Roundcube
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
337 function db_schema_check($DB, $update = false)
339 if (!$this->configured)
342 // simple ad hand-made db schema
345 'identities' => array(),
346 'contacts' => array(),
347 'contactgroups' => array(),
348 'contactgroupmembers' => array(),
350 'messages' => array(),
351 'session' => array(),
356 // check list of tables
357 $existing_tables = $DB->list_tables();
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
366 return !empty($errors) ? $errors : false;
370 * Compare the local database schema with the reference schema
371 * required for this version of Roundcube
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
376 function mdb2_schema_check($update = false)
378 if (!$this->configured)
382 'use_transactions' => false,
383 'log_line_break' => "\n",
384 'idxname_format' => '%s',
386 'quote_identifier' => true,
387 'force_defaults' => false,
388 'portability' => true
391 $dsnw = $this->config['db_dsnw'];
392 $schema = MDB2_Schema::factory($dsnw, $options);
393 $schema->db->supported['transactions'] = false;
395 if (PEAR::isError($schema)) {
396 $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
400 $definition = $schema->getDefinitionFromDatabase();
401 $definition['charset'] = 'utf8';
403 if (PEAR::isError($definition)) {
404 $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
408 // load reference schema
409 $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']);
411 $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml';
413 if (is_readable($ref_schema)) {
414 $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
416 if (PEAR::isError($reference)) {
417 $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
420 $diff = $schema->compareDefinitions($reference, $definition);
426 // update database schema with the diff from the above check
427 $success = $schema->alterDatabase($reference, $definition, $diff);
429 if (PEAR::isError($success)) {
430 $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
435 echo '<pre>'; var_dump($diff); echo '</pre>';
440 $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
449 * Getter for the last error message
451 * @return string Error message or null if none exists
455 return $this->last_error['message'];
460 * Return a list with all imap hosts configured
462 * @return array Clean list with imap hosts
464 function get_hostlist()
466 $default_hosts = (array)$this->getprop('default_host');
469 foreach ($default_hosts as $key => $name) {
471 $out[] = rcube_parse_host(is_numeric($key) ? $name : $key);
481 * @param string Test name
482 * @param string Confirm message
484 function pass($name, $message = '')
486 echo Q($name) . ': <span class="success">OK</span>';
487 $this->_showhint($message);
492 * Display an error status and increase failure count
494 * @param string Test name
495 * @param string Error message
496 * @param string URL for details
498 function fail($name, $message = '', $url = '')
502 echo Q($name) . ': <span class="fail">NOT OK</span>';
503 $this->_showhint($message, $url);
508 * Display an error status for optional settings/features
510 * @param string Test name
511 * @param string Error message
512 * @param string URL for details
514 function optfail($name, $message = '', $url = '')
516 echo Q($name) . ': <span class="na">NOT OK</span>';
517 $this->_showhint($message, $url);
522 * Display warning status
524 * @param string Test name
525 * @param string Warning message
526 * @param string URL for details
528 function na($name, $message = '', $url = '')
530 echo Q($name) . ': <span class="na">NOT AVAILABLE</span>';
531 $this->_showhint($message, $url);
535 function _showhint($message, $url = '')
540 $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
543 echo '<span class="indent">(' . $hint . ')</span>';
547 static function _clean_array($arr)
551 foreach (array_unique($arr) as $k => $val) {
564 static function _dump_var($var) {
565 if (is_array($var)) {
569 else { // check if all keys are numeric
571 foreach ($var as $key => $value) {
572 if (!is_numeric($key)) {
579 return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
583 return var_export($var, true);
588 * Initialize the database with the according schema
590 * @param object rcube_db Database connection
591 * @return boolen True on success, False on error
593 function init_db($DB)
595 $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql');
596 $engine = isset($db_map[$DB->db_provider]) ? $db_map[$DB->db_provider] : $DB->db_provider;
598 // read schema file from /SQL/*
599 $fname = "../SQL/$engine.initial.sql";
600 if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
602 foreach ($lines as $i => $line) {
603 if (preg_match('/^--/', $line))
606 $buff .= $line . "\n";
607 if (preg_match('/;$/', trim($line))) {
610 if ($this->get_error())
616 $this->fail('DB Schema', "Cannot read the schema file: $fname");
620 if ($err = $this->get_error()) {
621 $this->fail('DB Schema', "Error creating database schema: $err");
629 * Handler for Roundcube errors
631 function raise_error($p)
633 $this->last_error = $p;
638 * Generarte a ramdom string to be used as encryption key
640 * @param int Key length
641 * @return string The generated random string
644 function random_key($length)
646 $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
649 for ($i=0; $i < $length; $i++)
650 $out .= $alpha{rand(0, strlen($alpha)-1)};