Welcome to mirror list, hosted at ThFree Co, Russian Federation.

IniFileChain.php « Config « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ff9798762ddb8779f6eddd074640f9fd38ad99b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */
namespace Piwik\Config;

use Piwik\Common;
use Matomo\Ini\IniReader;
use Matomo\Ini\IniReadingException;
use Matomo\Ini\IniWriter;
use Piwik\Piwik;

/**
 * Manages a list of INI files where the settings in each INI file merge with or override the
 * settings in the previous INI file.
 *
 * The IniFileChain class manages two types of INI files: multiple default setting files and one
 * user settings file.
 *
 * The default setting files (for example, global.ini.php & common.ini.php) hold the default setting values.
 * The settings in these files are merged recursively, however, array settings in one file will still
 * overwrite settings in the previous file.
 *
 * Default settings files cannot be modified through the IniFileChain class.
 *
 * The user settings file (for example, config.ini.php) holds the actual setting values. Settings in the
 * user settings files overwrite other settings. So array settings will not merge w/ previous values.
 *
 * HTML characters and dollar signs are stored as encoded HTML entities in INI files. This prevents
 * several `parse_ini_file` issues, including one where parse_ini_file tries to insert a variable
 * into a setting value if a string like `"$varname" is present.
 */
class IniFileChain
{
    const CONFIG_CACHE_KEY = 'config.ini';
    /**
     * Maps INI file names with their parsed contents. The order of the files signifies the order
     * in the chain. Files with lower index are overwritten/merged with files w/ a higher index.
     *
     * @var array
     */
    protected $settingsChain = array();

    /**
     * The merged INI settings.
     *
     * @var array
     */
    protected $mergedSettings = array();

    /**
     * Constructor.
     *
     * @param string[] $defaultSettingsFiles The list of paths to INI files w/ the default setting values.
     * @param string|null $userSettingsFile The path to the user settings file.
     */
    public function __construct(array $defaultSettingsFiles = array(), $userSettingsFile = null)
    {
        $this->reload($defaultSettingsFiles, $userSettingsFile);
    }

    /**
     * Return setting section by reference.
     *
     * @param string $name
     * @return mixed
     */
    public function &get($name)
    {
        if (!isset($this->mergedSettings[$name])) {
            $this->mergedSettings[$name] = array();
        }

        $result =& $this->mergedSettings[$name];
        return $result;
    }

    /**
     * Return setting section from a specific file, rather than the current merged settings.
     *
     * @param string $file The path of the file. Should be the path used in construction or reload().
     * @param string $name The name of the section to access.
     */
    public function getFrom($file, $name)
    {
        return @$this->settingsChain[$file][$name];
    }

    /**
     * Sets a setting value.
     *
     * @param string $name
     * @param mixed $value
     */
    public function set($name, $value)
    {
        $this->mergedSettings[$name] = $value;
    }

    /**
     * Returns all settings. Changes made to the array result will be reflected in the
     * IniFileChain instance.
     *
     * @return array
     */
    public function &getAll()
    {
        return $this->mergedSettings;
    }

    /**
     * Dumps the current in-memory setting values to a string in INI format and returns it.
     *
     * @param string $header The header of the output INI file.
     * @return string The dumped INI contents.
     */
    public function dump($header = '')
    {
        return $this->dumpSettings($this->mergedSettings, $header);
    }

