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