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 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 (is_bool($default)) {
180 $value = (bool)$value;
182 else if (is_numeric($value)) {
183 $value = intval($value);
186 // skip this property
187 if (!$force && ($value == $default))
191 $this->config[$prop] = $value;
193 // replace the matching line in config file
195 '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
196 "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
205 * Check the current configuration for missing properties
206 * and deprecated or obsolete settings
208 * @return array List with problems detected
210 function check_config()
212 $this->config = array();
213 $this->load_defaults();
214 $defaults = $this->config;
216 $this->load_config();
217 if (!$this->configured)
220 $out = $seen = array();
221 $optional = array_flip($this->optional_config);
223 // iterate over the current configuration
224 foreach ($this->config as $prop => $value) {
225 if ($replacement = $this->replaced_config[$prop]) {
226 $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
227 $seen[$replacement] = true;
229 else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
230 $out['obsolete'][] = array('prop' => $prop);
235 // iterate over default config
236 foreach ($defaults as $prop => $value) {
237 if (!$seen[$prop] && !isset($this->config[$prop]) && !isset($optional[$prop]))
238 $out['missing'][] = array('prop' => $prop);
241 // check config dependencies and contradictions
242 if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
243 if (!extension_loaded('pspell')) {
244 $out['dependencies'][] = array('prop' => 'spellcheck_engine',
245 'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
247 if (empty($this->config['spellcheck_languages'])) {
248 $out['dependencies'][] = array('prop' => 'spellcheck_languages',
249 'explain' => 'You should specify the list of languages supported by your local pspell installation.');
253 if ($this->config['log_driver'] == 'syslog') {
254 if (!function_exists('openlog')) {
255 $out['dependencies'][] = array('prop' => 'log_driver',
256 'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
258 if (empty($this->config['syslog_id'])) {
259 $out['dependencies'][] = array('prop' => 'syslog_id',
260 'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
264 // check ldap_public sources having global_search enabled
265 if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
266 foreach ($this->config['ldap_public'] as $ldap_public) {
267 if ($ldap_public['global_search']) {
268 $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
279 * Merge the current configuration with the defaults
280 * and copy replaced values to the new options.
282 function merge_config()
284 $current = $this->config;
285 $this->config = array();
286 $this->load_defaults();
288 foreach ($this->replaced_config as $prop => $replacement)
289 if (isset($current[$prop])) {
290 if ($prop == 'skin_path')
291 $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
292 else if ($prop == 'multiple_identities')
293 $this->config[$replacement] = $current[$prop] ? 2 : 0;
295 $this->config[$replacement] = $current[$prop];
297 unset($current[$prop]);
300 foreach ($this->obsolete_config as $prop) {
301 unset($current[$prop]);
304 // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
305 if (is_array($current['ldap_public'])) {
306 foreach ($current['ldap_public'] as $key => $ldap_public) {
307 if ($ldap_public['global_search']) {
308 $this->config['autocomplete_addressbooks'][] = $key;
309 unset($current['ldap_public'][$key]['global_search']);
314 $this->config = array_merge($this->config, $current);
316 foreach ((array)$current['ldap_public'] as $key => $values) {
317 $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
323 * Compare the local database schema with the reference schema
324 * required for this version of RoundCube
326 * @param boolean True if the schema schould be updated
327 * @return boolean True if the schema is up-to-date, false if not or an error occured
329 function db_schema_check($update = false)
331 if (!$this->configured)
335 'use_transactions' => false,
336 'log_line_break' => "\n",
337 'idxname_format' => '%s',
339 'quote_identifier' => true,
340 'force_defaults' => false,
341 'portability' => true
344 $schema =& MDB2_Schema::factory($this->config['db_dsnw'], $options);
345 $schema->db->supported['transactions'] = false;
347 if (PEAR::isError($schema)) {
348 $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
352 $definition = $schema->getDefinitionFromDatabase();
353 $definition['charset'] = 'utf8';
355 if (PEAR::isError($definition)) {
356 $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
360 // load reference schema
361 $dsn = MDB2::parseDSN($this->config['db_dsnw']);
362 $ref_schema = INSTALL_PATH . 'SQL/' . $dsn['phptype'] . '.schema.xml';
364 if (is_file($ref_schema)) {
365 $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
367 if (PEAR::isError($reference)) {
368 $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
371 $diff = $schema->compareDefinitions($reference, $definition);
377 // update database schema with the diff from the above check
378 $success = $schema->alterDatabase($reference, $definition, $diff);
380 if (PEAR::isError($success)) {
381 $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
386 echo '<pre>'; var_dump($diff); echo '</pre>';
391 $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
400 * Getter for the last error message
402 * @return string Error message or null if none exists
406 return $this->last_error['message'];
411 * Return a list with all imap hosts configured
413 * @return array Clean list with imap hosts
415 function get_hostlist()
417 $default_hosts = (array)$this->getprop('default_host');
420 foreach ($default_hosts as $key => $name) {
422 $out[] = is_numeric($key) ? $name : $key;
432 * @param string Test name
433 * @param string Confirm message
435 function pass($name, $message = '')
437 echo Q($name) . ': <span class="success">OK</span>';
438 $this->_showhint($message);
443 * Display an error status and increase failure count
445 * @param string Test name
446 * @param string Error message
447 * @param string URL for details
449 function fail($name, $message = '', $url = '')
453 echo Q($name) . ': <span class="fail">NOT OK</span>';
454 $this->_showhint($message, $url);
459 * Display warning status
461 * @param string Test name
462 * @param string Warning message
463 * @param string URL for details
465 function na($name, $message = '', $url = '')
467 echo Q($name) . ': <span class="na">NOT AVAILABLE</span>';
468 $this->_showhint($message, $url);
472 function _showhint($message, $url = '')
477 $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
480 echo '<span class="indent">(' . $hint . ')</span>';
484 static function _clean_array($arr)
488 foreach (array_unique($arr) as $k => $val) {
501 static function _dump_var($var) {
502 if (is_array($var)) {
506 else { // check if all keys are numeric
508 foreach ($var as $key => $value) {
509 if (!is_numeric($key)) {
516 return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
520 return var_export($var, true);
525 * Initialize the database with the according schema
527 * @param object rcube_db Database connection
528 * @return boolen True on success, False on error
530 function init_db($DB)
532 $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql');
533 $engine = isset($db_map[$DB->db_provider]) ? $db_map[$DB->db_provider] : $DB->db_provider;
535 // read schema file from /SQL/*
536 $fname = "../SQL/$engine.initial.sql";
537 if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
539 foreach ($lines as $i => $line) {
540 if (eregi('^--', $line))
543 $buff .= $line . "\n";
544 if (eregi(';$', trim($line))) {
547 if ($this->get_error())
553 $this->fail('DB Schema', "Cannot read the schema file: $fname");
557 if ($err = $this->get_error()) {
558 $this->fail('DB Schema', "Error creating database schema: $err");
566 * Handler for RoundCube errors
568 function raise_error($p)
570 $this->last_error = $p;
575 * Generarte a ramdom string to be used as encryption key
577 * @param int Key length
578 * @return string The generated random string
581 function random_key($length)
583 $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
586 for ($i=0; $i < $length; $i++)
587 $out .= $alpha{rand(0, strlen($alpha)-1)};