    /**
     * Writes the difference of the in-memory setting values and the on-disk user settings file setting
     * values to a string in INI format, and returns it.
     *
     * If a config section is identical to the default settings section (as computed by merging
     * all default setting files), it is not written to the user settings file.
     *
     * @param string $header The header of the INI output.
     * @return string The dumped INI contents.
     */
    public function dumpChanges($header = '')
    {
        $userSettingsFile = $this->getUserSettingsFile();

        $defaultSettings = $this->getMergedDefaultSettings();
        $existingMutableSettings = $this->settingsChain[$userSettingsFile];

        $dirty = false;

        $configToWrite = array();
        foreach ($this->mergedSettings as $sectionName => $changedSection) {
            if(isset($existingMutableSettings[$sectionName])){
                $existingMutableSection = $existingMutableSettings[$sectionName];
            } else{
                $existingMutableSection = array();
            }

            // remove default values from both (they should not get written to local)
            if (isset($defaultSettings[$sectionName])) {
                $changedSection = $this->arrayUnmerge($defaultSettings[$sectionName], $changedSection);
                $existingMutableSection = $this->arrayUnmerge($defaultSettings[$sectionName], $existingMutableSection);
            }

            // if either local/config have non-default values and the other doesn't,
            // OR both have values, but different values, we must write to config.ini.php
            if (empty($changedSection) xor empty($existingMutableSection)
                || (!empty($changedSection)
                    && !empty($existingMutableSection)
                    && self::compareElements($changedSection, $existingMutableSection))
            ) {
                $dirty = true;
            }

            $configToWrite[$sectionName] = $changedSection;
        }

        if ($dirty) {
            // sort config sections by how early they appear in the file chain
            $self = $this;
            uksort($configToWrite, function ($sectionNameLhs, $sectionNameRhs) use ($self) {
                $lhsIndex = $self->findIndexOfFirstFileWithSection($sectionNameLhs);
                $rhsIndex = $self->findIndexOfFirstFileWithSection($sectionNameRhs);

                if ($lhsIndex == $rhsIndex) {
                    $lhsIndexInFile = $self->getIndexOfSectionInFile($lhsIndex, $sectionNameLhs);
                    $rhsIndexInFile = $self->getIndexOfSectionInFile($rhsIndex, $sectionNameRhs);

                    if ($lhsIndexInFile == $rhsIndexInFile) {
                        return 0;
                    } elseif ($lhsIndexInFile < $rhsIndexInFile) {
                        return -1;
                    } else {
                        return 1;
                    }
                } elseif ($lhsIndex < $rhsIndex) {
                    return -1;
                } else {
                    return 1;
                }
            });

            return $this->dumpSettings($configToWrite, $header);
        } else {
            return null;
        }
    }

    /**
     * Reloads settings from disk.
     */
    public function reload($defaultSettingsFiles = array(), $userSettingsFile = null)
    {
        if (!empty($defaultSettingsFiles)
            || !empty($userSettingsFile)
        ) {
            $this->resetSettingsChain($defaultSettingsFiles, $userSettingsFile);
        }

        $hasAbsoluteConfigFile = !empty($userSettingsFile) && strpos($userSettingsFile, DIRECTORY_SEPARATOR) === 0;
        $useConfigCache = !empty($GLOBALS['ENABLE_CONFIG_PHP_CACHE']) && $hasAbsoluteConfigFile;

        if ($useConfigCache) {
            $cache = new Cache();
            $values = $cache->doFetch(self::CONFIG_CACHE_KEY);
            
            if (!empty($values)
                && isset($values['mergedSettings'])
                && isset($values['settingsChain'][$userSettingsFile])) {
                $this->mergedSettings = $values['mergedSettings'];
                $this->settingsChain = $values['settingsChain'];
                return;
            }
        }

        $reader = new IniReader();
        foreach ($this->settingsChain as $file => $ignore) {
            if (is_readable($file)) {
                try {
                    $contents = $reader->readFile($file);
                    $this->settingsChain[$file] = $this->decodeValues($contents);
                } catch (IniReadingException $ex) {
                    throw new IniReadingException('Unable to read INI file {' . $file . '}: ' . $ex->getMessage() . "\n Your host may have disabled parse_ini_file().");
                }

                $this->decodeValues($this->settingsChain[$file]);
            }
        }

        $merged = $this->mergeFileSettings();
        // remove reference to $this->settingsChain... otherwise dump() or compareElements() will never notice a difference
        // on PHP 7+ as they would be always equal
        $this->mergedSettings = $this->copy($merged);

        if (!empty($GLOBALS['MATOMO_MODIFY_CONFIG_SETTINGS']) && !empty($this->mergedSettings)) {
            $this->mergedSettings = call_user_func($GLOBALS['MATOMO_MODIFY_CONFIG_SETTINGS'], $this->mergedSettings);
        }
        
        if ($useConfigCache
            && !empty($this->mergedSettings)
            && !empty($this->settingsChain)) {

            $ttlOneHour = 3600;
            $cache = new Cache();
            if ($cache->isValidHost($this->mergedSettings)) {
                // we make sure to save the config only if the host is valid...
                $data = array('mergedSettings' => $this->mergedSettings, 'settingsChain' => $this->settingsChain);
                $cache->doSave(self::CONFIG_CACHE_KEY, $data, $ttlOneHour);
            }
        }
    }

