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

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