source: github/installer/rcube_install.php @ 5fed074

HEADdev-browser-capabilitiespdo
Last change on this file since 5fed074 was 5fed074, checked in by Aleksander Machniak <alec@…>, 12 months ago

Always use 1 step as a fallback (#1488490)

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