]> git.donarmstrong.com Git - roundcube.git/blob - installer/rcube_install.php
Imported Upstream version 0.3
[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 config 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 ($prop == 'default_imap_folders'){
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       }
191       else if (is_bool($default)) {
192         $value = (bool)$value;
193       }
194       else if (is_numeric($value)) {
195         $value = intval($value);
196       }
197       
198       // skip this property
199       if (!$force && ($value == $default))
200         continue;
201
202       // save change
203       $this->config[$prop] = $value;
204
205       // replace the matching line in config file
206       $out = preg_replace(
207         '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
208         "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
209         $out);
210     }
211
212     return trim($out);
213   }
214
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     
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;
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     
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.');
258       }
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)");
264       }
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       }
276     }
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       }
286     }
287     
288     return $out;
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]);
306         else if ($prop == 'multiple_identities')
307           $this->config[$replacement] = $current[$prop] ? 2 : 0;
308         else
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     
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']);
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     }
333   }
334   
335   
336   /**
337    * Compare the local database schema with the reference schema
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   /**
414    * Getter for the last error message
415    *
416    * @return string Error message or null if none exists
417    */
418   function get_error()
419   {
420       return $this->last_error['message'];
421   }
422   
423   
424   /**
425    * Return a list with all imap hosts configured
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   /**
444    * Display OK status
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>';
452     $this->_showhint($message);
453   }
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>';
468     $this->_showhint($message, $url);
469   }
470
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   }
484   
485   
486   /**
487    * Display warning status
488    *
489    * @param string Test name
490    * @param string Warning message
491    * @param string URL for details
492    */
493   function na($name, $message = '', $url = '')
494   {
495     echo Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
496     $this->_showhint($message, $url);
497   }
498   
499   
500   function _showhint($message, $url = '')
501   {
502     $hint = Q($message);
503     
504     if ($url)
505       $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
506       
507     if ($hint)
508       echo '<span class="indent">(' . $hint . ')</span>';
509   }
510   
511   
512   static function _clean_array($arr)
513   {
514     $out = array();
515     
516     foreach (array_unique($arr) as $k => $val) {
517       if (!empty($val)) {
518         if (is_numeric($k))
519           $out[] = $val;
520         else
521           $out[$k] = $val;
522       }
523     }
524     
525     return $out;
526   }
527   
528   
529   static function _dump_var($var) {
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   
552   /**
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) {
568         if (preg_match('/^--/', $line))
569           continue;
570           
571         $buff .= $line . "\n";
572         if (preg_match('/;$/', trim($line))) {
573           $DB->query($buff);
574           $buff = '';
575           if ($this->get_error())
576             break;
577         }
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   
593   /**
594    * Handler for RoundCube errors
595    */
596   function raise_error($p)
597   {
598       $this->last_error = $p;
599   }
600   
601   
602   /**
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   
620 }
621