PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/installer/rcube_install.php

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