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