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