Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.25% covered (success)
89.25%
83 / 93
80.00% covered (success)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
Configuration
89.25% covered (success)
89.25%
83 / 93
80.00% covered (success)
80.00%
4 / 5
47.52
0.00% covered (danger)
0.00%
0 / 1
 __construct
88.10% covered (success)
88.10%
74 / 84
0.00% covered (danger)
0.00%
0 / 1
41.57
 get
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDefaults
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getKey
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getSection
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php declare(strict_types=1);
2/**
3 * PrivateBin
4 *
5 * a zero-knowledge paste bin
6 *
7 * @link      https://github.com/PrivateBin/PrivateBin
8 * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
9 * @license   https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
10 */
11
12namespace PrivateBin;
13
14use Exception;
15use PrivateBin\Exception\TranslatedException;
16
17/**
18 * Configuration
19 *
20 * parses configuration file, ensures default values present
21 */
22class Configuration
23{
24    /**
25     * parsed configuration
26     *
27     * @var array
28     */
29    protected $_configuration;
30
31    /**
32     * default configuration
33     *
34     * @var array
35     */
36    private static $_defaults = [
37        'main' => [
38            'name'                     => 'PrivateBin',
39            'basepath'                 => '',
40            'discussion'               => true,
41            'opendiscussion'           => false,
42            'discussiondatedisplay'    => true,
43            'password'                 => true,
44            'fileupload'               => false,
45            'burnafterreadingselected' => false,
46            'defaultformatter'         => 'plaintext',
47            'syntaxhighlightingtheme'  => '',
48            'sizelimit'                => 10485760,
49            'templateselection'        => false,
50            'template'                 => 'bootstrap5',
51            'availabletemplates'       => [
52                'bootstrap5',
53                'bootstrap',
54                'bootstrap-page',
55                'bootstrap-dark',
56                'bootstrap-dark-page',
57                'bootstrap-compact',
58                'bootstrap-compact-page',
59            ],
60            'info'                     => 'More information on the <a href=\'https://privatebin.info/\'>project page</a>.',
61            'notice'                   => '',
62            'languageselection'        => false,
63            'languagedefault'          => '',
64            'urlshortener'             => '',
65            'shortenbydefault'         => false,
66            'qrcode'                   => true,
67            'email'                    => true,
68            'icon'                     => 'jdenticon',
69            'cspheader'                => 'default-src \'none\'; base-uri \'self\'; form-action \'none\'; manifest-src \'self\'; connect-src * blob:; script-src \'self\' \'wasm-unsafe-eval\'; style-src \'self\'; font-src \'self\'; frame-ancestors \'none\'; frame-src blob:; img-src \'self\' data: blob:; media-src blob:; object-src blob:; sandbox allow-same-origin allow-scripts allow-forms allow-modals allow-downloads',
70            'httpwarning'              => true,
71            'compression'              => 'zlib',
72        ],
73        'expire' => [
74            'default' => '1week',
75        ],
76        'expire_options' => [
77            '5min'   => 300,
78            '10min'  => 600,
79            '1hour'  => 3600,
80            '1day'   => 86400,
81            '1week'  => 604800,
82            '1month' => 2592000,
83            '1year'  => 31536000,
84            'never'  => 0,
85        ],
86        'formatter_options' => [
87            'plaintext'          => 'Plain Text',
88            'syntaxhighlighting' => 'Source Code',
89            'markdown'           => 'Markdown',
90        ],
91        'traffic' => [
92            'limit'     => 10,
93            'header'    => '',
94            'exempted'  => '',
95            'creators'  => '',
96        ],
97        'purge' => [
98            'limit'     => 300,
99            'batchsize' => 10,
100        ],
101        'model' => [
102            'class' => 'Filesystem',
103        ],
104        'model_options' => [
105            'dir' => 'data',
106        ],
107        'yourls' => [
108            'signature' => '',
109            'apiurl'    => '',
110        ],
111        'shlink' => [
112            'apikey'    => '',
113            'apiurl'    => '',
114        ],
115        'chhoto' => [
116            'apikey'    => '',
117            'apiurl'    => '',
118        ],
119        // update this array when adding/changing/removing js files
120        'sri' => [
121            'js/base-x-5.0.1.js'     => 'sha512-FmhlnjIxQyxkkxQmzf0l6IRGsGbgyCdgqPxypFsEtHMF1naRqaLLo6mcyN5rEaT16nKx1PeJ4g7+07D6gnk/Tg==',
122            'js/bootstrap-5.3.8.js'  => 'sha512-BkZvJ5rZ3zbDCod5seWHpRGg+PRd6ZgE8Nua/OMtcxqm8Wtg0PqwhUUXK5bqvl3oclMt5O+3zjRVX0L+L2j7fA==',
123            'js/dark-mode-switch.js' => 'sha512-BhY7dNU14aDN5L+muoUmA66x0CkYUWkQT0nxhKBLP/o2d7jE025+dvWJa4OiYffBGEFgmhrD/Sp+QMkxGMTz2g==',
124            'js/kjua-0.10.0.js'      => 'sha512-BYj4xggowR7QD150VLSTRlzH62YPfhpIM+b/1EUEr7RQpdWAGKulxWnOvjFx1FUlba4m6ihpNYuQab51H6XlYg==',
125            'js/legacy.js'           => 'sha512-pRofxsrf5UItjiP22Dcjh3FAcBjF/n7h8U9/W5xqJk17U0N2U1oajhXypq/omo9jhwS1iVGOhWrRepoPeFns+w==',
126            'js/prettify.js'         => 'sha512-puO0Ogy++IoA2Pb9IjSxV1n4+kQkKXYAEUtVzfZpQepyDPyXk8hokiYDS7ybMogYlyyEIwMLpZqVhCkARQWLMg==',
127            'js/privatebin.js'       => 'sha512-ECxau81icFK+pB7VsyYoxEMXrERcuE7ILhtTD6dedfsHZfL59+4f57SSvvpwIy/CZ665jyvtYZ9FBDZ1Lx3DAQ==',
128            'js/purify-3.4.17.js'    => 'sha512-udF2zPdEyVCAxIGeBbeSGFK1Fj5c4eHGi6NqOSsr8M75lGs39POzgUNxO3SFxOg4cHfAoZJgR2EaXdmDi6v6AQ==',
129            'js/showdown-2.1.0.js'   => 'sha512-WYXZgkTR0u/Y9SVIA4nTTOih0kXMEd8RRV6MLFdL6YU8ymhR528NLlYQt1nlJQbYz4EW+ZsS0fx1awhiQJme1Q==',
130            'js/zlib-1.3.2.js'       => 'sha512-RAhJgxg9siMIA8ky4c10Rc2zUgnK80olHB8Tt1IOYWY4Eh1WmrviQkDn+sgBlb38ZHq3tzufGC41kP360gmosQ==',
131            'js/zlib.js'             => 'sha512-QOaEwssHqHRRcWJ2Un3Kl2Zhyprzl7T8zmsKN2FppFxW3VR+8UChYOx2iuL0HbXK42fuBWJm5PNQJxufulrt/w==',
132        ],
133    ];
134
135    /**
136     * parse configuration file and ensure default configuration values are present
137     *
138     * @throws TranslatedException
139     */
140    public function __construct()
141    {
142        $basePaths  = [];
143        $config     = [];
144        $configPath = getenv('CONFIG_PATH');
145        if ($configPath !== false && !empty($configPath)) {
146            $basePaths[] = $configPath;
147        }
148        $basePaths[] = PATH . 'cfg';
149        foreach ($basePaths as $basePath) {
150            $configFile = $basePath . DIRECTORY_SEPARATOR . 'conf.php';
151            if (is_readable($configFile)) {
152                $config = parse_ini_file($configFile, true);
153                foreach (['main', 'model', 'model_options'] as $section) {
154                    if (!array_key_exists($section, $config)) {
155                        $name = $config['main']['name'] ?? self::getDefaults()['main']['name'];
156                        throw new TranslatedException(['%s requires configuration section [%s] to be present in configuration file.', I18n::_($name), $section], 2);
157                    }
158                }
159                break;
160            }
161        }
162
163        $opts = '_options';
164        foreach (self::getDefaults() as $section => $values) {
165            // fill missing sections with default values
166            if (!array_key_exists($section, $config) || count($config[$section]) === 0) {
167                $this->_configuration[$section] = $values;
168                if (array_key_exists('dir', $this->_configuration[$section])) {
169                    $this->_configuration[$section]['dir'] = PATH . $this->_configuration[$section]['dir'];
170                }
171                continue;
172            }
173            // provide different defaults for database model
174            elseif (
175                $section === 'model_options' &&
176                $this->_configuration['model']['class'] === 'Database'
177            ) {
178                $values = [
179                    'dsn' => 'sqlite:' . PATH . 'data' . DIRECTORY_SEPARATOR . 'db.sq3',
180                    'tbl' => null,
181                    'usr' => null,
182                    'pwd' => null,
183                    'opt' => [],
184                ];
185            } elseif (
186                $section === 'model_options' &&
187                $this->_configuration['model']['class'] === 'GoogleCloudStorage'
188            ) {
189                $values = [
190                    'bucket'     => getenv('PRIVATEBIN_GCS_BUCKET') ? getenv('PRIVATEBIN_GCS_BUCKET') : null,
191                    'prefix'     => 'pastes',
192                    'uniformacl' => false,
193                ];
194            } elseif (
195                $section === 'model_options' &&
196                $this->_configuration['model']['class'] === 'S3Storage'
197            ) {
198                $values = [
199                    'region'                  => null,
200                    'version'                 => null,
201                    'endpoint'                => null,
202                    'accesskey'               => null,
203                    'secretkey'               => null,
204                    'use_path_style_endpoint' => null,
205                    'bucket'                  => null,
206                    'prefix'                  => '',
207                ];
208            }
209
210            // "*_options" sections don't require all defaults to be set
211            if (
212                $section !== 'model_options' &&
213                ($from = strlen($section) - strlen($opts)) >= 0 &&
214                strpos($section, $opts, $from) !== false
215            ) {
216                if (is_int(current($values))) {
217                    $config[$section] = array_map('intval', $config[$section]);
218                }
219                $this->_configuration[$section] = $config[$section];
220            }
221            // check for missing keys and set defaults if necessary
222            else {
223                // preserve configured SRI hashes
224                if ($section === 'sri' && array_key_exists($section, $config)) {
225                    $this->_configuration[$section] = $config[$section];
226                }
227                foreach ($values as $key => $val) {
228                    if ($key === 'dir') {
229                        $val = PATH . $val;
230                    }
231                    $result = $val;
232                    if (array_key_exists($key, $config[$section])) {
233                        if ($val === null) {
234                            $result = $config[$section][$key];
235                        } elseif (is_bool($val)) {
236                            $val = strtolower($config[$section][$key]);
237                            if (in_array($val, ['true', 'yes', 'on'])) {
238                                $result = true;
239                            } elseif (in_array($val, ['false', 'no', 'off'])) {
240                                $result = false;
241                            } else {
242                                $result = (bool) $config[$section][$key];
243                            }
244                        } elseif (is_int($val)) {
245                            $result = (int) $config[$section][$key];
246                        } elseif (is_string($val) && !empty($config[$section][$key])) {
247                            $result = (string) $config[$section][$key];
248                        } elseif (is_array($val) && is_array($config[$section][$key])) {
249                            $result = $config[$section][$key];
250                        }
251                    }
252                    $this->_configuration[$section][$key] = $result;
253                }
254            }
255        }
256
257        // ensure a valid expire default key is set
258        if (!array_key_exists($this->_configuration['expire']['default'], $this->_configuration['expire_options'])) {
259            $this->_configuration['expire']['default'] = key($this->_configuration['expire_options']);
260        }
261
262        // ensure the basepath ends in a slash, if one is set
263        if (
264            !empty($this->_configuration['main']['basepath']) &&
265            substr_compare($this->_configuration['main']['basepath'], '/', -1) !== 0
266        ) {
267            $this->_configuration['main']['basepath'] .= '/';
268        }
269    }
270
271    /**
272     * get configuration as array
273     *
274     * @return array
275     */
276    public function get()
277    {
278        return $this->_configuration;
279    }
280
281    /**
282     * get default configuration as array
283     *
284     * @return array
285     */
286    public static function getDefaults()
287    {
288        return self::$_defaults;
289    }
290
291    /**
292     * get a key from the configuration, typically the main section or all keys
293     *
294     * @param string $key
295     * @param string $section defaults to main
296     * @throws Exception
297     * @return mixed
298     */
299    public function getKey($key, $section = 'main')
300    {
301        $options = $this->getSection($section);
302        if (!array_key_exists($key, $options)) {
303            throw new Exception(I18n::_('Invalid data.') . " $section / $key", 4);
304        }
305        return $this->_configuration[$section][$key];
306    }
307
308    /**
309     * get a section from the configuration, must exist
310     *
311     * @param string $section
312     * @throws TranslatedException
313     * @return mixed
314     */
315    public function getSection($section)
316    {
317        if (!array_key_exists($section, $this->_configuration)) {
318            throw new TranslatedException(['%s requires configuration section [%s] to be present in configuration file.', I18n::_($this->getKey('name')), $section], 3);
319        }
320        return $this->_configuration[$section];
321    }
322}