]> git.donarmstrong.com Git - roundcube.git/blob - installer/rcube_install.php
Imported Upstream version 0.2.1
[roundcube.git] / installer / rcube_install.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | rcube_install.php                                                     |
6  |                                                                       |
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  +-----------------------------------------------------------------------+
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;
27   var $is_post = false;
28   var $failures = 0;
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();
34
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',
41   );
42   
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');
52   
53   /**
54    * Constructor
55    */
56   function rcube_install()
57   {
58     $this->step = intval($_REQUEST['_step']);
59     $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
60   }
61   
62   /**
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   }
74   
75   /**
76    * Read the default config files and store properties
77    */
78   function load_defaults()
79   {
80     $this->_load_config('.php.dist');
81   }
82
83
84   /**
85    * Read the local config files and store properties
86    */
87   function load_config()
88   {
89     $this->config = array();
90     $this->_load_config('.php');
91     $this->configured = !empty($this->config);
92   }
93
94   /**
95    * Read the default config file and store properties
96    * @access private
97    */
98   function _load_config($suffix)
99   {
100     @include RCMAIL_CONFIG_DIR . '/main.inc' . $suffix;
101     if (is_array($rcmail_config)) {
102       $this->config += $rcmail_config;
103     }
104       
105     @include RCMAIL_CONFIG_DIR . '/db.inc'. $suffix;
106     if (is_array($rcmail_config)) {
107       $this->config += $rcmail_config;
108     }
109   }
110   
111   
112   /**
113    * Getter for a certain config property
114    *
115    * @param string Property name
116    * @param string Default value
117    * @return string The property value
118    */
119   function getprop($name, $default = '')
120   {
121     $value = $this->config[$name];
122     
123     if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
124       $value = rcube_install::random_key(24);
125     
126     return $value !== null && $value !== '' ? $value : $default;
127   }
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    */
137   function create_config($which, $force = false)
138   {
139     $out = file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
140     
141     if (!$out)
142       return '[Warning: could not read the template file]';
143
144     foreach ($this->config as $prop => $default) {
145       $value = (isset($_POST["_$prop"]) || $this->bool_config_props[$prop]) ? $_POST["_$prop"] : $default;
146       
147       // convert some form data
148       if ($prop == 'debug_level') {
149         $val = 0;
150         if (is_array($value))
151           foreach ($value as $dbgval)
152             $val += intval($dbgval);
153         $value = $val;
154       }
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']);
158         else
159           $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'], 
160             rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
161       }
162       else if ($prop == 'smtp_auth_type' && $value == '0') {
163         $value = '';
164       }
165       else if ($prop == 'default_host' && is_array($value)) {
166         $value = rcube_install::_clean_array($value);
167         if (count($value) <= 1)
168           $value = $value[0];
169       }
170       else if ($prop == 'pagesize') {
171         $value = max(2, intval($value));
172       }
173       else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
174         $value = '%u';
175       }
176       else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
177         $value = '%p';
178       }
179       else if (is_bool($default)) {
180         $value = (bool)$value;
181       }
182       else if (is_numeric($value)) {
183         $value = intval($value);
184       }
185       
186       // skip this property
187       if (!$force && ($value == $default))
188         continue;
189
190       // save change
191       $this->config[$prop] = $value;
192
193       // replace the matching line in config file
194       $out = preg_replace(
195         '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
196         "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
197         $out);
198     }
199
200     return trim($out);
201   }
202
203
204   /**
205    * Check the current configuration for missing properties
206    * and deprecated or obsolete settings
207    *
208    * @return array List with problems detected
209    */
210   function check_config()
211   {
212     $this->config = array();
213     $this->load_defaults();
214     $defaults = $this->config;
215     
216     $this->load_config();
217     if (!$this->configured)
218       return null;
219     
220     $out = $seen = array();
221     $optional = array_flip($this->optional_config);
222     
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;
228       }
229       else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
230         $out['obsolete'][] = array('prop' => $prop);
231         $seen[$prop] = true;
232       }
233     }
234     
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);
239     }
240     
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.');
246       }
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.');
250       }
251     }
252     
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.');
257       }
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');
261       }
262     }
263     
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');
269           break;
270         }
271       }
272     }
273     
274     return $out;
275   }
276   
277   
278   /**
279    * Merge the current configuration with the defaults
280    * and copy replaced values to the new options.
281    */
282   function merge_config()
283   {
284     $current = $this->config;
285     $this->config = array();
286     $this->load_defaults();
287     
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;
294         else
295           $this->config[$replacement] = $current[$prop];
296         
297         unset($current[$prop]);
298     }
299     
300     foreach ($this->obsolete_config as $prop) {
301       unset($current[$prop]);
302     }
303     
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']);
310         }
311       }
312     }
313     
314     $this->config  = array_merge($this->config, $current);
315     
316     foreach ((array)$current['ldap_public'] as $key => $values) {
317       $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
318     }
319   }
320   
321   
322   /**
323    * Compare the local database schema with the reference schema
324    * required for this version of RoundCube
325    *
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
328    */
329   function db_schema_check($update = false)
330   {
331     if (!$this->configured)
332       return false;
333     
334     $options = array(
335       'use_transactions' => false,
336       'log_line_break' => "\n",
337       'idxname_format' => '%s',
338       'debug' => false,
339       'quote_identifier' => true,
340       'force_defaults' => false,
341       'portability' => true
342     );
343     
344     $schema =& MDB2_Schema::factory($this->config['db_dsnw'], $options);
345     $schema->db->supported['transactions'] = false;
346     
347     if (PEAR::isError($schema)) {
348       $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
349       return false;
350     }
351     else {
352       $definition = $schema->getDefinitionFromDatabase();
353       $definition['charset'] = 'utf8';
354       
355       if (PEAR::isError($definition)) {
356         $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
357         return false;
358       }
359       
360       // load reference schema
361       $dsn = MDB2::parseDSN($this->config['db_dsnw']);
362       $ref_schema = INSTALL_PATH . 'SQL/' . $dsn['phptype'] . '.schema.xml';
363       
364       if (is_file($ref_schema)) {
365         $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
366         
367         if (PEAR::isError($reference)) {
368           $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
369         }
370         else {
371           $diff = $schema->compareDefinitions($reference, $definition);
372           
373           if (empty($diff)) {
374             return true;
375           }
376           else if ($update) {
377             // update database schema with the diff from the above check
378             $success = $schema->alterDatabase($reference, $definition, $diff);
379             
380             if (PEAR::isError($success)) {
381               $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
382             }
383             else
384               return true;
385           }
386           echo '<pre>'; var_dump($diff); echo '</pre>';
387           return false;
388         }
389       }
390       else
391         $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
392         return false;
393     }
394     
395     return false;
396   }
397   
398   
399   /**
400    * Getter for the last error message
401    *
402    * @return string Error message or null if none exists
403    */
404   function get_error()
405   {
406       return $this->last_error['message'];
407   }
408   
409   
410   /**
411    * Return a list with all imap hosts configured
412    *
413    * @return array Clean list with imap hosts
414    */
415   function get_hostlist()
416   {
417     $default_hosts = (array)$this->getprop('default_host');
418     $out = array();
419     
420     foreach ($default_hosts as $key => $name) {
421       if (!empty($name))
422         $out[] = is_numeric($key) ? $name : $key;
423     }
424     
425     return $out;
426   }
427   
428   
429   /**
430    * Display OK status
431    *
432    * @param string Test name
433    * @param string Confirm message
434    */
435   function pass($name, $message = '')
436   {
437     echo Q($name) . ':&nbsp; <span class="success">OK</span>';
438     $this->_showhint($message);
439   }
440   
441   
442   /**
443    * Display an error status and increase failure count
444    *
445    * @param string Test name
446    * @param string Error message
447    * @param string URL for details
448    */
449   function fail($name, $message = '', $url = '')
450   {
451     $this->failures++;
452     
453     echo Q($name) . ':&nbsp; <span class="fail">NOT OK</span>';
454     $this->_showhint($message, $url);
455   }
456   
457   
458   /**
459    * Display warning status
460    *
461    * @param string Test name
462    * @param string Warning message
463    * @param string URL for details
464    */
465   function na($name, $message = '', $url = '')
466   {
467     echo Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
468     $this->_showhint($message, $url);
469   }
470   
471   
472   function _showhint($message, $url = '')
473   {
474     $hint = Q($message);
475     
476     if ($url)
477       $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
478       
479     if ($hint)
480       echo '<span class="indent">(' . $hint . ')</span>';
481   }
482   
483   
484   static function _clean_array($arr)
485   {
486     $out = array();
487     
488     foreach (array_unique($arr) as $k => $val) {
489       if (!empty($val)) {
490         if (is_numeric($k))
491           $out[] = $val;
492         else
493           $out[$k] = $val;
494       }
495     }
496     
497     return $out;
498   }
499   
500   
501   static function _dump_var($var) {
502     if (is_array($var)) {
503       if (empty($var)) {
504         return 'array()';
505       }
506       else {  // check if all keys are numeric
507         $isnum = true;
508         foreach ($var as $key => $value) {
509           if (!is_numeric($key)) {
510             $isnum = false;
511             break;
512           }
513         }
514         
515         if ($isnum)
516           return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
517       }
518     }
519     
520     return var_export($var, true);
521   }
522   
523   
524   /**
525    * Initialize the database with the according schema
526    *
527    * @param object rcube_db Database connection
528    * @return boolen True on success, False on error
529    */
530   function init_db($DB)
531   {
532     $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql');
533     $engine = isset($db_map[$DB->db_provider]) ? $db_map[$DB->db_provider] : $DB->db_provider;
534     
535     // read schema file from /SQL/*
536     $fname = "../SQL/$engine.initial.sql";
537     if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
538       $buff = '';
539       foreach ($lines as $i => $line) {
540         if (eregi('^--', $line))
541           continue;
542           
543         $buff .= $line . "\n";
544         if (eregi(';$', trim($line))) {
545           $DB->query($buff);
546           $buff = '';
547           if ($this->get_error())
548             break;
549         }
550       }
551     }
552     else {
553       $this->fail('DB Schema', "Cannot read the schema file: $fname");
554       return false;
555     }
556     
557     if ($err = $this->get_error()) {
558       $this->fail('DB Schema', "Error creating database schema: $err");
559       return false;
560     }
561
562     return true;
563   }
564   
565   /**
566    * Handler for RoundCube errors
567    */
568   function raise_error($p)
569   {
570       $this->last_error = $p;
571   }
572   
573   
574   /**
575    * Generarte a ramdom string to be used as encryption key
576    *
577    * @param int Key length
578    * @return string The generated random string
579    * @static
580    */
581   function random_key($length)
582   {
583     $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
584     $out = '';
585     
586     for ($i=0; $i < $length; $i++)
587       $out .= $alpha{rand(0, strlen($alpha)-1)};
588     
589     return $out;
590   }
591   
592 }
593