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.

rcube_config.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2008-2014, The Roundcube Dev Team |
  6. | |
  7. | Licensed under the GNU General Public License version 3 or |
  8. | any later version with exceptions for skins & plugins. |
  9. | See the README file for a full license statement. |
  10. | |
  11. | PURPOSE: |
  12. | Class to read configuration settings |
  13. +-----------------------------------------------------------------------+
  14. | Author: Thomas Bruederli <roundcube@gmail.com> |
  15. +-----------------------------------------------------------------------+
  16. */
  17. /**
  18. * Configuration class for Roundcube
  19. *
  20. * @package Framework
  21. * @subpackage Core
  22. */
  23. class rcube_config
  24. {
  25. const DEFAULT_SKIN = 'larry';
  26. private $env = '';
  27. private $paths = array();
  28. private $prop = array();
  29. private $errors = array();
  30. private $userprefs = array();
  31. /**
  32. * Renamed options
  33. *
  34. * @var array
  35. */
  36. private $legacy_props = array(
  37. // new name => old name
  38. 'mail_pagesize' => 'pagesize',
  39. 'addressbook_pagesize' => 'pagesize',
  40. 'reply_mode' => 'top_posting',
  41. 'refresh_interval' => 'keep_alive',
  42. 'min_refresh_interval' => 'min_keep_alive',
  43. 'messages_cache_ttl' => 'message_cache_lifetime',
  44. 'mail_read_time' => 'preview_pane_mark_read',
  45. 'redundant_attachments_cache_ttl' => 'redundant_attachments_memcache_ttl',
  46. );
  47. /**
  48. * Object constructor
  49. *
  50. * @param string $env Environment suffix for config files to load
  51. */
  52. public function __construct($env = '')
  53. {
  54. $this->env = $env;
  55. if ($paths = getenv('RCUBE_CONFIG_PATH')) {
  56. $this->paths = explode(PATH_SEPARATOR, $paths);
  57. // make all paths absolute
  58. foreach ($this->paths as $i => $path) {
  59. if (!rcube_utils::is_absolute_path($path)) {
  60. if ($realpath = realpath(RCUBE_INSTALL_PATH . $path)) {
  61. $this->paths[$i] = unslashify($realpath) . '/';
  62. }
  63. else {
  64. unset($this->paths[$i]);
  65. }
  66. }
  67. else {
  68. $this->paths[$i] = unslashify($path) . '/';
  69. }
  70. }
  71. }
  72. if (defined('RCUBE_CONFIG_DIR') && !in_array(RCUBE_CONFIG_DIR, $this->paths)) {
  73. $this->paths[] = RCUBE_CONFIG_DIR;
  74. }
  75. if (empty($this->paths)) {
  76. $this->paths[] = RCUBE_INSTALL_PATH . 'config/';
  77. }
  78. $this->load();
  79. // Defaults, that we do not require you to configure,
  80. // but contain information that is used in various locations in the code:
  81. if (empty($this->prop['contactlist_fields'])) {
  82. $this->set('contactlist_fields', array('name', 'firstname', 'surname', 'email'));
  83. }
  84. }
  85. /**
  86. * @brief Guess the type the string may fit into.
  87. *
  88. * Look inside the string to determine what type might be best as a container.
  89. *
  90. * @param mixed $value The value to inspect
  91. *
  92. * @return The guess at the type.
  93. */
  94. private function guess_type($value)
  95. {
  96. $type = 'string';
  97. // array requires hint to be passed.
  98. if (preg_match('/^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$/', $value)) {
  99. $type = 'double';
  100. }
  101. else if (preg_match('/^\d+$/', $value)) {
  102. $type = 'integer';
  103. }
  104. else if (preg_match('/^(t(rue)?)|(f(alse)?)$/i', $value)) {
  105. $type = 'boolean';
  106. }
  107. return $type;
  108. }
  109. /**
  110. * @brief Parse environment variable into PHP type.
  111. *
  112. * Perform an appropriate parsing of the string to create the desired PHP type.
  113. *
  114. * @param string $string String to parse into PHP type
  115. * @param string $type Type of value to return
  116. *
  117. * @return Appropriately typed interpretation of $string.
  118. */
  119. private function parse_env($string, $type)
  120. {
  121. $_ = $string;
  122. switch ($type) {
  123. case 'boolean':
  124. $_ = (boolean) $_;
  125. break;
  126. case 'integer':
  127. $_ = (integer) $_;
  128. break;
  129. case 'double':
  130. $_ = (double) $_;
  131. break;
  132. case 'string':
  133. break;
  134. case 'array':
  135. $_ = json_decode($_, true);
  136. break;
  137. case 'object':
  138. $_ = json_decode($_, false);
  139. break;
  140. case 'resource':
  141. case 'NULL':
  142. default:
  143. $_ = $this->parse_env($_, $this->guess_type($_));
  144. }
  145. return $_;
  146. }
  147. /**
  148. * @brief Get environment variable value.
  149. *
  150. * Retrieve an environment variable's value or if it's not found, return the
  151. * provided default value.
  152. *
  153. * @param string $varname Environment variable name
  154. * @param mixed $default_value Default value to return if necessary
  155. * @param string $type Type of value to return
  156. *
  157. * @return Value of the environment variable or default if not found.
  158. */
  159. private function getenv_default($varname, $default_value, $type = null)
  160. {
  161. $value = getenv($varname);
  162. if ($value === false) {
  163. $value = $default_value;
  164. }
  165. else {
  166. $value = $this->parse_env($value, $type ?: gettype($default_value));
  167. }
  168. return $value;
  169. }
  170. /**
  171. * Load config from local config file
  172. *
  173. * @todo Remove global $CONFIG
  174. */
  175. private function load()
  176. {
  177. // Load default settings
  178. if (!$this->load_from_file('defaults.inc.php')) {
  179. $this->errors[] = 'defaults.inc.php was not found.';
  180. }
  181. // load main config file
  182. if (!$this->load_from_file('config.inc.php')) {
  183. // Old configuration files
  184. if (!$this->load_from_file('main.inc.php') || !$this->load_from_file('db.inc.php')) {
  185. $this->errors[] = 'config.inc.php was not found.';
  186. }
  187. else if (rand(1,100) == 10) { // log warning on every 100th request (average)
  188. trigger_error("config.inc.php was not found. Please migrate your config by running bin/update.sh", E_USER_WARNING);
  189. }
  190. }
  191. // load host-specific configuration
  192. $this->load_host_config();
  193. // set skin (with fallback to old 'skin_path' property)
  194. if (empty($this->prop['skin'])) {
  195. if (!empty($this->prop['skin_path'])) {
  196. $this->prop['skin'] = str_replace('skins/', '', unslashify($this->prop['skin_path']));
  197. }
  198. else {
  199. $this->prop['skin'] = self::DEFAULT_SKIN;
  200. }
  201. }
  202. // larry is the new default skin :-)
  203. if ($this->prop['skin'] == 'default') {
  204. $this->prop['skin'] = self::DEFAULT_SKIN;
  205. }
  206. // fix paths
  207. foreach (array('log_dir' => 'logs', 'temp_dir' => 'temp') as $key => $dir) {
  208. foreach (array($this->prop[$key], '../' . $this->prop[$key], RCUBE_INSTALL_PATH . $dir) as $path) {
  209. if ($path && ($realpath = realpath(unslashify($path)))) {
  210. $this->prop[$key] = $realpath;
  211. break;
  212. }
  213. }
  214. }
  215. // fix default imap folders encoding
  216. foreach (array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox') as $folder) {
  217. $this->prop[$folder] = rcube_charset::convert($this->prop[$folder], RCUBE_CHARSET, 'UTF7-IMAP');
  218. }
  219. // set PHP error logging according to config
  220. if ($this->prop['debug_level'] & 1) {
  221. ini_set('log_errors', 1);
  222. if ($this->prop['log_driver'] == 'syslog') {
  223. ini_set('error_log', 'syslog');
  224. }
  225. else {
  226. ini_set('error_log', $this->prop['log_dir'].'/errors');
  227. }
  228. }
  229. // enable display_errors in 'show' level, but not for ajax requests
  230. ini_set('display_errors', intval(empty($_REQUEST['_remote']) && ($this->prop['debug_level'] & 4)));
  231. // remove deprecated properties
  232. unset($this->prop['dst_active']);
  233. // export config data
  234. $GLOBALS['CONFIG'] = &$this->prop;
  235. }
  236. /**
  237. * Load a host-specific config file if configured
  238. * This will merge the host specific configuration with the given one
  239. */
  240. private function load_host_config()
  241. {
  242. if (empty($this->prop['include_host_config'])) {
  243. return;
  244. }
  245. foreach (array('HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR') as $key) {
  246. $fname = null;
  247. $name = $_SERVER[$key];
  248. if (!$name) {
  249. continue;
  250. }
  251. if (is_array($this->prop['include_host_config'])) {
  252. $fname = $this->prop['include_host_config'][$name];
  253. }
  254. else {
  255. $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $name) . '.inc.php';
  256. }
  257. if ($fname && $this->load_from_file($fname)) {
  258. return;
  259. }
  260. }
  261. }
  262. /**
  263. * Read configuration from a file
  264. * and merge with the already stored config values
  265. *
  266. * @param string $file Name of the config file to be loaded
  267. *
  268. * @return booelan True on success, false on failure
  269. */
  270. public function load_from_file($file)
  271. {
  272. $success = false;
  273. foreach ($this->resolve_paths($file) as $fpath) {
  274. if ($fpath && is_file($fpath) && is_readable($fpath)) {
  275. // use output buffering, we don't need any output here
  276. ob_start();
  277. include($fpath);
  278. ob_end_clean();
  279. if (is_array($config)) {
  280. $this->merge($config);
  281. $success = true;
  282. }
  283. // deprecated name of config variable
  284. if (is_array($rcmail_config)) {
  285. $this->merge($rcmail_config);
  286. $success = true;
  287. }
  288. }
  289. }
  290. return $success;
  291. }
  292. /**
  293. * Helper method to resolve absolute paths to the given config file.
  294. * This also takes the 'env' property into account.
  295. *
  296. * @param string $file Filename or absolute file path
  297. * @param boolean $use_env Return -$env file path if exists
  298. *
  299. * @return array List of candidates in config dir path(s)
  300. */
  301. public function resolve_paths($file, $use_env = true)
  302. {
  303. $files = array();
  304. $abs_path = rcube_utils::is_absolute_path($file);
  305. foreach ($this->paths as $basepath) {
  306. $realpath = $abs_path ? $file : realpath($basepath . '/' . $file);
  307. // check if <file>-env.ini exists
  308. if ($realpath && $use_env && !empty($this->env)) {
  309. $envfile = preg_replace('/\.(inc.php)$/', '-' . $this->env . '.\\1', $realpath);
  310. if (is_file($envfile)) {
  311. $realpath = $envfile;
  312. }
  313. }
  314. if ($realpath) {
  315. $files[] = $realpath;
  316. // no need to continue the loop if an absolute file path is given
  317. if ($abs_path) {
  318. break;
  319. }
  320. }
  321. }
  322. return $files;
  323. }
  324. /**
  325. * Getter for a specific config parameter
  326. *
  327. * @param string $name Parameter name
  328. * @param mixed $def Default value if not set
  329. *
  330. * @return mixed The requested config value
  331. */
  332. public function get($name, $def = null)
  333. {
  334. if (isset($this->prop[$name])) {
  335. $result = $this->prop[$name];
  336. }
  337. else {
  338. $result = $def;
  339. }
  340. $result = $this->getenv_default('ROUNDCUBE_' . strtoupper($name), $result);
  341. $rcube = rcube::get_instance();
  342. if ($name == 'timezone') {
  343. if (empty($result) || $result == 'auto') {
  344. $result = $this->client_timezone();
  345. }
  346. }
  347. else if ($name == 'client_mimetypes') {
  348. if (!$result && !$def) {
  349. $result = 'text/plain,text/html,text/xml'
  350. . ',image/jpeg,image/gif,image/png,image/bmp,image/tiff,image/webp'
  351. . ',application/x-javascript,application/pdf,application/x-shockwave-flash';
  352. }
  353. if ($result && is_string($result)) {
  354. $result = explode(',', $result);
  355. }
  356. }
  357. $plugin = $rcube->plugins->exec_hook('config_get', array(
  358. 'name' => $name, 'default' => $def, 'result' => $result));
  359. return $plugin['result'];
  360. }
  361. /**
  362. * Setter for a config parameter
  363. *
  364. * @param string $name Parameter name
  365. * @param mixed $value Parameter value
  366. */
  367. public function set($name, $value)
  368. {
  369. $this->prop[$name] = $value;
  370. }
  371. /**
  372. * Override config options with the given values (eg. user prefs)
  373. *
  374. * @param array $prefs Hash array with config props to merge over
  375. */
  376. public function merge($prefs)
  377. {
  378. $prefs = $this->fix_legacy_props($prefs);
  379. $this->prop = array_merge($this->prop, $prefs, $this->userprefs);
  380. }
  381. /**
  382. * Merge the given prefs over the current config
  383. * and make sure that they survive further merging.
  384. *
  385. * @param array $prefs Hash array with user prefs
  386. */
  387. public function set_user_prefs($prefs)
  388. {
  389. $prefs = $this->fix_legacy_props($prefs);
  390. // Honor the dont_override setting for any existing user preferences
  391. $dont_override = $this->get('dont_override');
  392. if (is_array($dont_override) && !empty($dont_override)) {
  393. foreach ($dont_override as $key) {
  394. unset($prefs[$key]);
  395. }
  396. }
  397. // larry is the new default skin :-)
  398. if ($prefs['skin'] == 'default') {
  399. $prefs['skin'] = self::DEFAULT_SKIN;
  400. }
  401. $this->userprefs = $prefs;
  402. $this->prop = array_merge($this->prop, $prefs);
  403. }
  404. /**
  405. * Getter for all config options
  406. *
  407. * @return array Hash array containing all config properties
  408. */
  409. public function all()
  410. {
  411. $props = $this->prop;
  412. foreach ($props as $prop_name => $prop_value) {
  413. $props[$prop_name] = $this->getenv_default('ROUNDCUBE_' . strtoupper($prop_name), $prop_value);
  414. }
  415. $rcube = rcube::get_instance();
  416. $plugin = $rcube->plugins->exec_hook('config_get', array(
  417. 'name' => '*', 'result' => $props));
  418. return $plugin['result'];
  419. }
  420. /**
  421. * Special getter for user's timezone offset including DST
  422. *
  423. * @return float Timezone offset (in hours)
  424. * @deprecated
  425. */
  426. public function get_timezone()
  427. {
  428. if ($tz = $this->get('timezone')) {
  429. try {
  430. $tz = new DateTimeZone($tz);
  431. return $tz->getOffset(new DateTime('now')) / 3600;
  432. }
  433. catch (Exception $e) {
  434. }
  435. }
  436. return 0;
  437. }
  438. /**
  439. * Return requested DES crypto key.
  440. *
  441. * @param string $key Crypto key name
  442. *
  443. * @return string Crypto key
  444. */
  445. public function get_crypto_key($key)
  446. {
  447. // Bomb out if the requested key does not exist
  448. if (!array_key_exists($key, $this->prop) || empty($this->prop[$key])) {
  449. rcube::raise_error(array(
  450. 'code' => 500, 'type' => 'php',
  451. 'file' => __FILE__, 'line' => __LINE__,
  452. 'message' => "Request for unconfigured crypto key \"$key\""
  453. ), true, true);
  454. }
  455. return $this->prop[$key];
  456. }
  457. /**
  458. * Return configured crypto method.
  459. *
  460. * @return string Crypto method
  461. */
  462. public function get_crypto_method()
  463. {
  464. return $this->get('cipher_method') ?: 'DES-EDE3-CBC';
  465. }
  466. /**
  467. * Try to autodetect operating system and find the correct line endings
  468. *
  469. * @return string The appropriate mail header delimiter
  470. * @deprecated Since 1.3 we don't use mail()
  471. */
  472. public function header_delimiter()
  473. {
  474. // use the configured delimiter for headers
  475. if (!empty($this->prop['mail_header_delimiter'])) {
  476. $delim = $this->prop['mail_header_delimiter'];
  477. if ($delim == "\n" || $delim == "\r\n") {
  478. return $delim;
  479. }
  480. else {
  481. rcube::raise_error(array(
  482. 'code' => 500, 'type' => 'php',
  483. 'file' => __FILE__, 'line' => __LINE__,
  484. 'message' => "Invalid mail_header_delimiter setting"
  485. ), true, false);
  486. }
  487. }
  488. $php_os = strtolower(substr(PHP_OS, 0, 3));
  489. if ($php_os == 'win')
  490. return "\r\n";
  491. if ($php_os == 'mac')
  492. return "\r\n";
  493. return "\n";
  494. }
  495. /**
  496. * Return the mail domain configured for the given host
  497. *
  498. * @param string $host IMAP host
  499. * @param boolean $encode If true, domain name will be converted to IDN ASCII
  500. *
  501. * @return string Resolved SMTP host
  502. */
  503. public function mail_domain($host, $encode=true)
  504. {
  505. $domain = $host;
  506. if (is_array($this->prop['mail_domain'])) {
  507. if (isset($this->prop['mail_domain'][$host])) {
  508. $domain = $this->prop['mail_domain'][$host];
  509. }
  510. }
  511. else if (!empty($this->prop['mail_domain'])) {
  512. $domain = rcube_utils::parse_host($this->prop['mail_domain']);
  513. }
  514. if ($encode) {
  515. $domain = rcube_utils::idn_to_ascii($domain);
  516. }
  517. return $domain;
  518. }
  519. /**
  520. * Getter for error state
  521. *
  522. * @return mixed Error message on error, False if no errors
  523. */
  524. public function get_error()
  525. {
  526. return empty($this->errors) ? false : join("\n", $this->errors);
  527. }
  528. /**
  529. * Internal getter for client's (browser) timezone identifier
  530. */
  531. private function client_timezone()
  532. {
  533. // @TODO: remove this legacy timezone handling in the future
  534. $props = $this->fix_legacy_props(array('timezone' => $_SESSION['timezone']));
  535. if (!empty($props['timezone'])) {
  536. try {
  537. $tz = new DateTimeZone($props['timezone']);
  538. return $tz->getName();
  539. }
  540. catch (Exception $e) { /* gracefully ignore */ }
  541. }
  542. // fallback to server's timezone
  543. return date_default_timezone_get();
  544. }
  545. /**
  546. * Convert legacy options into new ones
  547. *
  548. * @param array $props Hash array with config props
  549. *
  550. * @return array Converted config props
  551. */
  552. private function fix_legacy_props($props)
  553. {
  554. foreach ($this->legacy_props as $new => $old) {
  555. if (isset($props[$old])) {
  556. if (!isset($props[$new])) {
  557. $props[$new] = $props[$old];
  558. }
  559. unset($props[$old]);
  560. }
  561. }
  562. // convert deprecated numeric timezone value
  563. if (isset($props['timezone']) && is_numeric($props['timezone'])) {
  564. if ($tz = self::timezone_name_from_abbr($props['timezone'])) {
  565. $props['timezone'] = $tz;
  566. }
  567. else {
  568. unset($props['timezone']);
  569. }
  570. }
  571. // translate old `preview_pane` settings to `layout`
  572. if (isset($props['preview_pane']) && !isset($props['layout'])) {
  573. $props['layout'] = $props['preview_pane'] ? 'desktop' : 'list';
  574. unset($props['preview_pane']);
  575. }
  576. return $props;
  577. }
  578. /**
  579. * timezone_name_from_abbr() replacement. Converts timezone offset
  580. * into timezone name abbreviation.
  581. *
  582. * @param float $offset Timezone offset (in hours)
  583. *
  584. * @return string Timezone abbreviation
  585. */
  586. static public function timezone_name_from_abbr($offset)
  587. {
  588. // List of timezones here is not complete - https://bugs.php.net/bug.php?id=44780
  589. if ($tz = timezone_name_from_abbr('', $offset * 3600, 0)) {
  590. return $tz;
  591. }
  592. // try with more complete list (#1489261)
  593. $timezones = array(
  594. '-660' => "Pacific/Apia",
  595. '-600' => "Pacific/Honolulu",
  596. '-570' => "Pacific/Marquesas",
  597. '-540' => "America/Anchorage",
  598. '-480' => "America/Los_Angeles",
  599. '-420' => "America/Denver",
  600. '-360' => "America/Chicago",
  601. '-300' => "America/New_York",
  602. '-270' => "America/Caracas",
  603. '-240' => "America/Halifax",
  604. '-210' => "Canada/Newfoundland",
  605. '-180' => "America/Sao_Paulo",
  606. '-60' => "Atlantic/Azores",
  607. '0' => "Europe/London",
  608. '60' => "Europe/Paris",
  609. '120' => "Europe/Helsinki",
  610. '180' => "Europe/Moscow",
  611. '210' => "Asia/Tehran",
  612. '240' => "Asia/Dubai",
  613. '270' => "Asia/Kabul",
  614. '300' => "Asia/Karachi",
  615. '330' => "Asia/Kolkata",
  616. '345' => "Asia/Katmandu",
  617. '360' => "Asia/Yekaterinburg",
  618. '390' => "Asia/Rangoon",
  619. '420' => "Asia/Krasnoyarsk",
  620. '480' => "Asia/Shanghai",
  621. '525' => "Australia/Eucla",
  622. '540' => "Asia/Tokyo",
  623. '570' => "Australia/Adelaide",
  624. '600' => "Australia/Melbourne",
  625. '630' => "Australia/Lord_Howe",
  626. '660' => "Asia/Vladivostok",
  627. '690' => "Pacific/Norfolk",
  628. '720' => "Pacific/Auckland",
  629. '765' => "Pacific/Chatham",
  630. '780' => "Pacific/Enderbury",
  631. '840' => "Pacific/Kiritimati",
  632. );
  633. return $timezones[(string) intval($offset * 60)];
  634. }
  635. }