code style: line breaks
[dokuwiki.git] / inc / confutils.php
blob394b7b31bd8152daa2faf1b18636787855a173dd
1 <?php
3 /**
4 * Utilities for collecting data from config files
6 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author Harry Fuecks <hfuecks@gmail.com>
8 */
11 * line prefix used to negate single value config items
12 * (scheme.conf & stopwords.conf), e.g.
13 * !gopher
16 use dokuwiki\Extension\AuthPlugin;
17 use dokuwiki\Extension\Event;
19 const DOKU_CONF_NEGATION = '!';
21 /**
22 * Returns the (known) extension and mimetype of a given filename
24 * If $knownonly is true (the default), then only known extensions
25 * are returned.
27 * @author Andreas Gohr <andi@splitbrain.org>
29 * @param string $file file name
30 * @param bool $knownonly
31 * @return array with extension, mimetype and if it should be downloaded
33 function mimetype($file, $knownonly = true)
35 $mtypes = getMimeTypes(); // known mimetypes
36 $ext = strrpos($file, '.');
37 if ($ext === false) {
38 return [false, false, false];
40 $ext = strtolower(substr($file, $ext + 1));
41 if (!isset($mtypes[$ext])) {
42 if ($knownonly) {
43 return [false, false, false];
44 } else {
45 return [$ext, 'application/octet-stream', true];
48 if ($mtypes[$ext][0] == '!') {
49 return [$ext, substr($mtypes[$ext], 1), true];
50 } else {
51 return [$ext, $mtypes[$ext], false];
55 /**
56 * returns a hash of mimetypes
58 * @author Andreas Gohr <andi@splitbrain.org>
60 function getMimeTypes()
62 static $mime = null;
63 if (!$mime) {
64 $mime = retrieveConfig('mime', 'confToHash');
65 $mime = array_filter($mime);
67 return $mime;
70 /**
71 * returns a hash of acronyms
73 * @author Harry Fuecks <hfuecks@gmail.com>
75 function getAcronyms()
77 static $acronyms = null;
78 if (!$acronyms) {
79 $acronyms = retrieveConfig('acronyms', 'confToHash');
80 $acronyms = array_filter($acronyms, 'strlen');
82 return $acronyms;
85 /**
86 * returns a hash of smileys
88 * @author Harry Fuecks <hfuecks@gmail.com>
90 function getSmileys()
92 static $smileys = null;
93 if (!$smileys) {
94 $smileys = retrieveConfig('smileys', 'confToHash');
95 $smileys = array_filter($smileys, 'strlen');
97 return $smileys;
101 * returns a hash of entities
103 * @author Harry Fuecks <hfuecks@gmail.com>
105 function getEntities()
107 static $entities = null;
108 if (!$entities) {
109 $entities = retrieveConfig('entities', 'confToHash');
110 $entities = array_filter($entities, 'strlen');
112 return $entities;
116 * returns a hash of interwikilinks
118 * @author Harry Fuecks <hfuecks@gmail.com>
120 function getInterwiki()
122 static $wikis = null;
123 if (!$wikis) {
124 $wikis = retrieveConfig('interwiki', 'confToHash', [true]);
125 $wikis = array_filter($wikis, 'strlen');
127 //add sepecial case 'this'
128 $wikis['this'] = DOKU_URL . '{NAME}';
130 return $wikis;
134 * Returns the jquery script URLs for the versions defined in lib/scripts/jquery/versions
136 * @trigger CONFUTIL_CDN_SELECT
137 * @return array
139 function getCdnUrls()
141 global $conf;
143 // load version info
144 $versions = [];
145 $lines = file(DOKU_INC . 'lib/scripts/jquery/versions');
146 foreach ($lines as $line) {
147 $line = trim(preg_replace('/#.*$/', '', $line));
148 if ($line === '') continue;
149 [$key, $val] = sexplode('=', $line, 2, '');
150 $key = trim($key);
151 $val = trim($val);
152 $versions[$key] = $val;
155 $src = [];
156 $data = ['versions' => $versions, 'src' => &$src];
157 $event = new Event('CONFUTIL_CDN_SELECT', $data);
158 if ($event->advise_before()) {
159 if (!$conf['jquerycdn']) {
160 $jqmod = md5(implode('-', $versions));
161 $src[] = DOKU_BASE . 'lib/exe/jquery.php' . '?tseed=' . $jqmod;
162 } elseif ($conf['jquerycdn'] == 'jquery') {
163 $src[] = sprintf('https://code.jquery.com/jquery-%s.min.js', $versions['JQ_VERSION']);
164 $src[] = sprintf('https://code.jquery.com/ui/%s/jquery-ui.min.js', $versions['JQUI_VERSION']);
165 } elseif ($conf['jquerycdn'] == 'cdnjs') {
166 $src[] = sprintf(
167 'https://cdnjs.cloudflare.com/ajax/libs/jquery/%s/jquery.min.js',
168 $versions['JQ_VERSION']
170 $src[] = sprintf(
171 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/%s/jquery-ui.min.js',
172 $versions['JQUI_VERSION']
176 $event->advise_after();
178 return $src;
182 * returns array of wordblock patterns
185 function getWordblocks()
187 static $wordblocks = null;
188 if (!$wordblocks) {
189 $wordblocks = retrieveConfig('wordblock', 'file', null, 'array_merge_with_removal');
191 return $wordblocks;
195 * Gets the list of configured schemes
197 * @return array the schemes
199 function getSchemes()
201 static $schemes = null;
202 if (!$schemes) {
203 $schemes = retrieveConfig('scheme', 'file', null, 'array_merge_with_removal');
204 $schemes = array_map('trim', $schemes);
205 $schemes = preg_replace('/^#.*/', '', $schemes);
206 $schemes = array_filter($schemes);
208 return $schemes;
212 * Builds a hash from an array of lines
214 * If $lower is set to true all hash keys are converted to
215 * lower case.
217 * @author Harry Fuecks <hfuecks@gmail.com>
218 * @author Andreas Gohr <andi@splitbrain.org>
219 * @author Gina Haeussge <gina@foosel.net>
221 * @param array $lines
222 * @param bool $lower
224 * @return array
226 function linesToHash($lines, $lower = false)
228 $conf = [];
229 // remove BOM
230 if (isset($lines[0]) && substr($lines[0], 0, 3) === pack('CCC', 0xef, 0xbb, 0xbf))
231 $lines[0] = substr($lines[0], 3);
232 foreach ($lines as $line) {
233 //ignore comments (except escaped ones)
234 $line = preg_replace('/(?<![&\\\\])#.*$/', '', $line);
235 $line = str_replace('\\#', '#', $line);
236 $line = trim($line);
237 if ($line === '') continue;
238 $line = preg_split('/\s+/', $line, 2);
239 $line = array_pad($line, 2, '');
240 // Build the associative array
241 if ($lower) {
242 $conf[strtolower($line[0])] = $line[1];
243 } else {
244 $conf[$line[0]] = $line[1];
248 return $conf;
252 * Builds a hash from a configfile
254 * If $lower is set to true all hash keys are converted to
255 * lower case.
257 * @author Harry Fuecks <hfuecks@gmail.com>
258 * @author Andreas Gohr <andi@splitbrain.org>
259 * @author Gina Haeussge <gina@foosel.net>
261 * @param string $file
262 * @param bool $lower
264 * @return array
266 function confToHash($file, $lower = false)
268 $conf = [];
269 $lines = @file($file);
270 if (!$lines) return $conf;
272 return linesToHash($lines, $lower);
276 * Read a json config file into an array
278 * @param string $file
279 * @return array
281 function jsonToArray($file)
283 $json = file_get_contents($file);
285 $conf = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
287 if ($conf === null) {
288 return [];
291 return $conf;
295 * Retrieve the requested configuration information
297 * @author Chris Smith <chris@jalakai.co.uk>
299 * @param string $type the configuration settings to be read, must correspond to a key/array in $config_cascade
300 * @param callback $fn the function used to process the configuration file into an array
301 * @param array $params optional additional params to pass to the callback
302 * @param callback $combine the function used to combine arrays of values read from different configuration files;
303 * the function takes two parameters,
304 * $combined - the already read & merged configuration values
305 * $new - array of config values from the config cascade file being currently processed
306 * and returns an array of the merged configuration values.
307 * @return array configuration values
309 function retrieveConfig($type, $fn, $params = null, $combine = 'array_merge')
311 global $config_cascade;
313 if (!is_array($params)) $params = [];
315 $combined = [];
316 if (!is_array($config_cascade[$type])) trigger_error('Missing config cascade for "' . $type . '"', E_USER_WARNING);
317 foreach (['default', 'local', 'protected'] as $config_group) {
318 if (empty($config_cascade[$type][$config_group])) continue;
319 foreach ($config_cascade[$type][$config_group] as $file) {
320 if (file_exists($file)) {
321 $config = call_user_func_array($fn, array_merge([$file], $params));
322 $combined = $combine($combined, $config);
327 return $combined;
331 * Include the requested configuration information
333 * @author Chris Smith <chris@jalakai.co.uk>
335 * @param string $type the configuration settings to be read, must correspond to a key/array in $config_cascade
336 * @return array list of files, default before local before protected
338 function getConfigFiles($type)
340 global $config_cascade;
341 $files = [];
343 if (!is_array($config_cascade[$type])) trigger_error('Missing config cascade for "' . $type . '"', E_USER_WARNING);
344 foreach (['default', 'local', 'protected'] as $config_group) {
345 if (empty($config_cascade[$type][$config_group])) continue;
346 $files = array_merge($files, $config_cascade[$type][$config_group]);
349 return $files;
353 * check if the given action was disabled in config
355 * @author Andreas Gohr <andi@splitbrain.org>
356 * @param string $action
357 * @returns boolean true if enabled, false if disabled
359 function actionOK($action)
361 static $disabled = null;
362 if (is_null($disabled) || defined('SIMPLE_TEST')) {
363 global $conf;
364 /** @var AuthPlugin $auth */
365 global $auth;
367 // prepare disabled actions array and handle legacy options
368 $disabled = explode(',', $conf['disableactions']);
369 $disabled = array_map('trim', $disabled);
370 if ((isset($conf['openregister']) && !$conf['openregister']) || is_null($auth) || !$auth->canDo('addUser')) {
371 $disabled[] = 'register';
373 if ((isset($conf['resendpasswd']) && !$conf['resendpasswd']) || is_null($auth) || !$auth->canDo('modPass')) {
374 $disabled[] = 'resendpwd';
376 if ((isset($conf['subscribers']) && !$conf['subscribers']) || is_null($auth)) {
377 $disabled[] = 'subscribe';
379 if (is_null($auth) || !$auth->canDo('Profile')) {
380 $disabled[] = 'profile';
382 if (is_null($auth) || !$auth->canDo('delUser')) {
383 $disabled[] = 'profile_delete';
385 if (is_null($auth)) {
386 $disabled[] = 'login';
388 if (is_null($auth) || !$auth->canDo('logout')) {
389 $disabled[] = 'logout';
391 $disabled = array_unique($disabled);
394 return !in_array($action, $disabled);
398 * check if headings should be used as link text for the specified link type
400 * @author Chris Smith <chris@jalakai.co.uk>
402 * @param string $linktype 'content'|'navigation', content applies to links in wiki text
403 * navigation applies to all other links
404 * @return boolean true if headings should be used for $linktype, false otherwise
406 function useHeading($linktype)
408 static $useHeading = null;
409 if (defined('DOKU_UNITTEST')) $useHeading = null; // don't cache during unit tests
411 if (is_null($useHeading)) {
412 global $conf;
414 if (!empty($conf['useheading'])) {
415 switch ($conf['useheading']) {
416 case 'content':
417 $useHeading['content'] = true;
418 break;
420 case 'navigation':
421 $useHeading['navigation'] = true;
422 break;
423 default:
424 $useHeading['content'] = true;
425 $useHeading['navigation'] = true;
427 } else {
428 $useHeading = [];
432 return (!empty($useHeading[$linktype]));
436 * obscure config data so information isn't plain text
438 * @param string $str data to be encoded
439 * @param string $code encoding method, values: plain, base64, uuencode.
440 * @return string the encoded value
442 function conf_encodeString($str, $code)
444 switch ($code) {
445 case 'base64':
446 return '<b>' . base64_encode($str);
447 case 'uuencode':
448 return '<u>' . convert_uuencode($str);
449 case 'plain':
450 default:
451 return $str;
455 * return obscured data as plain text
457 * @param string $str encoded data
458 * @return string plain text
460 function conf_decodeString($str)
462 switch (substr($str, 0, 3)) {
463 case '<b>':
464 return base64_decode(substr($str, 3));
465 case '<u>':
466 return convert_uudecode(substr($str, 3));
467 default: // not encoded (or unknown)
468 return $str;
473 * array combination function to remove negated values (prefixed by !)
475 * @param array $current
476 * @param array $new
478 * @return array the combined array, numeric keys reset
480 function array_merge_with_removal($current, $new)
482 foreach ($new as $val) {
483 if (substr($val, 0, 1) == DOKU_CONF_NEGATION) {
484 $idx = array_search(trim(substr($val, 1)), $current);
485 if ($idx !== false) {
486 unset($current[$idx]);
488 } else {
489 $current[] = trim($val);
493 return array_slice($current, 0);
495 //Setup VIM: ex: et ts=4 :