    public function deleteConfigCache()
    {
        if (!empty($GLOBALS['ENABLE_CONFIG_PHP_CACHE'])) {
            $cache = new Cache();
            $cache->doDelete(IniFileChain::CONFIG_CACHE_KEY);
        }
    }

    private function copy($merged)
    {
        $copy = array();
        foreach ($merged as $index => $value) {
            if (is_array($value)) {
                $copy[$index] = $this->copy($value);
            } else {
                $copy[$index] = $value;
            }
        }
        return $copy;
    }

    private function resetSettingsChain($defaultSettingsFiles, $userSettingsFile)
    {
        $this->settingsChain = array();

        if (!empty($defaultSettingsFiles)) {
            foreach ($defaultSettingsFiles as $file) {
                $this->settingsChain[$file] = null;
            }
        }

        if (!empty($userSettingsFile)) {
            $this->settingsChain[$userSettingsFile] = null;
        }
    }

    protected function mergeFileSettings()
    {
        $mergedSettings = $this->getMergedDefaultSettings();

        $userSettings = end($this->settingsChain) ?: array();
        foreach ($userSettings as $sectionName => $section) {
            if (!isset($mergedSettings[$sectionName])) {
                $mergedSettings[$sectionName] = $section;
            } else {
                // the last user settings file completely overwrites INI sections. the other files in the chain
                // can add to array options
                $mergedSettings[$sectionName] = array_merge($mergedSettings[$sectionName], $section);
            }
        }

        return $mergedSettings;
    }

    protected function getMergedDefaultSettings()
    {
        $userSettingsFile = $this->getUserSettingsFile();

        $mergedSettings = array();
        foreach ($this->settingsChain as $file => $settings) {
            if ($file == $userSettingsFile
                || empty($settings)
            ) {
                continue;
            }

            foreach ($settings as $sectionName => $section) {
                if (!isset($mergedSettings[$sectionName])) {
                    $mergedSettings[$sectionName] = $section;
                } else {
                    $mergedSettings[$sectionName] = $this->array_merge_recursive_distinct($mergedSettings[$sectionName], $section);
                }
            }
        }
        return $mergedSettings;
    }

    protected function getUserSettingsFile()
    {
        // the user settings file is the last key in $settingsChain
        end($this->settingsChain);
        return key($this->settingsChain);
    }

    /**
     * Comparison function
     *
     * @param mixed $elem1
     * @param mixed $elem2
     * @return int;
     */
    public static function compareElements($elem1, $elem2)
    {
        if (is_array($elem1)) {
            if (is_array($elem2)) {
                return strcmp(serialize($elem1), serialize($elem2));
            }

            return 1;
        }

        if (is_array($elem2)) {
            return -1;
        }

        if ((string)$elem1 === (string)$elem2) {
            return 0;
        }

        return ((string)$elem1 > (string)$elem2) ? 1 : -1;
    }

