4 +-----------------------------------------------------------------------+
7 | This file is part of the Roundcube Webmail package |
8 | Copyright (C) 2008-2011, The Roundcube Dev Team |
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 $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql', 'sqlsrv' => 'mssql');
33 var $email_pattern = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9])';
34 var $bool_config_props = array();
36 var $obsolete_config = array('db_backend', 'double_auth');
37 var $replaced_config = array(
38 'skin_path' => 'skin',
39 'locale_string' => 'language',
40 'multiple_identities' => 'identities_level',
41 'addrbook_show_images' => 'show_images',
42 'imap_root' => 'imap_ns_personal',
45 // these config options are required for a working system
46 var $required_config = array(
47 'db_dsnw', 'db_table_contactgroups', 'db_table_contactgroupmembers',
48 'des_key', 'session_lifetime',
54 function rcube_install()
56 $this->step = intval($_REQUEST['_step']);
57 $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
63 function get_instance()
68 $inst = new rcube_install();
74 * Read the default config files and store properties
76 function load_defaults()
78 $this->_load_config('.php.dist');
83 * Read the local config files and store properties
85 function load_config()
87 $this->config = array();
88 $this->_load_config('.php');
89 $this->configured = !empty($this->config);
93 * Read the default config file and store properties
96 function _load_config($suffix)
98 if (is_readable($main_inc = RCMAIL_CONFIG_DIR . '/main.inc' . $suffix)) {
100 if (is_array($rcmail_config))
101 $this->config += $rcmail_config;
103 if (is_readable($db_inc = RCMAIL_CONFIG_DIR . '/db.inc'. $suffix)) {
105 if (is_array($rcmail_config))
106 $this->config += $rcmail_config;
112 * Getter for a certain config property
114 * @param string Property name
115 * @param string Default value
116 * @return string The property value
118 function getprop($name, $default = '')
120 $value = $this->config[$name];
122 if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
123 $value = rcube_install::random_key(24);
125 return $value !== null && $value !== '' ? $value : $default;
130 * Take the default config file and replace the parameters
131 * with the submitted form data
133 * @param string Which config file (either 'main' or 'db')
134 * @return string The complete config file content
136 function create_config($which, $force = false)
138 $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
141 return '[Warning: could not read the config template file]';
143 foreach ($this->config as $prop => $default) {
145 $value = (isset($_POST["_$prop"]) || $this->bool_config_props[$prop]) ? $_POST["_$prop"] : $default;
147 // convert some form data
148 if ($prop == 'debug_level') {
150 if (is_array($value))
151 foreach ($value as $dbgval)
152 $val += intval($dbgval);
155 else if ($which == 'db' && $prop == 'db_dsnw' && !empty($_POST['_dbtype'])) {
156 if ($_POST['_dbtype'] == 'sqlite')
157 $value = sprintf('%s://%s?mode=0646', $_POST['_dbtype'], $_POST['_dbname']{0} == '/' ? '/' . $_POST['_dbname'] : $_POST['_dbname']);
159 $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'],
160 rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
162 else if ($prop == 'smtp_auth_type' && $value == '0') {
165 else if ($prop == 'default_host' && is_array($value)) {
166 $value = rcube_install::_clean_array($value);
167 if (count($value) <= 1)
170 else if ($prop == 'pagesize') {
171 $value = max(2, intval($value));
173 else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
176 else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
179 else if ($prop == 'default_imap_folders') {
181 foreach ($this->config['default_imap_folders'] as $_folder) {
183 case 'Drafts': $_folder = $this->config['drafts_mbox']; break;
184 case 'Sent': $_folder = $this->config['sent_mbox']; break;
185 case 'Junk': $_folder = $this->config['junk_mbox']; break;
186 case 'Trash': $_folder = $this->config['trash_mbox']; break;
188 if (!in_array($_folder, $value))
192 else if (is_bool($default)) {
193 $value = (bool)$value;
195 else if (is_numeric($value)) {
196 $value = intval($value);
199 // skip this property
200 if (!$force && !$this->configured && ($value == $default))
204 $this->config[$prop] = $value;
206 // replace the matching line in config file
208 '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
209 "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
218 * Check the current configuration for missing properties
219 * and deprecated or obsolete settings
221 * @return array List with problems detected
223 function check_config()
225 $this->config = array();
226 $this->load_defaults();
227 $defaults = $this->config;
229 $this->load_config();
230 if (!$this->configured)
233 $out = $seen = array();
234 $required = array_flip($this->required_config);
236 // iterate over the current configuration
237 foreach ($this->config as $prop => $value) {
238 if ($replacement = $this->replaced_config[$prop]) {
239 $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
240 $seen[$replacement] = true;
242 else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
243 $out['obsolete'][] = array('prop' => $prop);
248 // iterate over default config
249 foreach ($defaults as $prop => $value) {
250 if (!isset($seen[$prop]) && !isset($this->config[$prop]) && isset($required[$prop]))
251 $out['missing'][] = array('prop' => $prop);
254 // check config dependencies and contradictions
255 if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
256 if (!extension_loaded('pspell')) {
257 $out['dependencies'][] = array('prop' => 'spellcheck_engine',
258 'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
260 else if (!empty($this->config['spellcheck_languages'])) {
261 foreach ($this->config['spellcheck_languages'] as $lang => $descr)
262 if (!pspell_new($lang))
263 $out['dependencies'][] = array('prop' => 'spellcheck_languages',
264 'explain' => "You are missing pspell support for language $lang ($descr)");
268 if ($this->config['log_driver'] == 'syslog') {
269 if (!function_exists('openlog')) {
270 $out['dependencies'][] = array('prop' => 'log_driver',
271 'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
273 if (empty($this->config['syslog_id'])) {
274 $out['dependencies'][] = array('prop' => 'syslog_id',
275 'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
279 // check ldap_public sources having global_search enabled
280 if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
281 foreach ($this->config['ldap_public'] as $ldap_public) {
282 if ($ldap_public['global_search']) {
283 $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
294 * Merge the current configuration with the defaults
295 * and copy replaced values to the new options.
297 function merge_config()
299 $current = $this->config;
300 $this->config = array();
301 $this->load_defaults();
303 foreach ($this->replaced_config as $prop => $replacement) {
304 if (isset($current[$prop])) {
305 if ($prop == 'skin_path')
306 $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
307 else if ($prop == 'multiple_identities')
308 $this->config[$replacement] = $current[$prop] ? 2 : 0;
310 $this->config[$replacement] = $current[$prop];
312 unset($current[$prop]);
315 foreach ($this->obsolete_config as $prop) {
316 unset($current[$prop]);
319 // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
320 if (is_array($current['ldap_public'])) {
321 foreach ($current['ldap_public'] as $key => $ldap_public) {
322 if ($ldap_public['global_search']) {
323 $this->config['autocomplete_addressbooks'][] = $key;
324 unset($current['ldap_public'][$key]['global_search']);
329 if ($current['keep_alive'] && $current['session_lifetime'] < $current['keep_alive'])
330 $current['session_lifetime'] = max(10, ceil($current['keep_alive'] / 60) * 2);
332 $this->config = array_merge($this->config, $current);
334 foreach ((array)$current['ldap_public'] as $key => $values) {
335 $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
340 * Compare the local database schema with the reference schema
341 * required for this version of Roundcube
343 * @param boolean True if the schema schould be updated
344 * @return boolean True if the schema is up-to-date, false if not or an error occured
346 function db_schema_check($DB, $update = false)
348 if (!$this->configured)
351 // read reference schema from mysql.initial.sql
352 $db_schema = $this->db_read_schema(INSTALL_PATH . 'SQL/mysql.initial.sql');
355 // check list of tables
356 $existing_tables = $DB->list_tables();
358 foreach ($db_schema as $table => $cols) {
359 $table = !empty($this->config['db_table_'.$table]) ? $this->config['db_table_'.$table] : $table;
360 if (!in_array($table, $existing_tables)) {
361 $errors[] = "Missing table '".$table."'";
363 else { // compare cols
364 $db_cols = $DB->list_cols($table);
365 $diff = array_diff(array_keys($cols), $db_cols);
367 $errors[] = "Missing columns in table '$table': " . join(',', $diff);
371 return !empty($errors) ? $errors : false;
375 * Utility function to read database schema from an .sql file
377 private function db_read_schema($schemafile)
379 $lines = file($schemafile);
380 $table_block = false;
382 foreach ($lines as $line) {
383 if (preg_match('/^\s*create table `?([a-z0-9_]+)`?/i', $line, $m)) {
384 $table_block = $m[1];
386 else if ($table_block && preg_match('/^\s*`?([a-z0-9_-]+)`?\s+([a-z]+)/', $line, $m)) {
388 if (!in_array(strtoupper($col), array('PRIMARY','KEY','INDEX','UNIQUE','CONSTRAINT','REFERENCES','FOREIGN'))) {
389 $schema[$table_block][$col] = $m[2];
399 * Compare the local database schema with the reference schema
400 * required for this version of Roundcube
402 * @param boolean True if the schema schould be updated
403 * @return boolean True if the schema is up-to-date, false if not or an error occured
405 function mdb2_schema_check($update = false)
407 if (!$this->configured)
411 'use_transactions' => false,
412 'log_line_break' => "\n",
413 'idxname_format' => '%s',
415 'quote_identifier' => true,
416 'force_defaults' => false,
417 'portability' => true
420 $dsnw = $this->config['db_dsnw'];
421 $schema = MDB2_Schema::factory($dsnw, $options);
422 $schema->db->supported['transactions'] = false;
424 if (PEAR::isError($schema)) {
425 $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
429 $definition = $schema->getDefinitionFromDatabase();
430 $definition['charset'] = 'utf8';
432 if (PEAR::isError($definition)) {
433 $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
437 // load reference schema
438 $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']);
440 $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml';
442 if (is_readable($ref_schema)) {
443 $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
445 if (PEAR::isError($reference)) {
446 $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
449 $diff = $schema->compareDefinitions($reference, $definition);
455 // update database schema with the diff from the above check
456 $success = $schema->alterDatabase($reference, $definition, $diff);
458 if (PEAR::isError($success)) {
459 $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
464 echo '<pre>'; var_dump($diff); echo '</pre>';
469 $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
478 * Getter for the last error message
480 * @return string Error message or null if none exists
484 return $this->last_error['message'];
489 * Return a list with all imap hosts configured
491 * @return array Clean list with imap hosts
493 function get_hostlist()
495 $default_hosts = (array)$this->getprop('default_host');
498 foreach ($default_hosts as $key => $name) {
500 $out[] = rcube_parse_host(is_numeric($key) ? $name : $key);
507 * Create a HTML dropdown to select a previous version of Roundcube
509 function versions_select($attrib = array())
511 $select = new html_select($attrib);
512 $select->add(array('0.1-stable', '0.1.1', '0.2-alpha', '0.2-beta', '0.2-stable', '0.3-stable', '0.3.1', '0.4-beta', '0.4.2', '0.5-beta', '0.5', '0.5.1'));
517 * Return a list with available subfolders of the skin directory
519 function list_skins()
522 $skindir = INSTALL_PATH . 'skins/';
523 foreach (glob($skindir . '*') as $path) {
524 if (is_dir($path) && is_readable($path)) {
525 $skins[] = substr($path, strlen($skindir));
534 * @param string Test name
535 * @param string Confirm message
537 function pass($name, $message = '')
539 echo Q($name) . ': <span class="success">OK</span>';
540 $this->_showhint($message);
545 * Display an error status and increase failure count
547 * @param string Test name
548 * @param string Error message
549 * @param string URL for details
551 function fail($name, $message = '', $url = '')
555 echo Q($name) . ': <span class="fail">NOT OK</span>';
556 $this->_showhint($message, $url);
561 * Display an error status for optional settings/features
563 * @param string Test name
564 * @param string Error message
565 * @param string URL for details
567 function optfail($name, $message = '', $url = '')
569 echo Q($name) . ': <span class="na">NOT OK</span>';
570 $this->_showhint($message, $url);
575 * Display warning status
577 * @param string Test name
578 * @param string Warning message
579 * @param string URL for details
581 function na($name, $message = '', $url = '')
583 echo Q($name) . ': <span class="na">NOT AVAILABLE</span>';
584 $this->_showhint($message, $url);
588 function _showhint($message, $url = '')
593 $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
596 echo '<span class="indent">(' . $hint . ')</span>';
600 static function _clean_array($arr)
604 foreach (array_unique($arr) as $k => $val) {
617 static function _dump_var($var) {
618 if (is_array($var)) {
622 else { // check if all keys are numeric
624 foreach ($var as $key => $value) {
625 if (!is_numeric($key)) {
632 return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
636 return var_export($var, true);
641 * Initialize the database with the according schema
643 * @param object rcube_db Database connection
644 * @return boolen True on success, False on error
646 function init_db($DB)
648 $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
650 // read schema file from /SQL/*
651 $fname = INSTALL_PATH . "SQL/$engine.initial.sql";
652 if ($sql = @file_get_contents($fname)) {
653 $this->exec_sql($sql, $DB);
656 $this->fail('DB Schema', "Cannot read the schema file: $fname");
660 if ($err = $this->get_error()) {
661 $this->fail('DB Schema', "Error creating database schema: $err");
670 * Update database with SQL statements from SQL/*.update.sql
672 * @param object rcube_db Database connection
673 * @param string Version to update from
674 * @return boolen True on success, False on error
676 function update_db($DB, $version)
678 $version = strtolower($version);
679 $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
681 // read schema file from /SQL/*
682 $fname = INSTALL_PATH . "SQL/$engine.update.sql";
683 if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
684 $from = false; $sql = '';
685 foreach ($lines as $line) {
686 $is_comment = preg_match('/^--/', $line);
687 if (!$from && $is_comment && preg_match('/from version\s([0-9.]+[a-z-]*)/', $line, $m)) {
688 $v = strtolower($m[1]);
689 if ($v == $version || version_compare($version, $v, '<='))
692 if ($from && !$is_comment)
697 $this->exec_sql($sql, $DB);
700 $this->fail('DB Schema', "Cannot read the update file: $fname");
704 if ($err = $this->get_error()) {
705 $this->fail('DB Schema', "Error updating database: $err");
714 * Execute the given SQL queries on the database connection
716 * @param string SQL queries to execute
717 * @param object rcube_db Database connection
718 * @return boolen True on success, False on error
720 function exec_sql($sql, $DB)
723 foreach (explode("\n", $sql) as $line) {
724 if (preg_match('/^--/', $line) || trim($line) == '')
727 $buff .= $line . "\n";
728 if (preg_match('/(;|^GO)$/', trim($line))) {
736 return !$DB->is_error();
741 * Handler for Roundcube errors
743 function raise_error($p)
745 $this->last_error = $p;
750 * Generarte a ramdom string to be used as encryption key
752 * @param int Key length
753 * @return string The generated random string
756 function random_key($length)
758 $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
761 for ($i=0; $i < $length; $i++)
762 $out .= $alpha{rand(0, strlen($alpha)-1)};