xref: /dokuwiki/inc/confutils.php (revision 8c7c53b0321a3cd3116b8d3b2ad27863a38dece7)
1<?php
2/**
3 * Utilities for collecting data from config files
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Harry Fuecks <hfuecks@gmail.com>
7 */
8
9/*
10 * line prefix used to negate single value config items
11 * (scheme.conf & stopwords.conf), e.g.
12 * !gopher
13 */
14
15use dokuwiki\Extension\AuthPlugin;
16use dokuwiki\Extension\Event;
17const DOKU_CONF_NEGATION = '!';
18
19/**
20 * Returns the (known) extension and mimetype of a given filename
21 *
22 * If $knownonly is true (the default), then only known extensions
23 * are returned.
24 *
25 * @author Andreas Gohr <andi@splitbrain.org>
26 *
27 * @param string $file file name
28 * @param bool   $knownonly
29 * @return array with extension, mimetype and if it should be downloaded
30 */
31function mimetype($file, $knownonly=true){
32    $mtypes = getMimeTypes();     // known mimetypes
33    $ext    = strrpos($file, '.');
34    if ($ext === false) {
35        return [false, false, false];
36    }
37    $ext = strtolower(substr($file, $ext + 1));
38    if (!isset($mtypes[$ext])){
39        if ($knownonly) {
40            return [false, false, false];
41        } else {
42            return [$ext, 'application/octet-stream', true];
43        }
44    }
45    if($mtypes[$ext][0] == '!'){
46        return [$ext, substr($mtypes[$ext], 1), true];
47    }else{
48        return [$ext, $mtypes[$ext], false];
49    }
50}
51
52/**
53 * returns a hash of mimetypes
54 *
55 * @author Andreas Gohr <andi@splitbrain.org>
56 */
57function getMimeTypes() {
58    static $mime = null;
59    if ( !$mime ) {
60        $mime = retrieveConfig('mime', 'confToHash');
61        $mime = array_filter($mime);
62    }
63    return $mime;
64}
65
66/**
67 * returns a hash of acronyms
68 *
69 * @author Harry Fuecks <hfuecks@gmail.com>
70 */
71function getAcronyms() {
72    static $acronyms = null;
73    if ( !$acronyms ) {
74        $acronyms = retrieveConfig('acronyms', 'confToHash');
75        $acronyms = array_filter($acronyms, 'strlen');
76    }
77    return $acronyms;
78}
79
80/**
81 * returns a hash of smileys
82 *
83 * @author Harry Fuecks <hfuecks@gmail.com>
84 */
85function getSmileys() {
86    static $smileys = null;
87    if ( !$smileys ) {
88        $smileys = retrieveConfig('smileys', 'confToHash');
89        $smileys = array_filter($smileys, 'strlen');
90    }
91    return $smileys;
92}
93
94/**
95 * returns a hash of entities
96 *
97 * @author Harry Fuecks <hfuecks@gmail.com>
98 */
99function getEntities() {
100    static $entities = null;
101    if ( !$entities ) {
102        $entities = retrieveConfig('entities', 'confToHash');
103        $entities = array_filter($entities, 'strlen');
104    }
105    return $entities;
106}
107
108/**
109 * returns a hash of interwikilinks
110 *
111 * @author Harry Fuecks <hfuecks@gmail.com>
112 */
113function getInterwiki() {
114    static $wikis = null;
115    if ( !$wikis ) {
116        $wikis = retrieveConfig('interwiki', 'confToHash', [true]);
117        $wikis = array_filter($wikis, 'strlen');
118
119        //add sepecial case 'this'
120        $wikis['this'] = DOKU_URL.'{NAME}';
121    }
122    return $wikis;
123}
124
125/**
126 * Returns the jquery script URLs for the versions defined in lib/scripts/jquery/versions
127 *
128 * @trigger CONFUTIL_CDN_SELECT
129 * @return array
130 */
131function getCdnUrls() {
132    global $conf;
133
134    // load version info
135    $versions = [];
136    $lines = file(DOKU_INC . 'lib/scripts/jquery/versions');
137    foreach($lines as $line) {
138        $line = trim(preg_replace('/#.*$/', '', $line));
139        if($line === '') continue;
140        [$key, $val] = sexplode('=', $line, 2, '');
141        $key = trim($key);
142        $val = trim($val);
143        $versions[$key] = $val;
144    }
145
146    $src = [];
147    $data = ['versions' => $versions, 'src' => &$src];
148    $event = new Event('CONFUTIL_CDN_SELECT', $data);
149    if($event->advise_before()) {
150        if(!$conf['jquerycdn']) {
151            $jqmod = md5(implode('-', $versions));
152            $src[] = DOKU_BASE . 'lib/exe/jquery.php' . '?tseed=' . $jqmod;
153        } elseif($conf['jquerycdn'] == 'jquery') {
154            $src[] = sprintf('https://code.jquery.com/jquery-%s.min.js', $versions['JQ_VERSION']);
155            $src[] = sprintf('https://code.jquery.com/ui/%s/jquery-ui.min.js', $versions['JQUI_VERSION']);
156        } elseif($conf['jquerycdn'] == 'cdnjs') {
157            $src[] = sprintf(
158                'https://cdnjs.cloudflare.com/ajax/libs/jquery/%s/jquery.min.js',
159                $versions['JQ_VERSION']
160            );
161            $src[] = sprintf(
162                'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/%s/jquery-ui.min.js',
163                $versions['JQUI_VERSION']
164            );
165        }
166    }
167    $event->advise_after();
168
169    return $src;
170}
171
172/**
173 * returns array of wordblock patterns
174 *
175 */
176function getWordblocks() {
177    static $wordblocks = null;
178    if ( !$wordblocks ) {
179        $wordblocks = retrieveConfig('wordblock', 'file', null, 'array_merge_with_removal');
180    }
181    return $wordblocks;
182}
183
184/**
185 * Gets the list of configured schemes
186 *
187 * @return array the schemes
188 */
189function getSchemes() {
190    static $schemes = null;
191    if ( !$schemes ) {
192        $schemes = retrieveConfig('scheme', 'file', null, 'array_merge_with_removal');
193        $schemes = array_map('trim', $schemes);
194        $schemes = preg_replace('/^#.*/', '', $schemes);
195        $schemes = array_filter($schemes);
196    }
197    return $schemes;
198}
199
200/**
201 * Builds a hash from an array of lines
202 *
203 * If $lower is set to true all hash keys are converted to
204 * lower case.
205 *
206 * @author Harry Fuecks <hfuecks@gmail.com>
207 * @author Andreas Gohr <andi@splitbrain.org>
208 * @author Gina Haeussge <gina@foosel.net>
209 *
210 * @param array $lines
211 * @param bool $lower
212 *
213 * @return array
214 */
215function linesToHash($lines, $lower = false) {
216    $conf = [];
217    // remove BOM
218    if(isset($lines[0]) && substr($lines[0], 0, 3) === pack('CCC', 0xef, 0xbb, 0xbf))
219        $lines[0] = substr($lines[0], 3);
220    foreach($lines as $line) {
221        //ignore comments (except escaped ones)
222        $line = preg_replace('/(?<![&\\\\])#.*$/', '', $line);
223        $line = str_replace('\\#', '#', $line);
224        $line = trim($line);
225        if($line === '') continue;
226        $line = preg_split('/\s+/', $line, 2);
227        $line = array_pad($line, 2, '');
228        // Build the associative array
229        if($lower) {
230            $conf[strtolower($line[0])] = $line[1];
231        } else {
232            $conf[$line[0]] = $line[1];
233        }
234    }
235
236    return $conf;
237}
238
239/**
240 * Builds a hash from a configfile
241 *
242 * If $lower is set to true all hash keys are converted to
243 * lower case.
244 *
245 * @author Harry Fuecks <hfuecks@gmail.com>
246 * @author Andreas Gohr <andi@splitbrain.org>
247 * @author Gina Haeussge <gina@foosel.net>
248 *
249 * @param string $file
250 * @param bool $lower
251 *
252 * @return array
253 */
254function confToHash($file,$lower=false) {
255    $conf = [];
256    $lines = @file( $file );
257    if ( !$lines ) return $conf;
258
259    return linesToHash($lines, $lower);
260}
261
262/**
263 * Read a json config file into an array
264 *
265 * @param string $file
266 * @return array
267 */
268function jsonToArray($file)
269{
270    $json = file_get_contents($file);
271
272    $conf = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
273
274    if ($conf === null) {
275        return [];
276    }
277
278    return $conf;
279}
280
281/**
282 * Retrieve the requested configuration information
283 *
284 * @author Chris Smith <chris@jalakai.co.uk>
285 *
286 * @param  string   $type     the configuration settings to be read, must correspond to a key/array in $config_cascade
287 * @param  callback $fn       the function used to process the configuration file into an array
288 * @param  array    $params   optional additional params to pass to the callback
289 * @param  callback $combine  the function used to combine arrays of values read from different configuration files;
290 *                            the function takes two parameters,
291 *                               $combined - the already read & merged configuration values
292 *                               $new - array of config values from the config cascade file being currently processed
293 *                            and returns an array of the merged configuration values.
294 * @return array    configuration values
295 */
296function retrieveConfig($type,$fn,$params=null,$combine='array_merge') {
297    global $config_cascade;
298
299    if(!is_array($params)) $params = [];
300
301    $combined = [];
302    if (!is_array($config_cascade[$type])) trigger_error('Missing config cascade for "'.$type.'"', E_USER_WARNING);
303    foreach (['default', 'local', 'protected'] as $config_group) {
304        if (empty($config_cascade[$type][$config_group])) continue;
305        foreach ($config_cascade[$type][$config_group] as $file) {
306            if (file_exists($file)) {
307                $config = call_user_func_array($fn, array_merge([$file], $params));
308                $combined = $combine($combined, $config);
309            }
310        }
311    }
312
313    return $combined;
314}
315
316/**
317 * Include the requested configuration information
318 *
319 * @author Chris Smith <chris@jalakai.co.uk>
320 *
321 * @param  string   $type     the configuration settings to be read, must correspond to a key/array in $config_cascade
322 * @return array              list of files, default before local before protected
323 */
324function getConfigFiles($type) {
325    global $config_cascade;
326    $files = [];
327
328    if (!is_array($config_cascade[$type])) trigger_error('Missing config cascade for "'.$type.'"', E_USER_WARNING);
329    foreach (['default', 'local', 'protected'] as $config_group) {
330        if (empty($config_cascade[$type][$config_group])) continue;
331        $files = array_merge($files, $config_cascade[$type][$config_group]);
332    }
333
334    return $files;
335}
336
337/**
338 * check if the given action was disabled in config
339 *
340 * @author Andreas Gohr <andi@splitbrain.org>
341 * @param string $action
342 * @returns boolean true if enabled, false if disabled
343 */
344function actionOK($action){
345    static $disabled = null;
346    if(is_null($disabled) || defined('SIMPLE_TEST')){
347        global $conf;
348        /** @var AuthPlugin $auth */
349        global $auth;
350
351        // prepare disabled actions array and handle legacy options
352        $disabled = explode(',', $conf['disableactions']);
353        $disabled = array_map('trim', $disabled);
354        if((isset($conf['openregister']) && !$conf['openregister']) || is_null($auth) || !$auth->canDo('addUser')) {
355            $disabled[] = 'register';
356        }
357        if((isset($conf['resendpasswd']) && !$conf['resendpasswd']) || is_null($auth) || !$auth->canDo('modPass')) {
358            $disabled[] = 'resendpwd';
359        }
360        if((isset($conf['subscribers']) && !$conf['subscribers']) || is_null($auth)) {
361            $disabled[] = 'subscribe';
362        }
363        if (is_null($auth) || !$auth->canDo('Profile')) {
364            $disabled[] = 'profile';
365        }
366        if (is_null($auth) || !$auth->canDo('delUser')) {
367            $disabled[] = 'profile_delete';
368        }
369        if (is_null($auth)) {
370            $disabled[] = 'login';
371        }
372        if (is_null($auth) || !$auth->canDo('logout')) {
373            $disabled[] = 'logout';
374        }
375        $disabled = array_unique($disabled);
376    }
377
378    return !in_array($action, $disabled);
379}
380
381/**
382 * check if headings should be used as link text for the specified link type
383 *
384 * @author Chris Smith <chris@jalakai.co.uk>
385 *
386 * @param   string  $linktype   'content'|'navigation', content applies to links in wiki text
387 *                                                      navigation applies to all other links
388 * @return  boolean             true if headings should be used for $linktype, false otherwise
389 */
390function useHeading($linktype) {
391    static $useHeading = null;
392    if(defined('DOKU_UNITTEST')) $useHeading = null; // don't cache during unit tests
393
394    if (is_null($useHeading)) {
395        global $conf;
396
397        if (!empty($conf['useheading'])) {
398            switch ($conf['useheading']) {
399                case 'content':
400                    $useHeading['content'] = true;
401                    break;
402
403                case 'navigation':
404                    $useHeading['navigation'] = true;
405                    break;
406                default:
407                    $useHeading['content'] = true;
408                    $useHeading['navigation'] = true;
409            }
410        } else {
411            $useHeading = [];
412        }
413    }
414
415    return (!empty($useHeading[$linktype]));
416}
417
418/**
419 * obscure config data so information isn't plain text
420 *
421 * @param string       $str     data to be encoded
422 * @param string       $code    encoding method, values: plain, base64, uuencode.
423 * @return string               the encoded value
424 */
425function conf_encodeString($str,$code) {
426    switch ($code) {
427        case 'base64'   : return '<b>'.base64_encode($str);
428        case 'uuencode' : return '<u>'.convert_uuencode($str);
429        case 'plain':
430        default:
431                          return $str;
432    }
433}
434/**
435 * return obscured data as plain text
436 *
437 * @param  string      $str   encoded data
438 * @return string             plain text
439 */
440function conf_decodeString($str) {
441    switch (substr($str, 0, 3)) {
442        case '<b>' : return base64_decode(substr($str, 3));
443        case '<u>' : return convert_uudecode(substr($str, 3));
444        default:  // not encoded (or unknown)
445                     return $str;
446    }
447}
448
449/**
450 * array combination function to remove negated values (prefixed by !)
451 *
452 * @param  array $current
453 * @param  array $new
454 *
455 * @return array the combined array, numeric keys reset
456 */
457function array_merge_with_removal($current, $new) {
458    foreach ($new as $val) {
459        if (substr($val, 0, 1) == DOKU_CONF_NEGATION) {
460            $idx = array_search(trim(substr($val, 1)), $current);
461            if ($idx !== false) {
462                unset($current[$idx]);
463            }
464        } else {
465            $current[] = trim($val);
466        }
467    }
468
469    return array_slice($current, 0);
470}
471//Setup VIM: ex: et ts=4 :
472