RoundCube Webmail
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

799 lines
23 KiB

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