    /**
     * Compare arrays and return difference, such that:
     *
     *     $modified = array_merge($original, $difference);
     *
     * @param array $original original array
     * @param array $modified modified array
     * @return array differences between original and modified
     */
    public function arrayUnmerge($original, $modified)
    {
        // return key/value pairs for keys in $modified but not in $original
        // return key/value pairs for keys in both $modified and $original, but values differ
        // ignore keys that are in $original but not in $modified

        if (empty($original) || !is_array($original)) {
            $original = array();
        }

        if (empty($modified) || !is_array($modified)) {
            $modified = array();
        }

        return array_udiff_assoc($modified, $original, array(__CLASS__, 'compareElements'));
    }

    /**
     * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
     * keys to arrays rather than overwriting the value in the first array with the duplicate
     * value in the second array, as array_merge does. I.e., with array_merge_recursive,
     * this happens (documented behavior):
     *
     * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
     *     => array('key' => array('org value', 'new value'));
     *
     * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
     * Matching keys' values in the second array overwrite those in the first array, as is the
     * case with array_merge, i.e.:
     *
     * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
     *     => array('key' => array('new value'));
     *
     * Parameters are passed by reference, though only for performance reasons. They're not
     * altered by this function.
     *
     * @param array $array1
     * @param array $array2
     * @return array
     * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
     * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
     */
    private function array_merge_recursive_distinct(array &$array1, array &$array2)
    {
        $merged = $array1;
        foreach ($array2 as $key => &$value) {
            if (is_array($value) && isset($merged [$key]) && is_array($merged [$key])) {
                $merged [$key] = $this->array_merge_recursive_distinct($merged [$key], $value);
            } else {
                $merged [$key] = $value;
            }
        }
        return $merged;
    }

    /**
     * public for use in closure.
     */
    public function findIndexOfFirstFileWithSection($sectionName)
    {
        $count = 0;
        foreach ($this->settingsChain as $file => $settings) {
            if (isset($settings[$sectionName])) {
                break;
            }

            ++$count;
        }
        return $count;
    }

    /**
     * public for use in closure.
     */
    public function getIndexOfSectionInFile($fileIndex, $sectionName)
    {
        reset($this->settingsChain);
        for ($i = 0; $i != $fileIndex; ++$i) {
            next($this->settingsChain);
        }

        $settingsData = current($this->settingsChain);
        if (empty($settingsData)) {
            return -1;
        }

        $settingsDataSectionNames = array_keys($settingsData);

        return array_search($sectionName, $settingsDataSectionNames);
    }

    /**
     * Encode HTML entities
     *
     * @param mixed $values
     * @return mixed
     */
    protected function encodeValues(&$values)
    {
        if (is_array($values)) {
            foreach ($values as &$value) {
                $value = $this->encodeValues($value);
            }
        } elseif (is_float($values)) {
            $values = Common::forceDotAsSeparatorForDecimalPoint($values);
        } elseif (is_string($values)) {
            $values = htmlentities($values, ENT_COMPAT, 'UTF-8');
            $values = str_replace('$', '&#36;', $values);
        }
        return $values;
    }

    /**
     * Decode HTML entities
     *
     * @param mixed $values
     * @return mixed
     */
    protected function decodeValues(&$values)
    {
        if (is_array($values)) {
            foreach ($values as &$value) {
                $value = $this->decodeValues($value);
            }
            return $values;
        } elseif (is_string($values)) {
            return html_entity_decode($values, ENT_COMPAT, 'UTF-8');
        }
        return $values;
    }

    private function dumpSettings($values, $header)
    {
        /**
         * Triggered before a config is being written / saved on the local file system.
         *
         * A plugin can listen to it and modify which settings will be saved on the file system. This allows you
         * to prevent saving config values that a plugin sets on demand. Say you configure the database password in the
         * config on demand in your plugin, then you could prevent that the password is saved in the actual config file
         * by listening to this event like this:
         *
         * **Example**
         *     function doNotSaveDbPassword (&$values) {
         *         unset($values['database']['password']);
         *     }
         *
         * @param array &$values Config values that will be saved
         */
        Piwik::postEvent('Config.beforeSave', array(&$values));
        $values = $this->encodeValues($values);

        $writer = new IniWriter();
        return $writer->writeToString($values, $header);
    }
}