alecpl
2009-09-11 4aaecb661cd25d1b35ccc89ab64c1a1aff427087
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   
T 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',
5f25a1 46     'smtp_helo_host', 'smtp_auth_type', 'sendmail_delay', 'double_auth',
T 47     'language', 'mail_header_delimiter', 'create_default_folders',
e10712 48     'quota_zero_as_unlimited', 'spellcheck_uri', 'spellcheck_languages',
T 49     'http_received_header', 'session_domain', 'mime_magic', 'log_logins',
5f25a1 50     'enable_installer', 'skin_include_php', 'imap_root', 'imap_delimiter',
T 51     'virtuser_file', 'virtuser_query', 'dont_override');
354978 52   
T 53   /**
54    * Constructor
55    */
56   function rcube_install()
57   {
58     $this->step = intval($_REQUEST['_step']);
237119 59     $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
354978 60   }
T 61   
c5042d 62   /**
T 63    * Singleton getter
64    */
65   function get_instance()
66   {
67     static $inst;
68     
69     if (!$inst)
70       $inst = new rcube_install();
71     
72     return $inst;
73   }
354978 74   
T 75   /**
c5042d 76    * Read the default config files and store properties
354978 77    */
190e97 78   function load_defaults()
354978 79   {
c5042d 80     $this->_load_config('.php.dist');
T 81   }
82
83
84   /**
85    * Read the local config files and store properties
86    */
87   function load_config()
88   {
b3f9df 89     $this->config = array();
c5042d 90     $this->_load_config('.php');
b3f9df 91     $this->configured = !empty($this->config);
c5042d 92   }
T 93
94   /**
95    * Read the default config file and store properties
96    * @access private
97    */
98   function _load_config($suffix)
99   {
bba657 100     @include RCMAIL_CONFIG_DIR . '/main.inc' . $suffix;
354978 101     if (is_array($rcmail_config)) {
190e97 102       $this->config += $rcmail_config;
354978 103     }
T 104       
bba657 105     @include RCMAIL_CONFIG_DIR . '/db.inc'. $suffix;
354978 106     if (is_array($rcmail_config)) {
c5042d 107       $this->config += $rcmail_config;
354978 108     }
T 109   }
110   
111   
112   /**
113    * Getter for a certain config property
114    *
115    * @param string Property name
ad43e6 116    * @param string Default value
354978 117    * @return string The property value
T 118    */
fa7539 119   function getprop($name, $default = '')
354978 120   {
b77d0d 121     $value = $this->config[$name];
354978 122     
ccb412 123     if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
807d17 124       $value = rcube_install::random_key(24);
354978 125     
fa7539 126     return $value !== null && $value !== '' ? $value : $default;
354978 127   }
T 128   
129   
130   /**
131    * Take the default config file and replace the parameters
132    * with the submitted form data
133    *
134    * @param string Which config file (either 'main' or 'db')
135    * @return string The complete config file content
136    */
e10712 137   function create_config($which, $force = false)
354978 138   {
2c3d81 139     $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
354978 140     
T 141     if (!$out)
2c3d81 142       return '[Warning: could not read the config template file]';
0c3bde 143
c5042d 144     foreach ($this->config as $prop => $default) {
871ca9 145       $value = (isset($_POST["_$prop"]) || $this->bool_config_props[$prop]) ? $_POST["_$prop"] : $default;
354978 146       
T 147       // convert some form data
b77d0d 148       if ($prop == 'debug_level') {
354978 149         $val = 0;
7d7f67 150         if (is_array($value))
T 151           foreach ($value as $dbgval)
b77d0d 152             $val += intval($dbgval);
7d7f67 153         $value = $val;
354978 154       }
0c3bde 155       else if ($which == 'db' && $prop == 'db_dsnw' && !empty($_POST['_dbtype'])) {
237119 156         if ($_POST['_dbtype'] == 'sqlite')
T 157           $value = sprintf('%s://%s?mode=0646', $_POST['_dbtype'], $_POST['_dbname']{0} == '/' ? '/' . $_POST['_dbname'] : $_POST['_dbname']);
158         else
b61965 159           $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'], 
7d7f67 160             rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
c5042d 161       }
T 162       else if ($prop == 'smtp_auth_type' && $value == '0') {
163         $value = '';
164       }
165       else if ($prop == 'default_host' && is_array($value)) {
807d17 166         $value = rcube_install::_clean_array($value);
c5042d 167         if (count($value) <= 1)
T 168           $value = $value[0];
169       }
ccb412 170       else if ($prop == 'pagesize') {
T 171         $value = max(2, intval($value));
172       }
c5042d 173       else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
T 174         $value = '%u';
175       }
176       else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
177         $value = '%p';
178       }
569654 179       else if ($prop == 'default_imap_folders'){
A 180     $value = Array();
181     foreach($this->config['default_imap_folders'] as $_folder){
182       switch($_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;
187           }
188       if (!in_array($_folder, $value))  $value[] = $_folder;
189         }
190       }
c5042d 191       else if (is_bool($default)) {
27564f 192         $value = (bool)$value;
T 193       }
194       else if (is_numeric($value)) {
195         $value = intval($value);
c5042d 196       }
T 197       
198       // skip this property
e10712 199       if (!$force && ($value == $default))
c5042d 200         continue;
b77d0d 201
A 202       // save change
203       $this->config[$prop] = $value;
204
354978 205       // replace the matching line in config file
T 206       $out = preg_replace(
207         '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
5f25a1 208         "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
354978 209         $out);
T 210     }
0c3bde 211
967b34 212     return trim($out);
c5042d 213   }
e10712 214
T 215
216   /**
217    * Check the current configuration for missing properties
218    * and deprecated or obsolete settings
219    *
220    * @return array List with problems detected
221    */
222   function check_config()
223   {
224     $this->config = array();
225     $this->load_defaults();
226     $defaults = $this->config;
227     
228     $this->load_config();
229     if (!$this->configured)
230       return null;
231     
232     $out = $seen = array();
233     $optional = array_flip($this->optional_config);
234     
cbffc2 235     // iterate over the current configuration
e10712 236     foreach ($this->config as $prop => $value) {
T 237       if ($replacement = $this->replaced_config[$prop]) {
238         $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
239         $seen[$replacement] = true;
240       }
241       else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
242         $out['obsolete'][] = array('prop' => $prop);
243         $seen[$prop] = true;
244       }
245     }
246     
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);
251     }
252     
871ca9 253     // check config dependencies and contradictions
T 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.');
258       }
01a8c5 259       if (!empty($this->config['spellcheck_languages'])) {
T 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)");
871ca9 264       }
T 265     }
266     
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.');
271       }
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');
275       }
5f25a1 276     }
T 277     
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');
283           break;
284         }
285       }
871ca9 286     }
T 287     
e10712 288     return $out;
T 289   }
290   
291   
292   /**
293    * Merge the current configuration with the defaults
294    * and copy replaced values to the new options.
295    */
296   function merge_config()
297   {
298     $current = $this->config;
299     $this->config = array();
300     $this->load_defaults();
301     
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]);
cbffc2 306         else if ($prop == 'multiple_identities')
T 307           $this->config[$replacement] = $current[$prop] ? 2 : 0;
e10712 308         else
T 309           $this->config[$replacement] = $current[$prop];
310         
311         unset($current[$prop]);
312     }
313     
314     foreach ($this->obsolete_config as $prop) {
315       unset($current[$prop]);
316     }
317     
5f25a1 318     // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
T 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']);
324         }
325       }
326     }
327     
328     $this->config  = array_merge($this->config, $current);
329     
330     foreach ((array)$current['ldap_public'] as $key => $values) {
331       $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
332     }
e10712 333   }
c5042d 334   
T 335   
336   /**
871ca9 337    * Compare the local database schema with the reference schema
T 338    * required for this version of RoundCube
339    *
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
342    */
343   function db_schema_check($update = false)
344   {
345     if (!$this->configured)
346       return false;
347     
348     $options = array(
349       'use_transactions' => false,
350       'log_line_break' => "\n",
351       'idxname_format' => '%s',
352       'debug' => false,
353       'quote_identifier' => true,
354       'force_defaults' => false,
355       'portability' => true
356     );
357     
358     $schema =& MDB2_Schema::factory($this->config['db_dsnw'], $options);
359     $schema->db->supported['transactions'] = false;
360     
361     if (PEAR::isError($schema)) {
362       $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
363       return false;
364     }
365     else {
366       $definition = $schema->getDefinitionFromDatabase();
367       $definition['charset'] = 'utf8';
368       
369       if (PEAR::isError($definition)) {
370         $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
371         return false;
372       }
373       
374       // load reference schema
375       $dsn = MDB2::parseDSN($this->config['db_dsnw']);
376       $ref_schema = INSTALL_PATH . 'SQL/' . $dsn['phptype'] . '.schema.xml';
377       
378       if (is_file($ref_schema)) {
379         $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
380         
381         if (PEAR::isError($reference)) {
382           $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
383         }
384         else {
385           $diff = $schema->compareDefinitions($reference, $definition);
386           
387           if (empty($diff)) {
388             return true;
389           }
390           else if ($update) {
391             // update database schema with the diff from the above check
392             $success = $schema->alterDatabase($reference, $definition, $diff);
393             
394             if (PEAR::isError($success)) {
395               $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
396             }
397             else
398               return true;
399           }
400           echo '<pre>'; var_dump($diff); echo '</pre>';
401           return false;
402         }
403       }
404       else
405         $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
406         return false;
407     }
408     
409     return false;
410   }
411   
412   
413   /**
c5042d 414    * Getter for the last error message
T 415    *
416    * @return string Error message or null if none exists
417    */
418   function get_error()
419   {
420       return $this->last_error['message'];
354978 421   }
T 422   
423   
424   /**
112c54 425    * Return a list with all imap hosts configured
T 426    *
427    * @return array Clean list with imap hosts
428    */
429   function get_hostlist()
430   {
431     $default_hosts = (array)$this->getprop('default_host');
432     $out = array();
433     
434     foreach ($default_hosts as $key => $name) {
435       if (!empty($name))
436         $out[] = is_numeric($key) ? $name : $key;
437     }
438     
439     return $out;
440   }
441   
442   
443   /**
354978 444    * Display OK status
T 445    *
446    * @param string Test name
447    * @param string Confirm message
448    */
449   function pass($name, $message = '')
450   {
451     echo Q($name) . ':&nbsp; <span class="success">OK</span>';
6557d3 452     $this->_showhint($message);
354978 453   }
T 454   
455   
456   /**
457    * Display an error status and increase failure count
458    *
459    * @param string Test name
460    * @param string Error message
461    * @param string URL for details
462    */
463   function fail($name, $message = '', $url = '')
464   {
465     $this->failures++;
466     
467     echo Q($name) . ':&nbsp; <span class="fail">NOT OK</span>';
6557d3 468     $this->_showhint($message, $url);
354978 469   }
11e670 470
A 471
472   /**
473    * Display an error status for optional settings/features
474    *
475    * @param string Test name
476    * @param string Error message
477    * @param string URL for details
478    */
479   function optfail($name, $message = '', $url = '')
480   {
481     echo Q($name) . ':&nbsp; <span class="na">NOT OK</span>';
482     $this->_showhint($message, $url);
483   }
354978 484   
T 485   
486   /**
487    * Display warning status
488    *
489    * @param string Test name
490    * @param string Warning message
491    * @param string URL for details
492    */
6557d3 493   function na($name, $message = '', $url = '')
354978 494   {
6557d3 495     echo Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
T 496     $this->_showhint($message, $url);
497   }
498   
499   
500   function _showhint($message, $url = '')
501   {
502     $hint = Q($message);
503     
354978 504     if ($url)
6557d3 505       $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
T 506       
507     if ($hint)
508       echo '<span class="indent">(' . $hint . ')</span>';
354978 509   }
T 510   
511   
5f25a1 512   static function _clean_array($arr)
c5042d 513   {
T 514     $out = array();
515     
5f25a1 516     foreach (array_unique($arr) as $k => $val) {
T 517       if (!empty($val)) {
518         if (is_numeric($k))
519           $out[] = $val;
520         else
521           $out[$k] = $val;
522       }
523     }
c5042d 524     
T 525     return $out;
526   }
527   
190e97 528   
5f25a1 529   static function _dump_var($var) {
T 530     if (is_array($var)) {
531       if (empty($var)) {
532         return 'array()';
533       }
534       else {  // check if all keys are numeric
535         $isnum = true;
536         foreach ($var as $key => $value) {
537           if (!is_numeric($key)) {
538             $isnum = false;
539             break;
540           }
541         }
542         
543         if ($isnum)
544           return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
545       }
546     }
547     
548     return var_export($var, true);
549   }
550   
551   
190e97 552   /**
T 553    * Initialize the database with the according schema
554    *
555    * @param object rcube_db Database connection
556    * @return boolen True on success, False on error
557    */
558   function init_db($DB)
559   {
560     $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql');
561     $engine = isset($db_map[$DB->db_provider]) ? $db_map[$DB->db_provider] : $DB->db_provider;
562     
563     // read schema file from /SQL/*
564     $fname = "../SQL/$engine.initial.sql";
565     if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
566       $buff = '';
567       foreach ($lines as $i => $line) {
0ce119 568         if (preg_match('/^--/', $line))
190e97 569           continue;
T 570           
571         $buff .= $line . "\n";
0ce119 572         if (preg_match('/;$/', trim($line))) {
190e97 573           $DB->query($buff);
T 574           $buff = '';
c0dc90 575           if ($this->get_error())
T 576             break;
190e97 577         }
T 578       }
579     }
580     else {
581       $this->fail('DB Schema', "Cannot read the schema file: $fname");
582       return false;
583     }
584     
585     if ($err = $this->get_error()) {
586       $this->fail('DB Schema', "Error creating database schema: $err");
587       return false;
588     }
589
590     return true;
591   }
592   
c5042d 593   /**
T 594    * Handler for RoundCube errors
595    */
596   function raise_error($p)
597   {
598       $this->last_error = $p;
599   }
600   
601   
354978 602   /**
T 603    * Generarte a ramdom string to be used as encryption key
604    *
605    * @param int Key length
606    * @return string The generated random string
607    * @static
608    */
609   function random_key($length)
610   {
611     $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
612     $out = '';
613     
614     for ($i=0; $i < $length; $i++)
615       $out .= $alpha{rand(0, strlen($alpha)-1)};
616     
617     return $out;
618   }
619   
c5042d 620 }
T 621