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