]> git.donarmstrong.com Git - roundcube.git/blob - installer/rcube_install.php
ff3f7a4c3c5ec00897d076656be27131722bf30e
[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-2011, The Roundcube Dev Team                       |
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 $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql', 'sqlsrv' => 'mssql');
33   var $email_pattern = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9])';
34   var $bool_config_props = array();
35
36   var $obsolete_config = array('db_backend', 'double_auth');
37   var $replaced_config = array(
38     'skin_path' => 'skin',
39     'locale_string' => 'language',
40     'multiple_identities' => 'identities_level',
41     'addrbook_show_images' => 'show_images',
42     'imap_root' => 'imap_ns_personal',
43   );
44   
45   // these config options are required for a working system
46   var $required_config = array(
47     'db_dsnw', 'db_table_contactgroups', 'db_table_contactgroupmembers',
48     'des_key', 'session_lifetime',
49   );
50   
51   /**
52    * Constructor
53    */
54   function rcube_install()
55   {
56     $this->step = intval($_REQUEST['_step']);
57     $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
58   }
59   
60   /**
61    * Singleton getter
62    */
63   function get_instance()
64   {
65     static $inst;
66     
67     if (!$inst)
68       $inst = new rcube_install();
69     
70     return $inst;
71   }
72   
73   /**
74    * Read the default config files and store properties
75    */
76   function load_defaults()
77   {
78     $this->_load_config('.php.dist');
79   }
80
81
82   /**
83    * Read the local config files and store properties
84    */
85   function load_config()
86   {
87     $this->config = array();
88     $this->_load_config('.php');
89     $this->configured = !empty($this->config);
90   }
91
92   /**
93    * Read the default config file and store properties
94    * @access private
95    */
96   function _load_config($suffix)
97   {
98     if (is_readable($main_inc = RCMAIL_CONFIG_DIR . '/main.inc' . $suffix)) {
99       include($main_inc);
100       if (is_array($rcmail_config))
101         $this->config += $rcmail_config;
102     }
103     if (is_readable($db_inc = RCMAIL_CONFIG_DIR . '/db.inc'. $suffix)) {
104       include($db_inc);
105       if (is_array($rcmail_config))
106         $this->config += $rcmail_config;
107     }
108   }
109   
110   
111   /**
112    * Getter for a certain config property
113    *
114    * @param string Property name
115    * @param string Default value
116    * @return string The property value
117    */
118   function getprop($name, $default = '')
119   {
120     $value = $this->config[$name];
121     
122     if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
123       $value = rcube_install::random_key(24);
124     
125     return $value !== null && $value !== '' ? $value : $default;
126   }
127
128
129   /**
130    * Take the default config file and replace the parameters
131    * with the submitted form data
132    *
133    * @param string Which config file (either 'main' or 'db')
134    * @return string The complete config file content
135    */
136   function create_config($which, $force = false)
137   {
138     $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
139
140     if (!$out)
141       return '[Warning: could not read the config template file]';
142
143     foreach ($this->config as $prop => $default) {
144
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))
189               $value[] = $_folder;
190         }
191       }
192       else if (is_bool($default)) {
193         $value = (bool)$value;
194       }
195       else if (is_numeric($value)) {
196         $value = intval($value);
197       }
198
199       // skip this property
200       if (!$force && !$this->configured && ($value == $default))
201         continue;
202
203       // save change
204       $this->config[$prop] = $value;
205
206       // replace the matching line in config file
207       $out = preg_replace(
208         '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
209         "'\\1 = ' . rcube_install::_dump_var(\$value) . ';'",
210         $out);
211     }
212
213     return trim($out);
214   }
215
216
217   /**
218    * Check the current configuration for missing properties
219    * and deprecated or obsolete settings
220    *
221    * @return array List with problems detected
222    */
223   function check_config()
224   {
225     $this->config = array();
226     $this->load_defaults();
227     $defaults = $this->config;
228     
229     $this->load_config();
230     if (!$this->configured)
231       return null;
232     
233     $out = $seen = array();
234     $required = array_flip($this->required_config);
235     
236     // iterate over the current configuration
237     foreach ($this->config as $prop => $value) {
238       if ($replacement = $this->replaced_config[$prop]) {
239         $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
240         $seen[$replacement] = true;
241       }
242       else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
243         $out['obsolete'][] = array('prop' => $prop);
244         $seen[$prop] = true;
245       }
246     }
247     
248     // iterate over default config
249     foreach ($defaults as $prop => $value) {
250       if (!isset($seen[$prop]) && !isset($this->config[$prop]) && isset($required[$prop]))
251         $out['missing'][] = array('prop' => $prop);
252     }
253
254     // check config dependencies and contradictions
255     if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
256       if (!extension_loaded('pspell')) {
257         $out['dependencies'][] = array('prop' => 'spellcheck_engine',
258           'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
259       }
260       else if (!empty($this->config['spellcheck_languages'])) {
261         foreach ($this->config['spellcheck_languages'] as $lang => $descr)
262           if (!pspell_new($lang))
263             $out['dependencies'][] = array('prop' => 'spellcheck_languages',
264               'explain' => "You are missing pspell support for language $lang ($descr)");
265       }
266     }
267     
268     if ($this->config['log_driver'] == 'syslog') {
269       if (!function_exists('openlog')) {
270         $out['dependencies'][] = array('prop' => 'log_driver',
271           'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
272       }
273       if (empty($this->config['syslog_id'])) {
274         $out['dependencies'][] = array('prop' => 'syslog_id',
275           'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
276       }
277     }
278     
279     // check ldap_public sources having global_search enabled
280     if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
281       foreach ($this->config['ldap_public'] as $ldap_public) {
282         if ($ldap_public['global_search']) {
283           $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
284           break;
285         }
286       }
287     }
288     
289     return $out;
290   }
291   
292   
293   /**
294    * Merge the current configuration with the defaults
295    * and copy replaced values to the new options.
296    */
297   function merge_config()
298   {
299     $current = $this->config;
300     $this->config = array();
301     $this->load_defaults();
302     
303     foreach ($this->replaced_config as $prop => $replacement) {
304       if (isset($current[$prop])) {
305         if ($prop == 'skin_path')
306           $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
307         else if ($prop == 'multiple_identities')
308           $this->config[$replacement] = $current[$prop] ? 2 : 0;
309         else
310           $this->config[$replacement] = $current[$prop];
311       }
312       unset($current[$prop]);
313     }
314     
315     foreach ($this->obsolete_config as $prop) {
316       unset($current[$prop]);
317     }
318     
319     // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
320     if (is_array($current['ldap_public'])) {
321       foreach ($current['ldap_public'] as $key => $ldap_public) {
322         if ($ldap_public['global_search']) {
323           $this->config['autocomplete_addressbooks'][] = $key;
324           unset($current['ldap_public'][$key]['global_search']);
325         }
326       }
327     }
328     
329     if ($current['keep_alive'] && $current['session_lifetime'] < $current['keep_alive'])
330       $current['session_lifetime'] = max(10, ceil($current['keep_alive'] / 60) * 2);
331     
332     $this->config  = array_merge($this->config, $current);
333     
334     foreach ((array)$current['ldap_public'] as $key => $values) {
335       $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
336     }
337   }
338   
339   /**
340    * Compare the local database schema with the reference schema
341    * required for this version of Roundcube
342    *
343    * @param boolean True if the schema schould be updated
344    * @return boolean True if the schema is up-to-date, false if not or an error occured
345    */
346   function db_schema_check($DB, $update = false)
347   {
348     if (!$this->configured)
349       return false;
350     
351     // read reference schema from mysql.initial.sql
352     $db_schema = $this->db_read_schema(INSTALL_PATH . 'SQL/mysql.initial.sql');
353     $errors = array();
354     
355     // check list of tables
356     $existing_tables = $DB->list_tables();
357
358     foreach ($db_schema as $table => $cols) {
359       $table = !empty($this->config['db_table_'.$table]) ? $this->config['db_table_'.$table] : $table;
360       if (!in_array($table, $existing_tables)) {
361         $errors[] = "Missing table '".$table."'";
362       }
363       else {  // compare cols
364         $db_cols = $DB->list_cols($table);
365         $diff = array_diff(array_keys($cols), $db_cols);
366         if (!empty($diff))
367           $errors[] = "Missing columns in table '$table': " . join(',', $diff);
368       }
369     }
370     
371     return !empty($errors) ? $errors : false;
372   }
373
374   /**
375    * Utility function to read database schema from an .sql file
376    */
377   private function db_read_schema($schemafile)
378   {
379     $lines = file($schemafile);
380     $table_block = false;
381     $schema = array();
382     foreach ($lines as $line) {
383       if (preg_match('/^\s*create table `?([a-z0-9_]+)`?/i', $line, $m)) {
384         $table_block = $m[1];
385       }
386       else if ($table_block && preg_match('/^\s*`?([a-z0-9_-]+)`?\s+([a-z]+)/', $line, $m)) {
387         $col = $m[1];
388         if (!in_array(strtoupper($col), array('PRIMARY','KEY','INDEX','UNIQUE','CONSTRAINT','REFERENCES','FOREIGN'))) {
389           $schema[$table_block][$col] = $m[2];
390         }
391       }
392     }
393     
394     return $schema;
395   }
396   
397   
398   /**
399    * Compare the local database schema with the reference schema
400    * required for this version of Roundcube
401    *
402    * @param boolean True if the schema schould be updated
403    * @return boolean True if the schema is up-to-date, false if not or an error occured
404    */
405   function mdb2_schema_check($update = false)
406   {
407     if (!$this->configured)
408       return false;
409     
410     $options = array(
411       'use_transactions' => false,
412       'log_line_break' => "\n",
413       'idxname_format' => '%s',
414       'debug' => false,
415       'quote_identifier' => true,
416       'force_defaults' => false,
417       'portability' => true
418     );
419     
420     $dsnw = $this->config['db_dsnw'];
421     $schema = MDB2_Schema::factory($dsnw, $options);
422     $schema->db->supported['transactions'] = false;
423     
424     if (PEAR::isError($schema)) {
425       $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
426       return false;
427     }
428     else {
429       $definition = $schema->getDefinitionFromDatabase();
430       $definition['charset'] = 'utf8';
431       
432       if (PEAR::isError($definition)) {
433         $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
434         return false;
435       }
436       
437       // load reference schema
438       $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']);
439
440       $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml';
441       
442       if (is_readable($ref_schema)) {
443         $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
444         
445         if (PEAR::isError($reference)) {
446           $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
447         }
448         else {
449           $diff = $schema->compareDefinitions($reference, $definition);
450           
451           if (empty($diff)) {
452             return true;
453           }
454           else if ($update) {
455             // update database schema with the diff from the above check
456             $success = $schema->alterDatabase($reference, $definition, $diff);
457             
458             if (PEAR::isError($success)) {
459               $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
460             }
461             else
462               return true;
463           }
464           echo '<pre>'; var_dump($diff); echo '</pre>';
465           return false;
466         }
467       }
468       else
469         $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
470         return false;
471     }
472     
473     return false;
474   }
475   
476   
477   /**
478    * Getter for the last error message
479    *
480    * @return string Error message or null if none exists
481    */
482   function get_error()
483   {
484       return $this->last_error['message'];
485   }
486   
487   
488   /**
489    * Return a list with all imap hosts configured
490    *
491    * @return array Clean list with imap hosts
492    */
493   function get_hostlist()
494   {
495     $default_hosts = (array)$this->getprop('default_host');
496     $out = array();
497     
498     foreach ($default_hosts as $key => $name) {
499       if (!empty($name))
500         $out[] = rcube_parse_host(is_numeric($key) ? $name : $key);
501     }
502     
503     return $out;
504   }
505   
506   /**
507    * Create a HTML dropdown to select a previous version of Roundcube
508    */
509   function versions_select($attrib = array())
510   {
511     $select = new html_select($attrib);
512     $select->add(array('0.1-stable', '0.1.1', '0.2-alpha', '0.2-beta', '0.2-stable', '0.3-stable', '0.3.1', '0.4-beta', '0.4.2', '0.5-beta', '0.5', '0.5.1'));
513     return $select;
514   }
515   
516   /**
517    * Return a list with available subfolders of the skin directory
518    */
519   function list_skins()
520   {
521     $skins = array();
522     $skindir = INSTALL_PATH . 'skins/';
523     foreach (glob($skindir . '*') as $path) {
524       if (is_dir($path) && is_readable($path)) {
525         $skins[] = substr($path, strlen($skindir));
526       }
527     }
528     return $skins;
529   }
530   
531   /**
532    * Display OK status
533    *
534    * @param string Test name
535    * @param string Confirm message
536    */
537   function pass($name, $message = '')
538   {
539     echo Q($name) . ':&nbsp; <span class="success">OK</span>';
540     $this->_showhint($message);
541   }
542   
543   
544   /**
545    * Display an error status and increase failure count
546    *
547    * @param string Test name
548    * @param string Error message
549    * @param string URL for details
550    */
551   function fail($name, $message = '', $url = '')
552   {
553     $this->failures++;
554     
555     echo Q($name) . ':&nbsp; <span class="fail">NOT OK</span>';
556     $this->_showhint($message, $url);
557   }
558
559
560   /**
561    * Display an error status for optional settings/features
562    *
563    * @param string Test name
564    * @param string Error message
565    * @param string URL for details
566    */
567   function optfail($name, $message = '', $url = '')
568   {
569     echo Q($name) . ':&nbsp; <span class="na">NOT OK</span>';
570     $this->_showhint($message, $url);
571   }
572   
573   
574   /**
575    * Display warning status
576    *
577    * @param string Test name
578    * @param string Warning message
579    * @param string URL for details
580    */
581   function na($name, $message = '', $url = '')
582   {
583     echo Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
584     $this->_showhint($message, $url);
585   }
586   
587   
588   function _showhint($message, $url = '')
589   {
590     $hint = Q($message);
591     
592     if ($url)
593       $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
594       
595     if ($hint)
596       echo '<span class="indent">(' . $hint . ')</span>';
597   }
598   
599   
600   static function _clean_array($arr)
601   {
602     $out = array();
603     
604     foreach (array_unique($arr) as $k => $val) {
605       if (!empty($val)) {
606         if (is_numeric($k))
607           $out[] = $val;
608         else
609           $out[$k] = $val;
610       }
611     }
612     
613     return $out;
614   }
615   
616   
617   static function _dump_var($var) {
618     if (is_array($var)) {
619       if (empty($var)) {
620         return 'array()';
621       }
622       else {  // check if all keys are numeric
623         $isnum = true;
624         foreach ($var as $key => $value) {
625           if (!is_numeric($key)) {
626             $isnum = false;
627             break;
628           }
629         }
630         
631         if ($isnum)
632           return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
633       }
634     }
635     
636     return var_export($var, true);
637   }
638   
639   
640   /**
641    * Initialize the database with the according schema
642    *
643    * @param object rcube_db Database connection
644    * @return boolen True on success, False on error
645    */
646   function init_db($DB)
647   {
648     $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
649     
650     // read schema file from /SQL/*
651     $fname = INSTALL_PATH . "SQL/$engine.initial.sql";
652     if ($sql = @file_get_contents($fname)) {
653       $this->exec_sql($sql, $DB);
654     }
655     else {
656       $this->fail('DB Schema', "Cannot read the schema file: $fname");
657       return false;
658     }
659     
660     if ($err = $this->get_error()) {
661       $this->fail('DB Schema', "Error creating database schema: $err");
662       return false;
663     }
664
665     return true;
666   }
667   
668   
669   /**
670    * Update database with SQL statements from SQL/*.update.sql
671    *
672    * @param object rcube_db Database connection
673    * @param string Version to update from
674    * @return boolen True on success, False on error
675    */
676   function update_db($DB, $version)
677   {
678     $version = strtolower($version);
679     $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
680     
681     // read schema file from /SQL/*
682     $fname = INSTALL_PATH . "SQL/$engine.update.sql";
683     if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
684       $from = false; $sql = '';
685       foreach ($lines as $line) {
686         $is_comment = preg_match('/^--/', $line);
687         if (!$from && $is_comment && preg_match('/from version\s([0-9.]+[a-z-]*)/', $line, $m)) {
688           $v = strtolower($m[1]);
689           if ($v == $version || version_compare($version, $v, '<='))
690             $from = true;
691         }
692         if ($from && !$is_comment)
693           $sql .= $line. "\n";
694       }
695       
696       if ($sql)
697         $this->exec_sql($sql, $DB);
698     }
699     else {
700       $this->fail('DB Schema', "Cannot read the update file: $fname");
701       return false;
702     }
703     
704     if ($err = $this->get_error()) {
705       $this->fail('DB Schema', "Error updating database: $err");
706       return false;
707     }
708
709     return true;
710   }
711   
712   
713   /**
714    * Execute the given SQL queries on the database connection
715    *
716    * @param string SQL queries to execute
717    * @param object rcube_db Database connection
718    * @return boolen True on success, False on error
719    */
720   function exec_sql($sql, $DB)
721   {
722     $buff = '';
723     foreach (explode("\n", $sql) as $line) {
724       if (preg_match('/^--/', $line) || trim($line) == '')
725         continue;
726         
727       $buff .= $line . "\n";
728       if (preg_match('/(;|^GO)$/', trim($line))) {
729         $DB->query($buff);
730         $buff = '';
731         if ($DB->is_error())
732           break;
733       }
734     }
735     
736     return !$DB->is_error();
737   }
738   
739   
740   /**
741    * Handler for Roundcube errors
742    */
743   function raise_error($p)
744   {
745       $this->last_error = $p;
746   }
747   
748   
749   /**
750    * Generarte a ramdom string to be used as encryption key
751    *
752    * @param int Key length
753    * @return string The generated random string
754    * @static
755    */
756   function random_key($length)
757   {
758     $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
759     $out = '';
760     
761     for ($i=0; $i < $length; $i++)
762       $out .= $alpha{rand(0, strlen($alpha)-1)};
763     
764     return $out;
765   }
766   
767 }
768