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 $is_default = !isset($_POST["_$prop"]);
146 $value = !$is_default || $this->bool_config_props[$prop] ? $_POST["_$prop"] : $default;
148 // convert some form data
149 if ($prop == 'debug_level' && !$is_default) {
150 if (is_array($value)) {
152 foreach ($value as $dbgval)
153 $val += intval($dbgval);
157 else if ($which == 'db' && $prop == 'db_dsnw' && !empty($_POST['_dbtype'])) {
158 if ($_POST['_dbtype'] == 'sqlite')
159 $value = sprintf('%s://%s?mode=0646', $_POST['_dbtype'], $_POST['_dbname']{0} == '/' ? '/' . $_POST['_dbname'] : $_POST['_dbname']);
160 else if ($_POST['_dbtype'])
161 $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'],
162 rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
164 else if ($prop == 'smtp_auth_type' && $value == '0') {
167 else if ($prop == 'default_host' && is_array($value)) {
168 $value = rcube_install::_clean_array($value);
169 if (count($value) <= 1)
172 else if ($prop == 'pagesize') {
173 $value = max(2, intval($value));
175 else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
178 else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
181 else if ($prop == 'default_imap_folders') {
183 foreach ($this->config['default_imap_folders'] as $_folder) {
185 case 'Drafts': $_folder = $this->config['drafts_mbox']; break;
186 case 'Sent': $_folder = $this->config['sent_mbox']; break;
187 case 'Junk': $_folder = $this->config['junk_mbox']; break;
188 case 'Trash': $_folder = $this->config['trash_mbox']; break;
190 if (!in_array($_folder, $value))
194 else if (is_bool($default)) {
195 $value = (bool)$value;
197 else if (is_numeric($value)) {
198 $value = intval($value);
201 // skip this property
202 if (!$force && !$this->configured && ($value == $default))
206 $this->config[$prop] = $value;
208 // replace the matching line in config file
210 '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
211 "'\\1 = ' . rcube_install::_dump_var(\$value, \$prop) . ';'",
220 * Check the current configuration for missing properties
221 * and deprecated or obsolete settings
223 * @return array List with problems detected
225 function check_config()
227 $this->config = array();
228 $this->load_defaults();
229 $defaults = $this->config;
231 $this->load_config();
232 if (!$this->configured)
235 $out = $seen = array();
236 $required = array_flip($this->required_config);
238 // iterate over the current configuration
239 foreach ($this->config as $prop => $value) {
240 if ($replacement = $this->replaced_config[$prop]) {
241 $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
242 $seen[$replacement] = true;
244 else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
245 $out['obsolete'][] = array('prop' => $prop);
250 // iterate over default config
251 foreach ($defaults as $prop => $value) {
252 if (!isset($seen[$prop]) && !isset($this->config[$prop]) && isset($required[$prop]))
253 $out['missing'][] = array('prop' => $prop);
256 // check config dependencies and contradictions
257 if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
258 if (!extension_loaded('pspell')) {
259 $out['dependencies'][] = array('prop' => 'spellcheck_engine',
260 'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
262 else if (!empty($this->config['spellcheck_languages'])) {
263 foreach ($this->config['spellcheck_languages'] as $lang => $descr)
264 if (!pspell_new($lang))
265 $out['dependencies'][] = array('prop' => 'spellcheck_languages',
266 'explain' => "You are missing pspell support for language $lang ($descr)");
270 if ($this->config['log_driver'] == 'syslog') {
271 if (!function_exists('openlog')) {
272 $out['dependencies'][] = array('prop' => 'log_driver',
273 'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
275 if (empty($this->config['syslog_id'])) {
276 $out['dependencies'][] = array('prop' => 'syslog_id',
277 'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
281 // check ldap_public sources having global_search enabled
282 if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
283 foreach ($this->config['ldap_public'] as $ldap_public) {
284 if ($ldap_public['global_search']) {
285 $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
296 * Merge the current configuration with the defaults
297 * and copy replaced values to the new options.
299 function merge_config()
301 $current = $this->config;
302 $this->config = array();
303 $this->load_defaults();
305 foreach ($this->replaced_config as $prop => $replacement) {
306 if (isset($current[$prop])) {
307 if ($prop == 'skin_path')
308 $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
309 else if ($prop == 'multiple_identities')
310 $this->config[$replacement] = $current[$prop] ? 2 : 0;
312 $this->config[$replacement] = $current[$prop];
314 unset($current[$prop]);
317 foreach ($this->obsolete_config as $prop) {
318 unset($current[$prop]);
321 // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
322 if (is_array($current['ldap_public'])) {
323 foreach ($current['ldap_public'] as $key => $ldap_public) {
324 if ($ldap_public['global_search']) {
325 $this->config['autocomplete_addressbooks'][] = $key;
326 unset($current['ldap_public'][$key]['global_search']);
331 if ($current['keep_alive'] && $current['session_lifetime'] < $current['keep_alive'])
332 $current['session_lifetime'] = max(10, ceil($current['keep_alive'] / 60) * 2);
334 $this->config = array_merge($this->config, $current);
336 foreach ((array)$current['ldap_public'] as $key => $values) {
337 $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
342 * Compare the local database schema with the reference schema
343 * required for this version of Roundcube
345 * @param boolean True if the schema schould be updated
346 * @return boolean True if the schema is up-to-date, false if not or an error occured
348 function db_schema_check($DB, $update = false)
350 if (!$this->configured)
353 // read reference schema from mysql.initial.sql
354 $db_schema = $this->db_read_schema(INSTALL_PATH . 'SQL/mysql.initial.sql');
357 // check list of tables
358 $existing_tables = $DB->list_tables();
360 foreach ($db_schema as $table => $cols) {
361 $table = !empty($this->config['db_table_'.$table]) ? $this->config['db_table_'.$table] : $table;
362 if (!in_array($table, $existing_tables)) {
363 $errors[] = "Missing table '".$table."'";
365 else { // compare cols
366 $db_cols = $DB->list_cols($table);
367 $diff = array_diff(array_keys($cols), $db_cols);
369 $errors[] = "Missing columns in table '$table': " . join(',', $diff);
373 return !empty($errors) ? $errors : false;
377 * Utility function to read database schema from an .sql file
379 private function db_read_schema($schemafile)
381 $lines = file($schemafile);
382 $table_block = false;
384 foreach ($lines as $line) {
385 if (preg_match('/^\s*create table `?([a-z0-9_]+)`?/i', $line, $m)) {
386 $table_block = $m[1];
388 else if ($table_block && preg_match('/^\s*`?([a-z0-9_-]+)`?\s+([a-z]+)/', $line, $m)) {
390 if (!in_array(strtoupper($col), array('PRIMARY','KEY','INDEX','UNIQUE','CONSTRAINT','REFERENCES','FOREIGN'))) {
391 $schema[$table_block][$col] = $m[2];
401 * Compare the local database schema with the reference schema
402 * required for this version of Roundcube
404 * @param boolean True if the schema schould be updated
405 * @return boolean True if the schema is up-to-date, false if not or an error occured
407 function mdb2_schema_check($update = false)
409 if (!$this->configured)
413 'use_transactions' => false,
414 'log_line_break' => "\n",
415 'idxname_format' => '%s',
417 'quote_identifier' => true,
418 'force_defaults' => false,
419 'portability' => true
422 $dsnw = $this->config['db_dsnw'];
423 $schema = MDB2_Schema::factory($dsnw, $options);
424 $schema->db->supported['transactions'] = false;
426 if (PEAR::isError($schema)) {
427 $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
431 $definition = $schema->getDefinitionFromDatabase();
432 $definition['charset'] = 'utf8';
434 if (PEAR::isError($definition)) {
435 $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
439 // load reference schema
440 $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']);
442 $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml';
444 if (is_readable($ref_schema)) {
445 $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
447 if (PEAR::isError($reference)) {
448 $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
451 $diff = $schema->compareDefinitions($reference, $definition);
457 // update database schema with the diff from the above check
458 $success = $schema->alterDatabase($reference, $definition, $diff);
460 if (PEAR::isError($success)) {
461 $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
466 echo '<pre>'; var_dump($diff); echo '</pre>';
471 $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
480 * Getter for the last error message
482 * @return string Error message or null if none exists
486 return $this->last_error['message'];
491 * Return a list with all imap hosts configured
493 * @return array Clean list with imap hosts
495 function get_hostlist()
497 $default_hosts = (array)$this->getprop('default_host');
500 foreach ($default_hosts as $key => $name) {
502 $out[] = rcube_parse_host(is_numeric($key) ? $name : $key);
509 * Create a HTML dropdown to select a previous version of Roundcube
511 function versions_select($attrib = array())
513 $select = new html_select($attrib);
514 $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'));
519 * Return a list with available subfolders of the skin directory
521 function list_skins()
524 $skindir = INSTALL_PATH . 'skins/';
525 foreach (glob($skindir . '*') as $path) {
526 if (is_dir($path) && is_readable($path)) {
527 $skins[] = substr($path, strlen($skindir));
536 * @param string Test name
537 * @param string Confirm message
539 function pass($name, $message = '')
541 echo Q($name) . ': <span class="success">OK</span>';
542 $this->_showhint($message);
547 * Display an error status and increase failure count
549 * @param string Test name
550 * @param string Error message
551 * @param string URL for details
553 function fail($name, $message = '', $url = '')
557 echo Q($name) . ': <span class="fail">NOT OK</span>';
558 $this->_showhint($message, $url);
563 * Display an error status for optional settings/features
565 * @param string Test name
566 * @param string Error message
567 * @param string URL for details
569 function optfail($name, $message = '', $url = '')
571 echo Q($name) . ': <span class="na">NOT OK</span>';
572 $this->_showhint($message, $url);
577 * Display warning status
579 * @param string Test name
580 * @param string Warning message
581 * @param string URL for details
583 function na($name, $message = '', $url = '')
585 echo Q($name) . ': <span class="na">NOT AVAILABLE</span>';
586 $this->_showhint($message, $url);
590 function _showhint($message, $url = '')
595 $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
598 echo '<span class="indent">(' . $hint . ')</span>';
602 static function _clean_array($arr)
606 foreach (array_unique($arr) as $k => $val) {
619 static function _dump_var($var, $name=null) {
622 case 'syslog_facility':
623 $list = array(32 => 'LOG_AUTH', 80 => 'LOG_AUTHPRIV', 72 => ' LOG_CRON',
624 24 => 'LOG_DAEMON', 0 => 'LOG_KERN', 128 => 'LOG_LOCAL0',
625 136 => 'LOG_LOCAL1', 144 => 'LOG_LOCAL2', 152 => 'LOG_LOCAL3',
626 160 => 'LOG_LOCAL4', 168 => 'LOG_LOCAL5', 176 => 'LOG_LOCAL6',
627 184 => 'LOG_LOCAL7', 48 => 'LOG_LPR', 16 => 'LOG_MAIL',
628 56 => 'LOG_NEWS', 40 => 'LOG_SYSLOG', 8 => 'LOG_USER', 64 => 'LOG_UUCP');
629 if ($val = $list[$var])
635 if (is_array($var)) {
639 else { // check if all keys are numeric
641 foreach ($var as $key => $value) {
642 if (!is_numeric($key)) {
649 return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
653 return var_export($var, true);
658 * Initialize the database with the according schema
660 * @param object rcube_db Database connection
661 * @return boolen True on success, False on error
663 function init_db($DB)
665 $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
667 // read schema file from /SQL/*
668 $fname = INSTALL_PATH . "SQL/$engine.initial.sql";
669 if ($sql = @file_get_contents($fname)) {
670 $this->exec_sql($sql, $DB);
673 $this->fail('DB Schema', "Cannot read the schema file: $fname");
677 if ($err = $this->get_error()) {
678 $this->fail('DB Schema', "Error creating database schema: $err");
687 * Update database with SQL statements from SQL/*.update.sql
689 * @param object rcube_db Database connection
690 * @param string Version to update from
691 * @return boolen True on success, False on error
693 function update_db($DB, $version)
695 $version = strtolower($version);
696 $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
698 // read schema file from /SQL/*
699 $fname = INSTALL_PATH . "SQL/$engine.update.sql";
700 if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
701 $from = false; $sql = '';
702 foreach ($lines as $line) {
703 $is_comment = preg_match('/^--/', $line);
704 if (!$from && $is_comment && preg_match('/from version\s([0-9.]+[a-z-]*)/', $line, $m)) {
705 $v = strtolower($m[1]);
706 if ($v == $version || version_compare($version, $v, '<='))
709 if ($from && !$is_comment)
714 $this->exec_sql($sql, $DB);
717 $this->fail('DB Schema', "Cannot read the update file: $fname");
721 if ($err = $this->get_error()) {
722 $this->fail('DB Schema', "Error updating database: $err");
731 * Execute the given SQL queries on the database connection
733 * @param string SQL queries to execute
734 * @param object rcube_db Database connection
735 * @return boolen True on success, False on error
737 function exec_sql($sql, $DB)
740 foreach (explode("\n", $sql) as $line) {
741 if (preg_match('/^--/', $line) || trim($line) == '')
744 $buff .= $line . "\n";
745 if (preg_match('/(;|^GO)$/', trim($line))) {
753 return !$DB->is_error();
758 * Handler for Roundcube errors
760 function raise_error($p)
762 $this->last_error = $p;
767 * Generarte a ramdom string to be used as encryption key
769 * @param int Key length
770 * @return string The generated random string
773 function random_key($length)
775 $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
778 for ($i=0; $i < $length; $i++)
779 $out .= $alpha{rand(0, strlen($alpha)-1)};