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',
43 // these config options are optional or can be set to null
44 var $optional_config = array(
45 'log_driver', 'syslog_id', 'syslog_facility', 'imap_auth_type',
46 'smtp_helo_host', 'smtp_auth_type', 'sendmail_delay', 'double_auth',
47 'language', 'mail_header_delimiter', 'create_default_folders',
48 'quota_zero_as_unlimited', 'spellcheck_uri', 'spellcheck_languages',
49 'http_received_header', 'session_domain', 'mime_magic', 'log_logins',
50 'enable_installer', 'skin_include_php', 'imap_root', 'imap_delimiter',
51 'virtuser_file', 'virtuser_query', 'dont_override');
56 function rcube_install()
58 $this->step = intval($_REQUEST['_step']);
59 $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
65 function get_instance()
70 $inst = new rcube_install();
76 * Read the default config files and store properties
78 function load_defaults()
80 $this->_load_config('.php.dist');
85 * Read the local config files and store properties
87 function load_config()
89 $this->config = array();
90 $this->_load_config('.php');
91 $this->configured = !empty($this->config);
95 * Read the default config file and store properties
98 function _load_config($suffix)
100 @include RCMAIL_CONFIG_DIR . '/main.inc' . $suffix;
101 if (is_array($rcmail_config)) {
102 $this->config += $rcmail_config;
105 @include RCMAIL_CONFIG_DIR . '/db.inc'. $suffix;
106 if (is_array($rcmail_config)) {
107 $this->config += $rcmail_config;
113 * Getter for a certain config property
115 * @param string Property name
116 * @param string Default value
117 * @return string The property value
119 function getprop($name, $default = '')
121 $value = $this->config[$name];
123 if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
124 $value = rcube_install::random_key(24);
126 return $value !== null && $value !== '' ? $value : $default;
131 * Take the default config file and replace the parameters
132 * with the submitted form data
134 * @param string Which config file (either 'main' or 'db')
135 * @return string The complete config file content
137 function create_config($which, $force = false)
139 $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
142 return '[Warning: could not read the config template file]';
144 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)) $value[] = $_folder;
191 else if (is_bool($default)) {
192 $value = (bool)$value;
194 else if (is_numeric($value)) {
195 $value = intval($value);
198 // skip this property
199 if (!$force && ($value == $default))
203 $this->config[$prop] = $value;
205 // replace the matching line in config file
207 '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
208 "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
217 * Check the current configuration for missing properties
218 * and deprecated or obsolete settings
220 * @return array List with problems detected
222 function check_config()
224 $this->config = array();
225 $this->load_defaults();
226 $defaults = $this->config;
228 $this->load_config();
229 if (!$this->configured)
232 $out = $seen = array();
233 $optional = array_flip($this->optional_config);
235 // iterate over the current configuration
236 foreach ($this->config as $prop => $value) {
237 if ($replacement = $this->replaced_config[$prop]) {
238 $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
239 $seen[$replacement] = true;
241 else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
242 $out['obsolete'][] = array('prop' => $prop);
247 // iterate over default config
248 foreach ($defaults as $prop => $value) {
249 if (!$seen[$prop] && !isset($this->config[$prop]) && !isset($optional[$prop]))
250 $out['missing'][] = array('prop' => $prop);
253 // check config dependencies and contradictions
254 if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
255 if (!extension_loaded('pspell')) {
256 $out['dependencies'][] = array('prop' => 'spellcheck_engine',
257 'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
259 if (!empty($this->config['spellcheck_languages'])) {
260 foreach ($this->config['spellcheck_languages'] as $lang => $descr)
261 if (!pspell_new($lang))
262 $out['dependencies'][] = array('prop' => 'spellcheck_languages',
263 'explain' => "You are missing pspell support for language $lang ($descr)");
267 if ($this->config['log_driver'] == 'syslog') {
268 if (!function_exists('openlog')) {
269 $out['dependencies'][] = array('prop' => 'log_driver',
270 'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
272 if (empty($this->config['syslog_id'])) {
273 $out['dependencies'][] = array('prop' => 'syslog_id',
274 'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
278 // check ldap_public sources having global_search enabled
279 if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
280 foreach ($this->config['ldap_public'] as $ldap_public) {
281 if ($ldap_public['global_search']) {
282 $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
293 * Merge the current configuration with the defaults
294 * and copy replaced values to the new options.
296 function merge_config()
298 $current = $this->config;
299 $this->config = array();
300 $this->load_defaults();
302 foreach ($this->replaced_config as $prop => $replacement)
303 if (isset($current[$prop])) {
304 if ($prop == 'skin_path')
305 $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
306 else if ($prop == 'multiple_identities')
307 $this->config[$replacement] = $current[$prop] ? 2 : 0;
309 $this->config[$replacement] = $current[$prop];
311 unset($current[$prop]);
314 foreach ($this->obsolete_config as $prop) {
315 unset($current[$prop]);
318 // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
319 if (is_array($current['ldap_public'])) {
320 foreach ($current['ldap_public'] as $key => $ldap_public) {
321 if ($ldap_public['global_search']) {
322 $this->config['autocomplete_addressbooks'][] = $key;
323 unset($current['ldap_public'][$key]['global_search']);
328 $this->config = array_merge($this->config, $current);
330 foreach ((array)$current['ldap_public'] as $key => $values) {
331 $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
337 * Compare the local database schema with the reference schema
338 * required for this version of RoundCube
340 * @param boolean True if the schema schould be updated
341 * @return boolean True if the schema is up-to-date, false if not or an error occured
343 function db_schema_check($update = false)
345 if (!$this->configured)
349 'use_transactions' => false,
350 'log_line_break' => "\n",
351 'idxname_format' => '%s',
353 'quote_identifier' => true,
354 'force_defaults' => false,
355 'portability' => true
358 $schema =& MDB2_Schema::factory($this->config['db_dsnw'], $options);
359 $schema->db->supported['transactions'] = false;
361 if (PEAR::isError($schema)) {
362 $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
366 $definition = $schema->getDefinitionFromDatabase();
367 $definition['charset'] = 'utf8';
369 if (PEAR::isError($definition)) {
370 $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
374 // load reference schema
375 $dsn = MDB2::parseDSN($this->config['db_dsnw']);
376 $ref_schema = INSTALL_PATH . 'SQL/' . $dsn['phptype'] . '.schema.xml';
378 if (is_file($ref_schema)) {
379 $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
381 if (PEAR::isError($reference)) {
382 $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
385 $diff = $schema->compareDefinitions($reference, $definition);
391 // update database schema with the diff from the above check
392 $success = $schema->alterDatabase($reference, $definition, $diff);
394 if (PEAR::isError($success)) {
395 $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
400 echo '<pre>'; var_dump($diff); echo '</pre>';
405 $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
414 * Getter for the last error message
416 * @return string Error message or null if none exists
420 return $this->last_error['message'];
425 * Return a list with all imap hosts configured
427 * @return array Clean list with imap hosts
429 function get_hostlist()
431 $default_hosts = (array)$this->getprop('default_host');
434 foreach ($default_hosts as $key => $name) {
436 $out[] = is_numeric($key) ? $name : $key;
446 * @param string Test name
447 * @param string Confirm message
449 function pass($name, $message = '')
451 echo Q($name) . ': <span class="success">OK</span>';
452 $this->_showhint($message);
457 * Display an error status and increase failure count
459 * @param string Test name
460 * @param string Error message
461 * @param string URL for details
463 function fail($name, $message = '', $url = '')
467 echo Q($name) . ': <span class="fail">NOT OK</span>';
468 $this->_showhint($message, $url);
473 * Display an error status for optional settings/features
475 * @param string Test name
476 * @param string Error message
477 * @param string URL for details
479 function optfail($name, $message = '', $url = '')
481 echo Q($name) . ': <span class="na">NOT OK</span>';
482 $this->_showhint($message, $url);
487 * Display warning status
489 * @param string Test name
490 * @param string Warning message
491 * @param string URL for details
493 function na($name, $message = '', $url = '')
495 echo Q($name) . ': <span class="na">NOT AVAILABLE</span>';
496 $this->_showhint($message, $url);
500 function _showhint($message, $url = '')
505 $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
508 echo '<span class="indent">(' . $hint . ')</span>';
512 static function _clean_array($arr)
516 foreach (array_unique($arr) as $k => $val) {
529 static function _dump_var($var) {
530 if (is_array($var)) {
534 else { // check if all keys are numeric
536 foreach ($var as $key => $value) {
537 if (!is_numeric($key)) {
544 return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
548 return var_export($var, true);
553 * Initialize the database with the according schema
555 * @param object rcube_db Database connection
556 * @return boolen True on success, False on error
558 function init_db($DB)
560 $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql');
561 $engine = isset($db_map[$DB->db_provider]) ? $db_map[$DB->db_provider] : $DB->db_provider;
563 // read schema file from /SQL/*
564 $fname = "../SQL/$engine.initial.sql";
565 if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
567 foreach ($lines as $i => $line) {
568 if (preg_match('/^--/', $line))
571 $buff .= $line . "\n";
572 if (preg_match('/;$/', trim($line))) {
575 if ($this->get_error())
581 $this->fail('DB Schema', "Cannot read the schema file: $fname");
585 if ($err = $this->get_error()) {
586 $this->fail('DB Schema', "Error creating database schema: $err");
594 * Handler for RoundCube errors
596 function raise_error($p)
598 $this->last_error = $p;
603 * Generarte a ramdom string to be used as encryption key
605 * @param int Key length
606 * @return string The generated random string
609 function random_key($length)
611 $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
614 for ($i=0; $i < $length; $i++)
615 $out .= $alpha{rand(0, strlen($alpha)-1)};