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