PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/core/Config.php

https://github.com/CodeYellowBV/piwik
PHP | 728 lines | 391 code | 94 blank | 243 comment | 61 complexity | 39abaa19862cfc4c6e217fc539380f61 MD5 | raw file
Possible License(s): LGPL-3.0, JSON, MIT, GPL-3.0, LGPL-2.1, GPL-2.0, AGPL-1.0, BSD-2-Clause, BSD-3-Clause
  1. <?php
  2. /**
  3. * Piwik - free/libre analytics platform
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. *
  8. */
  9. namespace Piwik;
  10. use Exception;
  11. /**
  12. * Singleton that provides read & write access to Piwik's INI configuration.
  13. *
  14. * This class reads and writes to the `config/config.ini.php` file. If config
  15. * options are missing from that file, this class will look for their default
  16. * values in `config/global.ini.php`.
  17. *
  18. * ### Examples
  19. *
  20. * **Getting a value:**
  21. *
  22. * // read the minimum_memory_limit option under the [General] section
  23. * $minValue = Config::getInstance()->General['minimum_memory_limit'];
  24. *
  25. * **Setting a value:**
  26. *
  27. * // set the minimum_memory_limit option
  28. * Config::getInstance()->General['minimum_memory_limit'] = 256;
  29. * Config::getInstance()->forceSave();
  30. *
  31. * **Setting an entire section:**
  32. *
  33. * Config::getInstance()->MySection = array('myoption' => 1);
  34. * Config::getInstance()->forceSave();
  35. *
  36. * @method static \Piwik\Config getInstance()
  37. */
  38. class Config extends Singleton
  39. {
  40. const DEFAULT_LOCAL_CONFIG_PATH = '/config/config.ini.php';
  41. const DEFAULT_COMMON_CONFIG_PATH = '/config/common.config.ini.php';
  42. const DEFAULT_GLOBAL_CONFIG_PATH = '/config/global.ini.php';
  43. /**
  44. * Contains configuration files values
  45. *
  46. * @var array
  47. */
  48. protected $initialized = false;
  49. protected $configGlobal = array();
  50. protected $configLocal = array();
  51. protected $configCommon = array();
  52. protected $configCache = array();
  53. protected $pathGlobal = null;
  54. protected $pathCommon = null;
  55. protected $pathLocal = null;
  56. /**
  57. * @var boolean
  58. */
  59. protected $isTest = false;
  60. /**
  61. * Constructor
  62. */
  63. public function __construct($pathGlobal = null, $pathLocal = null, $pathCommon = null)
  64. {
  65. $this->pathGlobal = $pathGlobal ?: self::getGlobalConfigPath();
  66. $this->pathCommon = $pathCommon ?: self::getCommonConfigPath();
  67. $this->pathLocal = $pathLocal ?: self::getLocalConfigPath();
  68. }
  69. /**
  70. * Returns the path to the local config file used by this instance.
  71. *
  72. * @return string
  73. */
  74. public function getLocalPath()
  75. {
  76. return $this->pathLocal;
  77. }
  78. /**
  79. * Returns the path to the global config file used by this instance.
  80. *
  81. * @return string
  82. */
  83. public function getGlobalPath()
  84. {
  85. return $this->pathGlobal;
  86. }
  87. /**
  88. * Returns the path to the common config file used by this instance.
  89. *
  90. * @return string
  91. */
  92. public function getCommonPath()
  93. {
  94. return $this->pathCommon;
  95. }
  96. /**
  97. * Enable test environment
  98. *
  99. * @param string $pathLocal
  100. * @param string $pathGlobal
  101. * @param string $pathCommon
  102. */
  103. public function setTestEnvironment($pathLocal = null, $pathGlobal = null, $pathCommon = null, $allowSaving = false)
  104. {
  105. if (!$allowSaving) {
  106. $this->isTest = true;
  107. }
  108. $this->clear();
  109. $this->pathLocal = $pathLocal ?: Config::getLocalConfigPath();
  110. $this->pathGlobal = $pathGlobal ?: Config::getGlobalConfigPath();
  111. $this->pathCommon = $pathCommon ?: Config::getCommonConfigPath();
  112. $this->init();
  113. // this proxy will not record any data in the production database.
  114. // this provides security for Piwik installs and tests were setup.
  115. if (isset($this->configGlobal['database_tests'])
  116. || isset($this->configLocal['database_tests'])
  117. ) {
  118. $this->__get('database_tests');
  119. $this->configCache['database'] = $this->configCache['database_tests'];
  120. }
  121. // Ensure local mods do not affect tests
  122. if (empty($pathGlobal)) {
  123. $this->configCache['log'] = $this->configGlobal['log'];
  124. $this->configCache['Debug'] = $this->configGlobal['Debug'];
  125. $this->configCache['mail'] = $this->configGlobal['mail'];
  126. $this->configCache['General'] = $this->configGlobal['General'];
  127. $this->configCache['Segments'] = $this->configGlobal['Segments'];
  128. $this->configCache['Tracker'] = $this->configGlobal['Tracker'];
  129. $this->configCache['Deletelogs'] = $this->configGlobal['Deletelogs'];
  130. $this->configCache['Deletereports'] = $this->configGlobal['Deletereports'];
  131. }
  132. // for unit tests, we set that no plugin is installed. This will force
  133. // the test initialization to create the plugins tables, execute ALTER queries, etc.
  134. $this->configCache['PluginsInstalled'] = array('PluginsInstalled' => array());
  135. }
  136. /**
  137. * Returns absolute path to the global configuration file
  138. *
  139. * @return string
  140. */
  141. protected static function getGlobalConfigPath()
  142. {
  143. return PIWIK_USER_PATH . self::DEFAULT_GLOBAL_CONFIG_PATH;
  144. }
  145. /**
  146. * Returns absolute path to the common configuration file.
  147. *
  148. * @return string
  149. */
  150. public static function getCommonConfigPath()
  151. {
  152. return PIWIK_USER_PATH . self::DEFAULT_COMMON_CONFIG_PATH;
  153. }
  154. /**
  155. * Returns absolute path to the local configuration file
  156. *
  157. * @return string
  158. */
  159. public static function getLocalConfigPath()
  160. {
  161. $path = self::getByDomainConfigPath();
  162. if ($path) {
  163. return $path;
  164. }
  165. return PIWIK_USER_PATH . self::DEFAULT_LOCAL_CONFIG_PATH;
  166. }
  167. private static function getLocalConfigInfoForHostname($hostname)
  168. {
  169. // Remove any port number to get actual hostname
  170. $hostname = Url::getHostSanitized($hostname);
  171. $perHostFilename = $hostname . '.config.ini.php';
  172. $pathDomainConfig = PIWIK_USER_PATH . '/config/' . $perHostFilename;
  173. return array('file' => $perHostFilename, 'path' => $pathDomainConfig);
  174. }
  175. public function getConfigHostnameIfSet()
  176. {
  177. if ($this->getByDomainConfigPath() === false) {
  178. return false;
  179. }
  180. return $this->getHostname();
  181. }
  182. public function getClientSideOptions()
  183. {
  184. $general = $this->General;
  185. return array(
  186. 'action_url_category_delimiter' => $general['action_url_category_delimiter'],
  187. 'autocomplete_min_sites' => $general['autocomplete_min_sites'],
  188. 'datatable_export_range_as_day' => $general['datatable_export_range_as_day'],
  189. 'datatable_row_limits' => $this->getDatatableRowLimits()
  190. );
  191. }
  192. /**
  193. * @param $general
  194. * @return mixed
  195. */
  196. private function getDatatableRowLimits()
  197. {
  198. $limits = $this->General['datatable_row_limits'];
  199. $limits = explode(",", $limits);
  200. $limits = array_map('trim', $limits);
  201. return $limits;
  202. }
  203. protected static function getByDomainConfigPath()
  204. {
  205. $host = self::getHostname();
  206. $hostConfig = self::getLocalConfigInfoForHostname($host);
  207. if (Filesystem::isValidFilename($hostConfig['file'])
  208. && file_exists($hostConfig['path'])
  209. ) {
  210. return $hostConfig['path'];
  211. }
  212. return false;
  213. }
  214. /**
  215. * Returns the hostname of the current request (without port number)
  216. *
  217. * @return string
  218. */
  219. public static function getHostname()
  220. {
  221. // Check trusted requires config file which is not ready yet
  222. $host = Url::getHost($checkIfTrusted = false);
  223. // Remove any port number to get actual hostname
  224. $host = Url::getHostSanitized($host);
  225. return $host;
  226. }
  227. /**
  228. * If set, Piwik will use the hostname config no matter if it exists or not. Useful for instance if you want to
  229. * create a new hostname config:
  230. *
  231. * $config = Config::getInstance();
  232. * $config->forceUsageOfHostnameConfig('piwik.example.com');
  233. * $config->save();
  234. *
  235. * @param string $hostname eg piwik.example.com
  236. * @return string
  237. * @throws \Exception In case the domain contains not allowed characters
  238. */
  239. public function forceUsageOfLocalHostnameConfig($hostname)
  240. {
  241. $hostConfig = static::getLocalConfigInfoForHostname($hostname);
  242. if (!Filesystem::isValidFilename($hostConfig['file'])) {
  243. throw new Exception('Hostname is not valid');
  244. }
  245. $this->pathLocal = $hostConfig['path'];
  246. $this->configLocal = array();
  247. $this->initialized = false;
  248. return $this->pathLocal;
  249. }
  250. /**
  251. * Returns `true` if the local configuration file is writable.
  252. *
  253. * @return bool
  254. */
  255. public function isFileWritable()
  256. {
  257. return is_writable($this->pathLocal);
  258. }
  259. /**
  260. * Clear in-memory configuration so it can be reloaded
  261. */
  262. public function clear()
  263. {
  264. $this->configGlobal = array();
  265. $this->configLocal = array();
  266. $this->configCache = array();
  267. $this->initialized = false;
  268. }
  269. /**
  270. * Read configuration from files into memory
  271. *
  272. * @throws Exception if local config file is not readable; exits for other errors
  273. */
  274. public function init()
  275. {
  276. $this->initialized = true;
  277. $reportError = SettingsServer::isTrackerApiRequest();
  278. // read defaults from global.ini.php
  279. if (!is_readable($this->pathGlobal) && $reportError) {
  280. Piwik_ExitWithMessage(Piwik::translate('General_ExceptionConfigurationFileNotFound', array($this->pathGlobal)));
  281. }
  282. $this->configGlobal = _parse_ini_file($this->pathGlobal, true);
  283. if (empty($this->configGlobal) && $reportError) {
  284. Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathGlobal, "parse_ini_file()")));
  285. }
  286. $this->configCommon = _parse_ini_file($this->pathCommon, true);
  287. // Check config.ini.php last
  288. $this->checkLocalConfigFound();
  289. $this->configLocal = _parse_ini_file($this->pathLocal, true);
  290. if (empty($this->configLocal) && $reportError) {
  291. Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathLocal, "parse_ini_file()")));
  292. }
  293. }
  294. public function existsLocalConfig()
  295. {
  296. return is_readable($this->pathLocal);
  297. }
  298. public function deleteLocalConfig()
  299. {
  300. $configLocal = $this->getLocalPath();
  301. unlink($configLocal);
  302. }
  303. public function checkLocalConfigFound()
  304. {
  305. if (!$this->existsLocalConfig()) {
  306. throw new Exception(Piwik::translate('General_ExceptionConfigurationFileNotFound', array($this->pathLocal)));
  307. }
  308. }
  309. /**
  310. * Decode HTML entities
  311. *
  312. * @param mixed $values
  313. * @return mixed
  314. */
  315. protected function decodeValues($values)
  316. {
  317. if (is_array($values)) {
  318. foreach ($values as &$value) {
  319. $value = $this->decodeValues($value);
  320. }
  321. return $values;
  322. }
  323. return html_entity_decode($values, ENT_COMPAT, 'UTF-8');
  324. }
  325. /**
  326. * Encode HTML entities
  327. *
  328. * @param mixed $values
  329. * @return mixed
  330. */
  331. protected function encodeValues($values)
  332. {
  333. if (is_array($values)) {
  334. foreach ($values as &$value) {
  335. $value = $this->encodeValues($value);
  336. }
  337. } else {
  338. $values = htmlentities($values, ENT_COMPAT, 'UTF-8');
  339. }
  340. return $values;
  341. }
  342. /**
  343. * Returns a configuration value or section by name.
  344. *
  345. * @param string $name The value or section name.
  346. * @return string|array The requested value requested. Returned by reference.
  347. * @throws Exception If the value requested not found in either `config.ini.php` or
  348. * `global.ini.php`.
  349. * @api
  350. */
  351. public function &__get($name)
  352. {
  353. if (!$this->initialized) {
  354. $this->init();
  355. // must be called here, not in init(), since setTestEnvironment() calls init(). (this avoids
  356. // infinite recursion)
  357. Piwik::postTestEvent('Config.createConfigSingleton',
  358. array($this, &$this->configCache, &$this->configLocal));
  359. }
  360. // check cache for merged section
  361. if (isset($this->configCache[$name])) {
  362. $tmp =& $this->configCache[$name];
  363. return $tmp;
  364. }
  365. $section = $this->getFromGlobalConfig($name);
  366. $sectionCommon = $this->getFromCommonConfig($name);
  367. if(empty($section) && !empty($sectionCommon)) {
  368. $section = $sectionCommon;
  369. } elseif(!empty($section) && !empty($sectionCommon)) {
  370. $section = $this->array_merge_recursive_distinct($section, $sectionCommon);
  371. }
  372. if (isset($this->configLocal[$name])) {
  373. // local settings override the global defaults
  374. $section = $section
  375. ? array_merge($section, $this->configLocal[$name])
  376. : $this->configLocal[$name];
  377. }
  378. if ($section === null && $name = 'superuser') {
  379. $user = $this->getConfigSuperUserForBackwardCompatibility();
  380. return $user;
  381. } else if ($section === null) {
  382. throw new Exception("Error while trying to read a specific config file entry <strong>'$name'</strong> from your configuration files.</b>If you just completed a Piwik upgrade, please check that the file config/global.ini.php was overwritten by the latest Piwik version.");
  383. }
  384. // cache merged section for later
  385. $this->configCache[$name] = $this->decodeValues($section);
  386. $tmp =& $this->configCache[$name];
  387. return $tmp;
  388. }
  389. /**
  390. * @deprecated since version 2.0.4
  391. */
  392. public function getConfigSuperUserForBackwardCompatibility()
  393. {
  394. try {
  395. $db = Db::get();
  396. $user = $db->fetchRow("SELECT login, email, password
  397. FROM " . Common::prefixTable("user") . "
  398. WHERE superuser_access = 1
  399. ORDER BY date_registered ASC LIMIT 1");
  400. if (!empty($user)) {
  401. $user['bridge'] = 1;
  402. return $user;
  403. }
  404. } catch (Exception $e) {}
  405. return array();
  406. }
  407. public function getFromGlobalConfig($name)
  408. {
  409. if (isset($this->configGlobal[$name])) {
  410. return $this->configGlobal[$name];
  411. }
  412. return null;
  413. }
  414. public function getFromCommonConfig($name)
  415. {
  416. if (isset($this->configCommon[$name])) {
  417. return $this->configCommon[$name];
  418. }
  419. return null;
  420. }
  421. /**
  422. * Sets a configuration value or section.
  423. *
  424. * @param string $name This section name or value name to set.
  425. * @param mixed $value
  426. * @api
  427. */
  428. public function __set($name, $value)
  429. {
  430. $this->configCache[$name] = $value;
  431. }
  432. /**
  433. * Comparison function
  434. *
  435. * @param mixed $elem1
  436. * @param mixed $elem2
  437. * @return int;
  438. */
  439. public static function compareElements($elem1, $elem2)
  440. {
  441. if (is_array($elem1)) {
  442. if (is_array($elem2)) {
  443. return strcmp(serialize($elem1), serialize($elem2));
  444. }
  445. return 1;
  446. }
  447. if (is_array($elem2)) {
  448. return -1;
  449. }
  450. if ((string)$elem1 === (string)$elem2) {
  451. return 0;
  452. }
  453. return ((string)$elem1 > (string)$elem2) ? 1 : -1;
  454. }
  455. /**
  456. * Compare arrays and return difference, such that:
  457. *
  458. * $modified = array_merge($original, $difference);
  459. *
  460. * @param array $original original array
  461. * @param array $modified modified array
  462. * @return array differences between original and modified
  463. */
  464. public function array_unmerge($original, $modified)
  465. {
  466. // return key/value pairs for keys in $modified but not in $original
  467. // return key/value pairs for keys in both $modified and $original, but values differ
  468. // ignore keys that are in $original but not in $modified
  469. return array_udiff_assoc($modified, $original, array(__CLASS__, 'compareElements'));
  470. }
  471. /**
  472. * Dump config
  473. *
  474. * @param array $configLocal
  475. * @param array $configGlobal
  476. * @param array $configCommon
  477. * @param array $configCache
  478. * @return string
  479. */
  480. public function dumpConfig($configLocal, $configGlobal, $configCommon, $configCache)
  481. {
  482. $dirty = false;
  483. $output = "; <?php exit; ?> DO NOT REMOVE THIS LINE\n";
  484. $output .= "; file automatically generated or modified by Piwik; you can manually override the default values in global.ini.php by redefining them in this file.\n";
  485. if (!$configCache) {
  486. return false;
  487. }
  488. // If there is a common.config.ini.php, this will ensure config.ini.php does not duplicate its values
  489. if(!empty($configCommon)) {
  490. $configGlobal = $this->array_merge_recursive_distinct($configGlobal, $configCommon);
  491. }
  492. if ($configLocal) {
  493. foreach ($configLocal as $name => $section) {
  494. if (!isset($configCache[$name])) {
  495. $configCache[$name] = $this->decodeValues($section);
  496. }
  497. }
  498. }
  499. $sectionNames = array_unique(array_merge(array_keys($configGlobal), array_keys($configCache)));
  500. foreach ($sectionNames as $section) {
  501. if (!isset($configCache[$section])) {
  502. continue;
  503. }
  504. // Only merge if the section exists in global.ini.php (in case a section only lives in config.ini.php)
  505. // get local and cached config
  506. $local = isset($configLocal[$section]) ? $configLocal[$section] : array();
  507. $config = $configCache[$section];
  508. // remove default values from both (they should not get written to local)
  509. if (isset($configGlobal[$section])) {
  510. $config = $this->array_unmerge($configGlobal[$section], $configCache[$section]);
  511. $local = $this->array_unmerge($configGlobal[$section], $local);
  512. }
  513. // if either local/config have non-default values and the other doesn't,
  514. // OR both have values, but different values, we must write to config.ini.php
  515. if (empty($local) xor empty($config)
  516. || (!empty($local)
  517. && !empty($config)
  518. && self::compareElements($config, $configLocal[$section]))
  519. ) {
  520. $dirty = true;
  521. }
  522. // no point in writing empty sections, so skip if the cached section is empty
  523. if (empty($config)) {
  524. continue;
  525. }
  526. $output .= "[$section]\n";
  527. foreach ($config as $name => $value) {
  528. $value = $this->encodeValues($value);
  529. if (is_numeric($name)) {
  530. $name = $section;
  531. $value = array($value);
  532. }
  533. if (is_array($value)) {
  534. foreach ($value as $currentValue) {
  535. $output .= $name . "[] = \"$currentValue\"\n";
  536. }
  537. } else {
  538. if (!is_numeric($value)) {
  539. $value = "\"$value\"";
  540. }
  541. $output .= $name . ' = ' . $value . "\n";
  542. }
  543. }
  544. $output .= "\n";
  545. }
  546. if ($dirty) {
  547. return $output;
  548. }
  549. return false;
  550. }
  551. /**
  552. * Write user configuration file
  553. *
  554. * @param array $configLocal
  555. * @param array $configGlobal
  556. * @param array $configCommon
  557. * @param array $configCache
  558. * @param string $pathLocal
  559. * @param bool $clear
  560. *
  561. * @throws \Exception if config file not writable
  562. */
  563. protected function writeConfig($configLocal, $configGlobal, $configCommon, $configCache, $pathLocal, $clear = true)
  564. {
  565. if ($this->isTest) {
  566. return;
  567. }
  568. $output = $this->dumpConfig($configLocal, $configGlobal, $configCommon, $configCache);
  569. if ($output !== false) {
  570. $success = @file_put_contents($pathLocal, $output);
  571. if (!$success) {
  572. throw $this->getConfigNotWritableException();
  573. }
  574. }
  575. if ($clear) {
  576. $this->clear();
  577. }
  578. }
  579. /**
  580. * Writes the current configuration to the **config.ini.php** file. Only writes options whose
  581. * values are different from the default.
  582. *
  583. * @api
  584. */
  585. public function forceSave()
  586. {
  587. $this->writeConfig($this->configLocal, $this->configGlobal, $this->configCommon, $this->configCache, $this->pathLocal);
  588. }
  589. /**
  590. * @throws \Exception
  591. */
  592. public function getConfigNotWritableException()
  593. {
  594. $path = "config/" . basename($this->pathLocal);
  595. return new Exception(Piwik::translate('General_ConfigFileIsNotWritable', array("(" . $path . ")", "")));
  596. }
  597. /**
  598. * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
  599. * keys to arrays rather than overwriting the value in the first array with the duplicate
  600. * value in the second array, as array_merge does. I.e., with array_merge_recursive,
  601. * this happens (documented behavior):
  602. *
  603. * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
  604. * => array('key' => array('org value', 'new value'));
  605. *
  606. * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
  607. * Matching keys' values in the second array overwrite those in the first array, as is the
  608. * case with array_merge, i.e.:
  609. *
  610. * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
  611. * => array('key' => array('new value'));
  612. *
  613. * Parameters are passed by reference, though only for performance reasons. They're not
  614. * altered by this function.
  615. *
  616. * @param array $array1
  617. * @param array $array2
  618. * @return array
  619. * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
  620. * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
  621. */
  622. function array_merge_recursive_distinct ( array &$array1, array &$array2 )
  623. {
  624. $merged = $array1;
  625. foreach ( $array2 as $key => &$value ) {
  626. if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) ) {
  627. $merged [$key] = $this->array_merge_recursive_distinct ( $merged [$key], $value );
  628. } else {
  629. $merged [$key] = $value;
  630. }
  631. }
  632. return $merged;
  633. }
  634. }