thomascube
2010-04-15 2491c6240cad60e68916a79c7a0689bedc2cefd9
commit | author | age
354978 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | rcube_install.php                                                     |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail package                    |
cbbef3 8  | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland                 |
354978 9  | Licensed under the GNU Public License                                 |
T 10  +-----------------------------------------------------------------------+
11
12  $Id:  $
13
14 */
15
16
17 /**
18  * Class to control the installation process of the RoundCube Webmail package
19  *
20  * @category Install
21  * @package  RoundCube
22  * @author Thomas Bruederli
23  */
24 class rcube_install
25 {
26   var $step;
237119 27   var $is_post = false;
354978 28   var $failures = 0;
c5042d 29   var $config = array();
b3f9df 30   var $configured = false;
c5042d 31   var $last_error = null;
ad43e6 32   var $email_pattern = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9])';
871ca9 33   var $bool_config_props = array();
e10712 34
T 35   var $obsolete_config = array('db_backend');
cbffc2 36   var $replaced_config = array(
T 37     'skin_path' => 'skin',
38     'locale_string' => 'language',
39     'multiple_identities' => 'identities_level',
2a4135 40     'addrbook_show_images' => 'show_images',
cbffc2 41   );
e10712 42   
2491c6 43   // these config options are required for a working system
T 44   var $required_config = array('db_dsnw', 'db_table_contactgroups', 'db_table_contactgroupmembers', 'des_key');
354978 45   
T 46   /**
47    * Constructor
48    */
49   function rcube_install()
50   {
51     $this->step = intval($_REQUEST['_step']);
237119 52     $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
354978 53   }
T 54   
c5042d 55   /**
T 56    * Singleton getter
57    */
58   function get_instance()
59   {
60     static $inst;
61     
62     if (!$inst)
63       $inst = new rcube_install();
64     
65     return $inst;
66   }
354978 67   
T 68   /**
c5042d 69    * Read the default config files and store properties
354978 70    */
190e97 71   function load_defaults()
354978 72   {
c5042d 73     $this->_load_config('.php.dist');
T 74   }
75
76
77   /**
78    * Read the local config files and store properties
79    */
80   function load_config()
81   {
b3f9df 82     $this->config = array();
c5042d 83     $this->_load_config('.php');
b3f9df 84     $this->configured = !empty($this->config);
c5042d 85   }
T 86
87   /**
88    * Read the default config file and store properties
89    * @access private
90    */
91   function _load_config($suffix)
92   {
bba657 93     @include RCMAIL_CONFIG_DIR . '/main.inc' . $suffix;
354978 94     if (is_array($rcmail_config)) {
190e97 95       $this->config += $rcmail_config;
354978 96     }
T 97       
bba657 98     @include RCMAIL_CONFIG_DIR . '/db.inc'. $suffix;
354978 99     if (is_array($rcmail_config)) {
c5042d 100       $this->config += $rcmail_config;
354978 101     }
T 102   }
103   
104   
105   /**
106    * Getter for a certain config property
107    *
108    * @param string Property name
ad43e6 109    * @param string Default value
354978 110    * @return string The property value
T 111    */
fa7539 112   function getprop($name, $default = '')
354978 113   {
b77d0d 114     $value = $this->config[$name];
354978 115     
ccb412 116     if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
807d17 117       $value = rcube_install::random_key(24);
354978 118     
fa7539 119     return $value !== null && $value !== '' ? $value : $default;
354978 120   }
T 121   
122   
123   /**
124    * Take the default config file and replace the parameters
125    * with the submitted form data
126    *
127    * @param string Which config file (either 'main' or 'db')
128    * @return string The complete config file content
129    */
e10712 130   function create_config($which, $force = false)
354978 131   {
2c3d81 132     $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
354978 133     
T 134     if (!$out)
2c3d81 135       return '[Warning: could not read the config template file]';
0c3bde 136
c5042d 137     foreach ($this->config as $prop => $default) {
871ca9 138       $value = (isset($_POST["_$prop"]) || $this->bool_config_props[$prop]) ? $_POST["_$prop"] : $default;
354978 139       
T 140       // convert some form data
b77d0d 141       if ($prop == 'debug_level') {
354978 142         $val = 0;
7d7f67 143         if (is_array($value))
T 144           foreach ($value as $dbgval)
b77d0d 145             $val += intval($dbgval);
7d7f67 146         $value = $val;
354978 147       }
0c3bde 148       else if ($which == 'db' && $prop == 'db_dsnw' && !empty($_POST['_dbtype'])) {
237119 149         if ($_POST['_dbtype'] == 'sqlite')
T 150           $value = sprintf('%s://%s?mode=0646', $_POST['_dbtype'], $_POST['_dbname']{0} == '/' ? '/' . $_POST['_dbname'] : $_POST['_dbname']);
151         else
b61965 152           $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'], 
7d7f67 153             rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
c5042d 154       }
T 155       else if ($prop == 'smtp_auth_type' && $value == '0') {
156         $value = '';
157       }
158       else if ($prop == 'default_host' && is_array($value)) {
807d17 159         $value = rcube_install::_clean_array($value);
c5042d 160         if (count($value) <= 1)
T 161           $value = $value[0];
162       }
ccb412 163       else if ($prop == 'pagesize') {
T 164         $value = max(2, intval($value));
165       }
c5042d 166       else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
T 167         $value = '%u';
168       }
169       else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
170         $value = '%p';
171       }
569654 172       else if ($prop == 'default_imap_folders'){
A 173     $value = Array();
174     foreach($this->config['default_imap_folders'] as $_folder){
175       switch($_folder) {
176       case 'Drafts': $_folder = $this->config['drafts_mbox']; break;
177       case 'Sent':   $_folder = $this->config['sent_mbox']; break;
178       case 'Junk':   $_folder = $this->config['junk_mbox']; break;
179       case 'Trash':  $_folder = $this->config['trash_mbox']; break;
180           }
181       if (!in_array($_folder, $value))  $value[] = $_folder;
182         }
183       }
c5042d 184       else if (is_bool($default)) {
27564f 185         $value = (bool)$value;
T 186       }
187       else if (is_numeric($value)) {
188         $value = intval($value);
c5042d 189       }
T 190       
191       // skip this property
e10712 192       if (!$force && ($value == $default))
c5042d 193         continue;
b77d0d 194
A 195       // save change
196       $this->config[$prop] = $value;
197
354978 198       // replace the matching line in config file
T 199       $out = preg_replace(
200         '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
5f25a1 201         "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
354978 202         $out);
T 203     }
0c3bde 204
967b34 205     return trim($out);
c5042d 206   }
e10712 207
T 208
209   /**
210    * Check the current configuration for missing properties
211    * and deprecated or obsolete settings
212    *
213    * @return array List with problems detected
214    */
215   function check_config()
216   {
217     $this->config = array();
218     $this->load_defaults();
219     $defaults = $this->config;
220     
221     $this->load_config();
222     if (!$this->configured)
223       return null;
224     
225     $out = $seen = array();
f8c06e 226     $required = array_flip($this->required_config);
e10712 227     
cbffc2 228     // iterate over the current configuration
e10712 229     foreach ($this->config as $prop => $value) {
T 230       if ($replacement = $this->replaced_config[$prop]) {
231         $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
232         $seen[$replacement] = true;
233       }
234       else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
235         $out['obsolete'][] = array('prop' => $prop);
236         $seen[$prop] = true;
237       }
238     }
239     
240     // iterate over default config
241     foreach ($defaults as $prop => $value) {
f8c06e 242       if (!isset($seen[$prop]) && !isset($this->config[$prop]) && isset($required[$prop]))
e10712 243         $out['missing'][] = array('prop' => $prop);
T 244     }
f8c06e 245
871ca9 246     // check config dependencies and contradictions
T 247     if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
248       if (!extension_loaded('pspell')) {
249         $out['dependencies'][] = array('prop' => 'spellcheck_engine',
250           'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
251       }
924b1a 252       else if (!empty($this->config['spellcheck_languages'])) {
01a8c5 253         foreach ($this->config['spellcheck_languages'] as $lang => $descr)
924b1a 254           if (!pspell_new($lang))
01a8c5 255             $out['dependencies'][] = array('prop' => 'spellcheck_languages',
T 256               'explain' => "You are missing pspell support for language $lang ($descr)");
871ca9 257       }
T 258     }
259     
260     if ($this->config['log_driver'] == 'syslog') {
261       if (!function_exists('openlog')) {
262         $out['dependencies'][] = array('prop' => 'log_driver',
263           'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
264       }
265       if (empty($this->config['syslog_id'])) {
266         $out['dependencies'][] = array('prop' => 'syslog_id',
267           'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
268       }
5f25a1 269     }
T 270     
271     // check ldap_public sources having global_search enabled
272     if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
273       foreach ($this->config['ldap_public'] as $ldap_public) {
274         if ($ldap_public['global_search']) {
275           $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
276           break;
277         }
278       }
871ca9 279     }
T 280     
e10712 281     return $out;
T 282   }
283   
284   
285   /**
286    * Merge the current configuration with the defaults
287    * and copy replaced values to the new options.
288    */
289   function merge_config()
290   {
291     $current = $this->config;
292     $this->config = array();
293     $this->load_defaults();
294     
295     foreach ($this->replaced_config as $prop => $replacement)
296       if (isset($current[$prop])) {
297         if ($prop == 'skin_path')
298           $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
cbffc2 299         else if ($prop == 'multiple_identities')
T 300           $this->config[$replacement] = $current[$prop] ? 2 : 0;
e10712 301         else
T 302           $this->config[$replacement] = $current[$prop];
303         
304         unset($current[$prop]);
305     }
306     
307     foreach ($this->obsolete_config as $prop) {
308       unset($current[$prop]);
309     }
310     
5f25a1 311     // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
T 312     if (is_array($current['ldap_public'])) {
313       foreach ($current['ldap_public'] as $key => $ldap_public) {
314         if ($ldap_public['global_search']) {
315           $this->config['autocomplete_addressbooks'][] = $key;
316           unset($current['ldap_public'][$key]['global_search']);
317         }
318       }
319     }
320     
321     $this->config  = array_merge($this->config, $current);
322     
323     foreach ((array)$current['ldap_public'] as $key => $values) {
324       $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
325     }
e10712 326   }
c5042d 327   
2491c6 328   /**
T 329    * Compare the local database schema with the reference schema
330    * required for this version of RoundCube
331    *
332    * @param boolean True if the schema schould be updated
333    * @return boolean True if the schema is up-to-date, false if not or an error occured
334    */
335   function db_schema_check($DB, $update = false)
336   {
337     if (!$this->configured)
338       return false;
339     
340     // simple ad hand-made db schema
341     $db_schema = array(
342       'users' => array(),
343       'identities' => array(),
344       'contacts' => array(),
345       'contactgroups' => array(),
346       'contactgroupmembers' => array(),
347       'cache' => array(),
348       'messages' => array(),
349       'session' => array(),
350     );
351     
352     $errors = array();
353     
354     // check list of tables
355     $existing_tables = $DB->list_tables();
356     foreach ($db_schema as $table => $cols) {
357       if (!in_array($this->config['db_table_'.$table], $existing_tables))
358         $errors[] = "Missing table ".$table;
359       
360       // TODO: check cols and indices
361     }
362     
363     return !empty($errors) ? $errors : false;
364   }
c5042d 365   
T 366   /**
871ca9 367    * Compare the local database schema with the reference schema
T 368    * required for this version of RoundCube
369    *
370    * @param boolean True if the schema schould be updated
371    * @return boolean True if the schema is up-to-date, false if not or an error occured
372    */
2491c6 373   function mdb2_schema_check($update = false)
871ca9 374   {
T 375     if (!$this->configured)
376       return false;
377     
378     $options = array(
379       'use_transactions' => false,
380       'log_line_break' => "\n",
381       'idxname_format' => '%s',
382       'debug' => false,
383       'quote_identifier' => true,
384       'force_defaults' => false,
385       'portability' => true
386     );
387     
924b1a 388     $dsnw = $this->config['db_dsnw'];
T 389     $schema = MDB2_Schema::factory($dsnw, $options);
871ca9 390     $schema->db->supported['transactions'] = false;
T 391     
392     if (PEAR::isError($schema)) {
393       $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
394       return false;
395     }
396     else {
397       $definition = $schema->getDefinitionFromDatabase();
398       $definition['charset'] = 'utf8';
399       
400       if (PEAR::isError($definition)) {
401         $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
402         return false;
403       }
404       
405       // load reference schema
924b1a 406       $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']);
T 407
408       $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml';
871ca9 409       
924b1a 410       if (is_readable($ref_schema)) {
871ca9 411         $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
T 412         
413         if (PEAR::isError($reference)) {
414           $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
415         }
416         else {
417           $diff = $schema->compareDefinitions($reference, $definition);
418           
419           if (empty($diff)) {
420             return true;
421           }
422           else if ($update) {
423             // update database schema with the diff from the above check
424             $success = $schema->alterDatabase($reference, $definition, $diff);
425             
426             if (PEAR::isError($success)) {
427               $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
428             }
429             else
430               return true;
431           }
432           echo '<pre>'; var_dump($diff); echo '</pre>';
433           return false;
434         }
435       }
436       else
437         $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
438         return false;
439     }
440     
441     return false;
442   }
443   
444   
445   /**
c5042d 446    * Getter for the last error message
T 447    *
448    * @return string Error message or null if none exists
449    */
450   function get_error()
451   {
452       return $this->last_error['message'];
354978 453   }
T 454   
455   
456   /**
112c54 457    * Return a list with all imap hosts configured
T 458    *
459    * @return array Clean list with imap hosts
460    */
461   function get_hostlist()
462   {
463     $default_hosts = (array)$this->getprop('default_host');
464     $out = array();
465     
466     foreach ($default_hosts as $key => $name) {
467       if (!empty($name))
468         $out[] = is_numeric($key) ? $name : $key;
469     }
470     
471     return $out;
472   }
473   
474   
475   /**
354978 476    * Display OK status
T 477    *
478    * @param string Test name
479    * @param string Confirm message
480    */
481   function pass($name, $message = '')
482   {
483     echo Q($name) . ':&nbsp; <span class="success">OK</span>';
6557d3 484     $this->_showhint($message);
354978 485   }
T 486   
487   
488   /**
489    * Display an error status and increase failure count
490    *
491    * @param string Test name
492    * @param string Error message
493    * @param string URL for details
494    */
495   function fail($name, $message = '', $url = '')
496   {
497     $this->failures++;
498     
499     echo Q($name) . ':&nbsp; <span class="fail">NOT OK</span>';
6557d3 500     $this->_showhint($message, $url);
354978 501   }
11e670 502
A 503
504   /**
505    * Display an error status for optional settings/features
506    *
507    * @param string Test name
508    * @param string Error message
509    * @param string URL for details
510    */
511   function optfail($name, $message = '', $url = '')
512   {
513     echo Q($name) . ':&nbsp; <span class="na">NOT OK</span>';
514     $this->_showhint($message, $url);
515   }
354978 516   
T 517   
518   /**
519    * Display warning status
520    *
521    * @param string Test name
522    * @param string Warning message
523    * @param string URL for details
524    */
6557d3 525   function na($name, $message = '', $url = '')
354978 526   {
6557d3 527     echo Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
T 528     $this->_showhint($message, $url);
529   }
530   
531   
532   function _showhint($message, $url = '')
533   {
534     $hint = Q($message);
535     
354978 536     if ($url)
6557d3 537       $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
T 538       
539     if ($hint)
540       echo '<span class="indent">(' . $hint . ')</span>';
354978 541   }
T 542   
543   
5f25a1 544   static function _clean_array($arr)
c5042d 545   {
T 546     $out = array();
547     
5f25a1 548     foreach (array_unique($arr) as $k => $val) {
T 549       if (!empty($val)) {
550         if (is_numeric($k))
551           $out[] = $val;
552         else
553           $out[$k] = $val;
554       }
555     }
c5042d 556     
T 557     return $out;
558   }
559   
190e97 560   
5f25a1 561   static function _dump_var($var) {
T 562     if (is_array($var)) {
563       if (empty($var)) {
564         return 'array()';
565       }
566       else {  // check if all keys are numeric
567         $isnum = true;
568         foreach ($var as $key => $value) {
569           if (!is_numeric($key)) {
570             $isnum = false;
571             break;
572           }
573         }
574         
575         if ($isnum)
576           return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
577       }
578     }
579     
580     return var_export($var, true);
581   }
582   
583   
190e97 584   /**
T 585    * Initialize the database with the according schema
586    *
587    * @param object rcube_db Database connection
588    * @return boolen True on success, False on error
589    */
590   function init_db($DB)
591   {
592     $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql');
593     $engine = isset($db_map[$DB->db_provider]) ? $db_map[$DB->db_provider] : $DB->db_provider;
594     
595     // read schema file from /SQL/*
596     $fname = "../SQL/$engine.initial.sql";
597     if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
598       $buff = '';
599       foreach ($lines as $i => $line) {
0ce119 600         if (preg_match('/^--/', $line))
190e97 601           continue;
T 602           
603         $buff .= $line . "\n";
0ce119 604         if (preg_match('/;$/', trim($line))) {
190e97 605           $DB->query($buff);
T 606           $buff = '';
c0dc90 607           if ($this->get_error())
T 608             break;
190e97 609         }
T 610       }
611     }
612     else {
613       $this->fail('DB Schema', "Cannot read the schema file: $fname");
614       return false;
615     }
616     
617     if ($err = $this->get_error()) {
618       $this->fail('DB Schema', "Error creating database schema: $err");
619       return false;
620     }
621
622     return true;
623   }
624   
c5042d 625   /**
T 626    * Handler for RoundCube errors
627    */
628   function raise_error($p)
629   {
630       $this->last_error = $p;
631   }
632   
633   
354978 634   /**
T 635    * Generarte a ramdom string to be used as encryption key
636    *
637    * @param int Key length
638    * @return string The generated random string
639    * @static
640    */
641   function random_key($length)
642   {
643     $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
644     $out = '';
645     
646     for ($i=0; $i < $length; $i++)
647       $out .= $alpha{rand(0, strlen($alpha)-1)};
648     
649     return $out;
650   }
651   
c5042d 652 }
T 653