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