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