Failed Conditions
Push — psr2 ( 9ddafc...b78f68 )
by Andreas
07:11
created

inc/common.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

Code
1
<?php
2
/**
3
 * Common DokuWiki functions
4
 *
5
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6
 * @author     Andreas Gohr <[email protected]>
7
 */
8
9
use dokuwiki\ChangeLog\PageChangeLog;
0 ignored issues
show
This use statement conflicts with another class in this namespace, PageChangeLog.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
10
11
/**
12
 * These constants are used with the recents function
13
 */
14
define('RECENTS_SKIP_DELETED', 2);
15
define('RECENTS_SKIP_MINORS', 4);
16
define('RECENTS_SKIP_SUBSPACES', 8);
17
define('RECENTS_MEDIA_CHANGES', 16);
18
define('RECENTS_MEDIA_PAGES_MIXED', 32);
19
20
/**
21
 * Wrapper around htmlspecialchars()
22
 *
23
 * @author Andreas Gohr <[email protected]>
24
 * @see    htmlspecialchars()
25
 *
26
 * @param string $string the string being converted
27
 * @return string converted string
28
 */
29
function hsc($string) {
30
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
31
}
32
33
/**
34
 * Checks if the given input is blank
35
 *
36
 * This is similar to empty() but will return false for "0".
37
 *
38
 * Please note: when you pass uninitialized variables, they will implicitly be created
39
 * with a NULL value without warning.
40
 *
41
 * To avoid this it's recommended to guard the call with isset like this:
42
 *
43
 * (isset($foo) && !blank($foo))
44
 * (!isset($foo) || blank($foo))
45
 *
46
 * @param $in
47
 * @param bool $trim Consider a string of whitespace to be blank
48
 * @return bool
49
 */
50
function blank(&$in, $trim = false) {
51
    if(is_null($in)) return true;
52
    if(is_array($in)) return empty($in);
53
    if($in === "\0") return true;
54
    if($trim && trim($in) === '') return true;
55
    if(strlen($in) > 0) return false;
56
    return empty($in);
57
}
58
59
/**
60
 * print a newline terminated string
61
 *
62
 * You can give an indention as optional parameter
63
 *
64
 * @author Andreas Gohr <[email protected]>
65
 *
66
 * @param string $string  line of text
67
 * @param int    $indent  number of spaces indention
68
 */
69
function ptln($string, $indent = 0) {
70
    echo str_repeat(' ', $indent)."$string\n";
71
}
72
73
/**
74
 * strips control characters (<32) from the given string
75
 *
76
 * @author Andreas Gohr <[email protected]>
77
 *
78
 * @param string $string being stripped
79
 * @return string
80
 */
81
function stripctl($string) {
82
    return preg_replace('/[\x00-\x1F]+/s', '', $string);
83
}
84
85
/**
86
 * Return a secret token to be used for CSRF attack prevention
87
 *
88
 * @author  Andreas Gohr <[email protected]>
89
 * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
90
 * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
91
 *
92
 * @return  string
93
 */
94
function getSecurityToken() {
95
    /** @var Input $INPUT */
96
    global $INPUT;
97
98
    $user = $INPUT->server->str('REMOTE_USER');
99
    $session = session_id();
100
101
    // CSRF checks are only for logged in users - do not generate for anonymous
102
    if(trim($user) == '' || trim($session) == '') return '';
103
    return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
104
}
105
106
/**
107
 * Check the secret CSRF token
108
 *
109
 * @param null|string $token security token or null to read it from request variable
110
 * @return bool success if the token matched
111
 */
112
function checkSecurityToken($token = null) {
113
    /** @var Input $INPUT */
114
    global $INPUT;
115
    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
116
117
    if(is_null($token)) $token = $INPUT->str('sectok');
118
    if(getSecurityToken() != $token) {
119
        msg('Security Token did not match. Possible CSRF attack.', -1);
120
        return false;
121
    }
122
    return true;
123
}
124
125
/**
126
 * Print a hidden form field with a secret CSRF token
127
 *
128
 * @author  Andreas Gohr <[email protected]>
129
 *
130
 * @param bool $print  if true print the field, otherwise html of the field is returned
131
 * @return string html of hidden form field
132
 */
133
function formSecurityToken($print = true) {
134
    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
135
    if($print) echo $ret;
136
    return $ret;
137
}
138
139
/**
140
 * Determine basic information for a request of $id
141
 *
142
 * @author Andreas Gohr <[email protected]>
143
 * @author Chris Smith <[email protected]>
144
 *
145
 * @param string $id         pageid
146
 * @param bool   $htmlClient add info about whether is mobile browser
147
 * @return array with info for a request of $id
148
 *
149
 */
150
function basicinfo($id, $htmlClient=true){
151
    global $USERINFO;
152
    /* @var Input $INPUT */
153
    global $INPUT;
154
155
    // set info about manager/admin status.
156
    $info = array();
157
    $info['isadmin']   = false;
158
    $info['ismanager'] = false;
159
    if($INPUT->server->has('REMOTE_USER')) {
160
        $info['userinfo']   = $USERINFO;
161
        $info['perm']       = auth_quickaclcheck($id);
162
        $info['client']     = $INPUT->server->str('REMOTE_USER');
163
164
        if($info['perm'] == AUTH_ADMIN) {
165
            $info['isadmin']   = true;
166
            $info['ismanager'] = true;
167
        } elseif(auth_ismanager()) {
168
            $info['ismanager'] = true;
169
        }
170
171
        // if some outside auth were used only REMOTE_USER is set
172
        if(!$info['userinfo']['name']) {
173
            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
174
        }
175
176
    } else {
177
        $info['perm']       = auth_aclcheck($id, '', null);
178
        $info['client']     = clientIP(true);
179
    }
180
181
    $info['namespace'] = getNS($id);
182
183
    // mobile detection
184
    if ($htmlClient) {
185
        $info['ismobile'] = clientismobile();
186
    }
187
188
    return $info;
189
 }
190
191
/**
192
 * Return info about the current document as associative
193
 * array.
194
 *
195
 * @author Andreas Gohr <[email protected]>
196
 *
197
 * @return array with info about current document
198
 */
199
function pageinfo() {
200
    global $ID;
201
    global $REV;
202
    global $RANGE;
203
    global $lang;
204
    /* @var Input $INPUT */
205
    global $INPUT;
206
207
    $info = basicinfo($ID);
208
209
    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
210
    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
211
    $info['id']  = $ID;
212
    $info['rev'] = $REV;
213
214
    if($INPUT->server->has('REMOTE_USER')) {
215
        $sub = new Subscription();
216
        $info['subscribed'] = $sub->user_subscription();
217
    } else {
218
        $info['subscribed'] = false;
219
    }
220
221
    $info['locked']     = checklock($ID);
222
    $info['filepath']   = wikiFN($ID);
223
    $info['exists']     = file_exists($info['filepath']);
224
    $info['currentrev'] = @filemtime($info['filepath']);
225
    if($REV) {
226
        //check if current revision was meant
227
        if($info['exists'] && ($info['currentrev'] == $REV)) {
228
            $REV = '';
229
        } elseif($RANGE) {
230
            //section editing does not work with old revisions!
231
            $REV   = '';
232
            $RANGE = '';
233
            msg($lang['nosecedit'], 0);
234
        } else {
235
            //really use old revision
236
            $info['filepath'] = wikiFN($ID, $REV);
237
            $info['exists']   = file_exists($info['filepath']);
238
        }
239
    }
240
    $info['rev'] = $REV;
241
    if($info['exists']) {
242
        $info['writable'] = (is_writable($info['filepath']) &&
243
            ($info['perm'] >= AUTH_EDIT));
244
    } else {
245
        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
246
    }
247
    $info['editable'] = ($info['writable'] && empty($info['locked']));
248
    $info['lastmod']  = @filemtime($info['filepath']);
249
250
    //load page meta data
251
    $info['meta'] = p_get_metadata($ID);
252
253
    //who's the editor
254
    $pagelog = new PageChangeLog($ID, 1024);
255
    if($REV) {
256
        $revinfo = $pagelog->getRevisionInfo($REV);
257
    } else {
258
        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
259
            $revinfo = $info['meta']['last_change'];
260
        } else {
261
            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
262
            // cache most recent changelog line in metadata if missing and still valid
263
            if($revinfo !== false) {
264
                $info['meta']['last_change'] = $revinfo;
265
                p_set_metadata($ID, array('last_change' => $revinfo));
266
            }
267
        }
268
    }
269
    //and check for an external edit
270
    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
271
        // cached changelog line no longer valid
272
        $revinfo                     = false;
273
        $info['meta']['last_change'] = $revinfo;
274
        p_set_metadata($ID, array('last_change' => $revinfo));
275
    }
276
277
    $info['ip']   = $revinfo['ip'];
278
    $info['user'] = $revinfo['user'];
279
    $info['sum']  = $revinfo['sum'];
280
    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
281
    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
282
283
    if($revinfo['user']) {
284
        $info['editor'] = $revinfo['user'];
285
    } else {
286
        $info['editor'] = $revinfo['ip'];
287
    }
288
289
    // draft
290
    $draft = new \dokuwiki\Draft($ID, $info['client']);
291
    if ($draft->isDraftAvailable()) {
292
        $info['draft'] = $draft->getDraftFilename();
293
    }
294
295
    return $info;
296
}
297
298
/**
299
 * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
300
 */
301
function jsinfo() {
302
    global $JSINFO, $ID, $INFO, $ACT;
303
304
    if (!is_array($JSINFO)) {
305
        $JSINFO = [];
306
    }
307
    //export minimal info to JS, plugins can add more
308
    $JSINFO['id']                    = $ID;
309
    $JSINFO['namespace']             = (string) $INFO['namespace'];
310
    $JSINFO['ACT']                   = act_clean($ACT);
311
    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
312
    $JSINFO['useHeadingContent']     = (int) useHeading('content');
313
}
314
315
/**
316
 * Return information about the current media item as an associative array.
317
 *
318
 * @return array with info about current media item
319
 */
320
function mediainfo(){
321
    global $NS;
322
    global $IMG;
323
324
    $info = basicinfo("$NS:*");
325
    $info['image'] = $IMG;
326
327
    return $info;
328
}
329
330
/**
331
 * Build an string of URL parameters
332
 *
333
 * @author Andreas Gohr
334
 *
335
 * @param array  $params    array with key-value pairs
336
 * @param string $sep       series of pairs are separated by this character
337
 * @return string query string
338
 */
339
function buildURLparams($params, $sep = '&amp;') {
340
    $url = '';
341
    $amp = false;
342
    foreach($params as $key => $val) {
343
        if($amp) $url .= $sep;
344
345
        $url .= rawurlencode($key).'=';
346
        $url .= rawurlencode((string) $val);
347
        $amp = true;
348
    }
349
    return $url;
350
}
351
352
/**
353
 * Build an string of html tag attributes
354
 *
355
 * Skips keys starting with '_', values get HTML encoded
356
 *
357
 * @author Andreas Gohr
358
 *
359
 * @param array $params    array with (attribute name-attribute value) pairs
360
 * @param bool  $skipempty skip empty string values?
361
 * @return string
362
 */
363
function buildAttributes($params, $skipempty = false) {
364
    $url   = '';
365
    $white = false;
366
    foreach($params as $key => $val) {
367
        if($key{0} == '_') continue;
368
        if($val === '' && $skipempty) continue;
369
        if($white) $url .= ' ';
370
371
        $url .= $key.'="';
372
        $url .= htmlspecialchars($val);
373
        $url .= '"';
374
        $white = true;
375
    }
376
    return $url;
377
}
378
379
/**
380
 * This builds the breadcrumb trail and returns it as array
381
 *
382
 * @author Andreas Gohr <[email protected]>
383
 *
384
 * @return string[] with the data: array(pageid=>name, ... )
385
 */
386
function breadcrumbs() {
387
    // we prepare the breadcrumbs early for quick session closing
388
    static $crumbs = null;
389
    if($crumbs != null) return $crumbs;
390
391
    global $ID;
392
    global $ACT;
393
    global $conf;
394
395
    //first visit?
396
    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
397
    //we only save on show and existing visible wiki documents
398
    $file = wikiFN($ID);
399
    if($ACT != 'show' || isHiddenPage($ID) || !file_exists($file)) {
400
        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
401
        return $crumbs;
402
    }
403
404
    // page names
405
    $name = noNSorNS($ID);
406
    if(useHeading('navigation')) {
407
        // get page title
408
        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
409
        if($title) {
410
            $name = $title;
411
        }
412
    }
413
414
    //remove ID from array
415
    if(isset($crumbs[$ID])) {
416
        unset($crumbs[$ID]);
417
    }
418
419
    //add to array
420
    $crumbs[$ID] = $name;
421
    //reduce size
422
    while(count($crumbs) > $conf['breadcrumbs']) {
423
        array_shift($crumbs);
424
    }
425
    //save to session
426
    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
427
    return $crumbs;
428
}
429
430
/**
431
 * Filter for page IDs
432
 *
433
 * This is run on a ID before it is outputted somewhere
434
 * currently used to replace the colon with something else
435
 * on Windows (non-IIS) systems and to have proper URL encoding
436
 *
437
 * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
438
 * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
439
 * unaffected servers instead of blacklisting affected servers here.
440
 *
441
 * Urlencoding is ommitted when the second parameter is false
442
 *
443
 * @author Andreas Gohr <[email protected]>
444
 *
445
 * @param string $id pageid being filtered
446
 * @param bool   $ue apply urlencoding?
447
 * @return string
448
 */
449
function idfilter($id, $ue = true) {
450
    global $conf;
451
    /* @var Input $INPUT */
452
    global $INPUT;
453
454
    if($conf['useslash'] && $conf['userewrite']) {
455
        $id = strtr($id, ':', '/');
456
    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
457
        $conf['userewrite'] &&
458
        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
459
    ) {
460
        $id = strtr($id, ':', ';');
461
    }
462
    if($ue) {
463
        $id = rawurlencode($id);
464
        $id = str_replace('%3A', ':', $id); //keep as colon
465
        $id = str_replace('%3B', ';', $id); //keep as semicolon
466
        $id = str_replace('%2F', '/', $id); //keep as slash
467
    }
468
    return $id;
469
}
470
471
/**
472
 * This builds a link to a wikipage
473
 *
474
 * It handles URL rewriting and adds additional parameters
475
 *
476
 * @author Andreas Gohr <[email protected]>
477
 *
478
 * @param string       $id             page id, defaults to start page
479
 * @param string|array $urlParameters  URL parameters, associative array recommended
480
 * @param bool         $absolute       request an absolute URL instead of relative
481
 * @param string       $separator      parameter separator
482
 * @return string
483
 */
484
function wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
485
    global $conf;
486
    if(is_array($urlParameters)) {
487
        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
488
        if(isset($urlParameters['at']) && $conf['date_at_format']) {
489
            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
490
        }
491
        $urlParameters = buildURLparams($urlParameters, $separator);
492
    } else {
493
        $urlParameters = str_replace(',', $separator, $urlParameters);
494
    }
495
    if($id === '') {
496
        $id = $conf['start'];
497
    }
498
    $id = idfilter($id);
499
    if($absolute) {
500
        $xlink = DOKU_URL;
501
    } else {
502
        $xlink = DOKU_BASE;
503
    }
504
505
    if($conf['userewrite'] == 2) {
506
        $xlink .= DOKU_SCRIPT.'/'.$id;
507
        if($urlParameters) $xlink .= '?'.$urlParameters;
508
    } elseif($conf['userewrite']) {
509
        $xlink .= $id;
510
        if($urlParameters) $xlink .= '?'.$urlParameters;
511
    } elseif($id) {
512
        $xlink .= DOKU_SCRIPT.'?id='.$id;
513
        if($urlParameters) $xlink .= $separator.$urlParameters;
514
    } else {
515
        $xlink .= DOKU_SCRIPT;
516
        if($urlParameters) $xlink .= '?'.$urlParameters;
517
    }
518
519
    return $xlink;
520
}
521
522
/**
523
 * This builds a link to an alternate page format
524
 *
525
 * Handles URL rewriting if enabled. Follows the style of wl().
526
 *
527
 * @author Ben Coburn <[email protected]>
528
 * @param string       $id             page id, defaults to start page
529
 * @param string       $format         the export renderer to use
530
 * @param string|array $urlParameters  URL parameters, associative array recommended
531
 * @param bool         $abs            request an absolute URL instead of relative
532
 * @param string       $sep            parameter separator
533
 * @return string
534
 */
535
function exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
536
    global $conf;
537
    if(is_array($urlParameters)) {
538
        $urlParameters = buildURLparams($urlParameters, $sep);
539
    } else {
540
        $urlParameters = str_replace(',', $sep, $urlParameters);
541
    }
542
543
    $format = rawurlencode($format);
544
    $id     = idfilter($id);
545
    if($abs) {
546
        $xlink = DOKU_URL;
547
    } else {
548
        $xlink = DOKU_BASE;
549
    }
550
551
    if($conf['userewrite'] == 2) {
552
        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
553
        if($urlParameters) $xlink .= $sep.$urlParameters;
554
    } elseif($conf['userewrite'] == 1) {
555
        $xlink .= '_export/'.$format.'/'.$id;
556
        if($urlParameters) $xlink .= '?'.$urlParameters;
557
    } else {
558
        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
559
        if($urlParameters) $xlink .= $sep.$urlParameters;
560
    }
561
562
    return $xlink;
563
}
564
565
/**
566
 * Build a link to a media file
567
 *
568
 * Will return a link to the detail page if $direct is false
569
 *
570
 * The $more parameter should always be given as array, the function then
571
 * will strip default parameters to produce even cleaner URLs
572
 *
573
 * @param string  $id     the media file id or URL
574
 * @param mixed   $more   string or array with additional parameters
575
 * @param bool    $direct link to detail page if false
576
 * @param string  $sep    URL parameter separator
577
 * @param bool    $abs    Create an absolute URL
578
 * @return string
579
 */
580
function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
581
    global $conf;
582
    $isexternalimage = media_isexternal($id);
583
    if(!$isexternalimage) {
584
        $id = cleanID($id);
585
    }
586
587
    if(is_array($more)) {
588
        // add token for resized images
589
        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
590
            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
591
        }
592
        // strip defaults for shorter URLs
593
        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
594
        if(empty($more['w'])) unset($more['w']);
595
        if(empty($more['h'])) unset($more['h']);
596
        if(isset($more['id']) && $direct) unset($more['id']);
597
        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
598
        $more = buildURLparams($more, $sep);
599
    } else {
600
        $matches = array();
601
        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
602
            $resize = array('w'=>0, 'h'=>0);
603
            foreach ($matches as $match){
604
                $resize[$match[1]] = $match[2];
605
            }
606
            $more .= $more === '' ? '' : $sep;
607
            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
608
        }
609
        $more = str_replace('cache=cache', '', $more); //skip default
610
        $more = str_replace(',,', ',', $more);
611
        $more = str_replace(',', $sep, $more);
612
    }
613
614
    if($abs) {
615
        $xlink = DOKU_URL;
616
    } else {
617
        $xlink = DOKU_BASE;
618
    }
619
620
    // external URLs are always direct without rewriting
621
    if($isexternalimage) {
622
        $xlink .= 'lib/exe/fetch.php';
623
        $xlink .= '?'.$more;
624
        $xlink .= $sep.'media='.rawurlencode($id);
625
        return $xlink;
626
    }
627
628
    $id = idfilter($id);
629
630
    // decide on scriptname
631
    if($direct) {
632
        if($conf['userewrite'] == 1) {
633
            $script = '_media';
634
        } else {
635
            $script = 'lib/exe/fetch.php';
636
        }
637
    } else {
638
        if($conf['userewrite'] == 1) {
639
            $script = '_detail';
640
        } else {
641
            $script = 'lib/exe/detail.php';
642
        }
643
    }
644
645
    // build URL based on rewrite mode
646
    if($conf['userewrite']) {
647
        $xlink .= $script.'/'.$id;
648
        if($more) $xlink .= '?'.$more;
649
    } else {
650
        if($more) {
651
            $xlink .= $script.'?'.$more;
652
            $xlink .= $sep.'media='.$id;
653
        } else {
654
            $xlink .= $script.'?media='.$id;
655
        }
656
    }
657
658
    return $xlink;
659
}
660
661
/**
662
 * Returns the URL to the DokuWiki base script
663
 *
664
 * Consider using wl() instead, unless you absoutely need the doku.php endpoint
665
 *
666
 * @author Andreas Gohr <[email protected]>
667
 *
668
 * @return string
669
 */
670
function script() {
671
    return DOKU_BASE.DOKU_SCRIPT;
672
}
673
674
/**
675
 * Spamcheck against wordlist
676
 *
677
 * Checks the wikitext against a list of blocked expressions
678
 * returns true if the text contains any bad words
679
 *
680
 * Triggers COMMON_WORDBLOCK_BLOCKED
681
 *
682
 *  Action Plugins can use this event to inspect the blocked data
683
 *  and gain information about the user who was blocked.
684
 *
685
 *  Event data:
686
 *    data['matches']  - array of matches
687
 *    data['userinfo'] - information about the blocked user
688
 *      [ip]           - ip address
689
 *      [user]         - username (if logged in)
690
 *      [mail]         - mail address (if logged in)
691
 *      [name]         - real name (if logged in)
692
 *
693
 * @author Andreas Gohr <[email protected]>
694
 * @author Michael Klier <[email protected]>
695
 *
696
 * @param  string $text - optional text to check, if not given the globals are used
697
 * @return bool         - true if a spam word was found
698
 */
699
function checkwordblock($text = '') {
700
    global $TEXT;
701
    global $PRE;
702
    global $SUF;
703
    global $SUM;
704
    global $conf;
705
    global $INFO;
706
    /* @var Input $INPUT */
707
    global $INPUT;
708
709
    if(!$conf['usewordblock']) return false;
710
711
    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
712
713
    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
714
    // phpcs:disable Generic.Files.LineLength.TooLong
715
    $text = preg_replace(
716
        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
717
        '\1http://\2 \2\3',
718
        $text
719
    );
720
    // phpcs:enable
721
722
    $wordblocks = getWordblocks();
723
    // how many lines to read at once (to work around some PCRE limits)
724
    if(version_compare(phpversion(), '4.3.0', '<')) {
725
        // old versions of PCRE define a maximum of parenthesises even if no
726
        // backreferences are used - the maximum is 99
727
        // this is very bad performancewise and may even be too high still
728
        $chunksize = 40;
729
    } else {
730
        // read file in chunks of 200 - this should work around the
731
        // MAX_PATTERN_SIZE in modern PCRE
732
        $chunksize = 200;
733
    }
734
    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
735
        $re = array();
736
        // build regexp from blocks
737
        foreach($blocks as $block) {
738
            $block = preg_replace('/#.*$/', '', $block);
739
            $block = trim($block);
740
            if(empty($block)) continue;
741
            $re[] = $block;
742
        }
743
        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
744
            // prepare event data
745
            $data = array();
746
            $data['matches']        = $matches;
747
            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
748
            if($INPUT->server->str('REMOTE_USER')) {
749
                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
750
                $data['userinfo']['name'] = $INFO['userinfo']['name'];
751
                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
752
            }
753
            $callback = function () {
754
                return true;
755
            };
756
            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
757
        }
758
    }
759
    return false;
760
}
761
762
/**
763
 * Return the IP of the client
764
 *
765
 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
766
 *
767
 * It returns a comma separated list of IPs if the above mentioned
768
 * headers are set. If the single parameter is set, it tries to return
769
 * a routable public address, prefering the ones suplied in the X
770
 * headers
771
 *
772
 * @author Andreas Gohr <[email protected]>
773
 *
774
 * @param  boolean $single If set only a single IP is returned
775
 * @return string
776
 */
777
function clientIP($single = false) {
778
    /* @var Input $INPUT */
779
    global $INPUT;
780
781
    $ip   = array();
782
    $ip[] = $INPUT->server->str('REMOTE_ADDR');
783
    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
784
        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
785
    }
786
    if($INPUT->server->str('HTTP_X_REAL_IP')) {
787
        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
788
    }
789
790
    // some IPv4/v6 regexps borrowed from Feyd
791
    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
792
    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
793
    $hex_digit   = '[A-Fa-f0-9]';
794
    $h16         = "{$hex_digit}{1,4}";
795
    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
796
    $ls32        = "(?:$h16:$h16|$IPv4Address)";
797
    $IPv6Address =
798
        "(?:(?:{$IPv4Address})|(?:".
799
            "(?:$h16:){6}$ls32".
800
            "|::(?:$h16:){5}$ls32".
801
            "|(?:$h16)?::(?:$h16:){4}$ls32".
802
            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
803
            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
804
            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
805
            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
806
            "|(?:(?:$h16:){0,5}$h16)?::$h16".
807
            "|(?:(?:$h16:){0,6}$h16)?::".
808
            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
809
810
    // remove any non-IP stuff
811
    $cnt   = count($ip);
812
    $match = array();
813
    for($i = 0; $i < $cnt; $i++) {
814
        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
815
            $ip[$i] = $match[0];
816
        } else {
817
            $ip[$i] = '';
818
        }
819
        if(empty($ip[$i])) unset($ip[$i]);
820
    }
821
    $ip = array_values(array_unique($ip));
822
    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
823
824
    if(!$single) return join(',', $ip);
825
826
    // decide which IP to use, trying to avoid local addresses
827
    $ip = array_reverse($ip);
828
    foreach($ip as $i) {
829
        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
830
            continue;
831
        } else {
832
            return $i;
833
        }
834
    }
835
    // still here? just use the first (last) address
836
    return $ip[0];
837
}
838
839
/**
840
 * Check if the browser is on a mobile device
841
 *
842
 * Adapted from the example code at url below
843
 *
844
 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
845
 *
846
 * @deprecated 2018-04-27 you probably want media queries instead anyway
847
 * @return bool if true, client is mobile browser; otherwise false
848
 */
849
function clientismobile() {
850
    /* @var Input $INPUT */
851
    global $INPUT;
852
853
    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
854
855
    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
856
857
    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
858
859
    $uamatches = join(
860
        '|',
861
        [
862
            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
863
            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
864
            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
865
            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
866
            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
867
            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
868
            '\d\d\di', 'moto'
869
        ]
870
    );
871
872
    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
873
874
    return false;
875
}
876
877
/**
878
 * check if a given link is interwiki link
879
 *
880
 * @param string $link the link, e.g. "wiki>page"
881
 * @return bool
882
 */
883
function link_isinterwiki($link){
884
    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
885
    return false;
886
}
887
888
/**
889
 * Convert one or more comma separated IPs to hostnames
890
 *
891
 * If $conf['dnslookups'] is disabled it simply returns the input string
892
 *
893
 * @author Glen Harris <[email protected]>
894
 *
895
 * @param  string $ips comma separated list of IP addresses
896
 * @return string a comma separated list of hostnames
897
 */
898
function gethostsbyaddrs($ips) {
899
    global $conf;
900
    if(!$conf['dnslookups']) return $ips;
901
902
    $hosts = array();
903
    $ips   = explode(',', $ips);
904
905
    if(is_array($ips)) {
906
        foreach($ips as $ip) {
907
            $hosts[] = gethostbyaddr(trim($ip));
908
        }
909
        return join(',', $hosts);
910
    } else {
911
        return gethostbyaddr(trim($ips));
912
    }
913
}
914
915
/**
916
 * Checks if a given page is currently locked.
917
 *
918
 * removes stale lockfiles
919
 *
920
 * @author Andreas Gohr <[email protected]>
921
 *
922
 * @param string $id page id
923
 * @return bool page is locked?
924
 */
925
function checklock($id) {
926
    global $conf;
927
    /* @var Input $INPUT */
928
    global $INPUT;
929
930
    $lock = wikiLockFN($id);
931
932
    //no lockfile
933
    if(!file_exists($lock)) return false;
934
935
    //lockfile expired
936
    if((time() - filemtime($lock)) > $conf['locktime']) {
937
        @unlink($lock);
938
        return false;
939
    }
940
941
    //my own lock
942
    @list($ip, $session) = explode("\n", io_readFile($lock));
943
    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
944
        return false;
945
    }
946
947
    return $ip;
948
}
949
950
/**
951
 * Lock a page for editing
952
 *
953
 * @author Andreas Gohr <[email protected]>
954
 *
955
 * @param string $id page id to lock
956
 */
957
function lock($id) {
958
    global $conf;
959
    /* @var Input $INPUT */
960
    global $INPUT;
961
962
    if($conf['locktime'] == 0) {
963
        return;
964
    }
965
966
    $lock = wikiLockFN($id);
967
    if($INPUT->server->str('REMOTE_USER')) {
968
        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
969
    } else {
970
        io_saveFile($lock, clientIP()."\n".session_id());
971
    }
972
}
973
974
/**
975
 * Unlock a page if it was locked by the user
976
 *
977
 * @author Andreas Gohr <[email protected]>
978
 *
979
 * @param string $id page id to unlock
980
 * @return bool true if a lock was removed
981
 */
982
function unlock($id) {
983
    /* @var Input $INPUT */
984
    global $INPUT;
985
986
    $lock = wikiLockFN($id);
987
    if(file_exists($lock)) {
988
        @list($ip, $session) = explode("\n", io_readFile($lock));
989
        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
990
            @unlink($lock);
991
            return true;
992
        }
993
    }
994
    return false;
995
}
996
997
/**
998
 * convert line ending to unix format
999
 *
1000
 * also makes sure the given text is valid UTF-8
1001
 *
1002
 * @see    formText() for 2crlf conversion
1003
 * @author Andreas Gohr <[email protected]>
1004
 *
1005
 * @param string $text
1006
 * @return string
1007
 */
1008
function cleanText($text) {
1009
    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
1010
1011
    // if the text is not valid UTF-8 we simply assume latin1
1012
    // this won't break any worse than it breaks with the wrong encoding
1013
    // but might actually fix the problem in many cases
1014
    if(!utf8_check($text)) $text = utf8_encode($text);
1015
1016
    return $text;
1017
}
1018
1019
/**
1020
 * Prepares text for print in Webforms by encoding special chars.
1021
 * It also converts line endings to Windows format which is
1022
 * pseudo standard for webforms.
1023
 *
1024
 * @see    cleanText() for 2unix conversion
1025
 * @author Andreas Gohr <[email protected]>
1026
 *
1027
 * @param string $text
1028
 * @return string
1029
 */
1030
function formText($text) {
1031
    $text = str_replace("\012", "\015\012", $text);
1032
    return htmlspecialchars($text);
1033
}
1034
1035
/**
1036
 * Returns the specified local text in raw format
1037
 *
1038
 * @author Andreas Gohr <[email protected]>
1039
 *
1040
 * @param string $id   page id
1041
 * @param string $ext  extension of file being read, default 'txt'
1042
 * @return string
1043
 */
1044
function rawLocale($id, $ext = 'txt') {
1045
    return io_readFile(localeFN($id, $ext));
1046
}
1047
1048
/**
1049
 * Returns the raw WikiText
1050
 *
1051
 * @author Andreas Gohr <[email protected]>
1052
 *
1053
 * @param string $id   page id
1054
 * @param string|int $rev  timestamp when a revision of wikitext is desired
1055
 * @return string
1056
 */
1057
function rawWiki($id, $rev = '') {
1058
    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1059
}
1060
1061
/**
1062
 * Returns the pagetemplate contents for the ID's namespace
1063
 *
1064
 * @triggers COMMON_PAGETPL_LOAD
1065
 * @author Andreas Gohr <[email protected]>
1066
 *
1067
 * @param string $id the id of the page to be created
1068
 * @return string parsed pagetemplate content
1069
 */
1070
function pageTemplate($id) {
1071
    global $conf;
1072
1073
    if(is_array($id)) $id = $id[0];
1074
1075
    // prepare initial event data
1076
    $data = array(
1077
        'id'        => $id, // the id of the page to be created
1078
        'tpl'       => '', // the text used as template
1079
        'tplfile'   => '', // the file above text was/should be loaded from
1080
        'doreplace' => true // should wildcard replacements be done on the text?
1081
    );
1082
1083
    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
1084
    if($evt->advise_before(true)) {
1085
        // the before event might have loaded the content already
1086
        if(empty($data['tpl'])) {
1087
            // if the before event did not set a template file, try to find one
1088
            if(empty($data['tplfile'])) {
1089
                $path = dirname(wikiFN($id));
1090
                if(file_exists($path.'/_template.txt')) {
1091
                    $data['tplfile'] = $path.'/_template.txt';
1092
                } else {
1093
                    // search upper namespaces for templates
1094
                    $len = strlen(rtrim($conf['datadir'], '/'));
1095
                    while(strlen($path) >= $len) {
1096
                        if(file_exists($path.'/__template.txt')) {
1097
                            $data['tplfile'] = $path.'/__template.txt';
1098
                            break;
1099
                        }
1100
                        $path = substr($path, 0, strrpos($path, '/'));
1101
                    }
1102
                }
1103
            }
1104
            // load the content
1105
            $data['tpl'] = io_readFile($data['tplfile']);
1106
        }
1107
        if($data['doreplace']) parsePageTemplate($data);
1108
    }
1109
    $evt->advise_after();
1110
    unset($evt);
1111
1112
    return $data['tpl'];
1113
}
1114
1115
/**
1116
 * Performs common page template replacements
1117
 * This works on data from COMMON_PAGETPL_LOAD
1118
 *
1119
 * @author Andreas Gohr <[email protected]>
1120
 *
1121
 * @param array $data array with event data
1122
 * @return string
1123
 */
1124
function parsePageTemplate(&$data) {
1125
    /**
1126
     * @var string $id        the id of the page to be created
1127
     * @var string $tpl       the text used as template
1128
     * @var string $tplfile   the file above text was/should be loaded from
1129
     * @var bool   $doreplace should wildcard replacements be done on the text?
1130
     */
1131
    extract($data);
1132
1133
    global $USERINFO;
1134
    global $conf;
1135
    /* @var Input $INPUT */
1136
    global $INPUT;
1137
1138
    // replace placeholders
1139
    $file = noNS($id);
1140
    $page = strtr($file, $conf['sepchar'], ' ');
1141
1142
    $tpl = str_replace(
1143
        array(
1144
             '@ID@',
1145
             '@NS@',
1146
             '@CURNS@',
1147
             '@FILE@',
1148
             '@!FILE@',
1149
             '@!FILE!@',
1150
             '@PAGE@',
1151
             '@!PAGE@',
1152
             '@!!PAGE@',
1153
             '@!PAGE!@',
1154
             '@USER@',
1155
             '@NAME@',
1156
             '@MAIL@',
1157
             '@DATE@',
1158
        ),
1159
        array(
1160
             $id,
1161
             getNS($id),
1162
             curNS($id),
1163
             $file,
1164
             utf8_ucfirst($file),
1165
             utf8_strtoupper($file),
1166
             $page,
1167
             utf8_ucfirst($page),
1168
             utf8_ucwords($page),
1169
             utf8_strtoupper($page),
1170
             $INPUT->server->str('REMOTE_USER'),
1171
             $USERINFO['name'],
1172
             $USERINFO['mail'],
1173
             $conf['dformat'],
1174
        ), $tpl
1175
    );
1176
1177
    // we need the callback to work around strftime's char limit
1178
    $tpl = preg_replace_callback(
1179
        '/%./',
1180
        function ($m) {
1181
            return strftime($m[0]);
1182
        },
1183
        $tpl
1184
    );
1185
    $data['tpl'] = $tpl;
1186
    return $tpl;
1187
}
1188
1189
/**
1190
 * Returns the raw Wiki Text in three slices.
1191
 *
1192
 * The range parameter needs to have the form "from-to"
1193
 * and gives the range of the section in bytes - no
1194
 * UTF-8 awareness is needed.
1195
 * The returned order is prefix, section and suffix.
1196
 *
1197
 * @author Andreas Gohr <[email protected]>
1198
 *
1199
 * @param string $range in form "from-to"
1200
 * @param string $id    page id
1201
 * @param string $rev   optional, the revision timestamp
1202
 * @return string[] with three slices
1203
 */
1204
function rawWikiSlices($range, $id, $rev = '') {
1205
    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1206
1207
    // Parse range
1208
    list($from, $to) = explode('-', $range, 2);
1209
    // Make range zero-based, use defaults if marker is missing
1210
    $from = !$from ? 0 : ($from - 1);
1211
    $to   = !$to ? strlen($text) : ($to - 1);
1212
1213
    $slices = array();
1214
    $slices[0] = substr($text, 0, $from);
1215
    $slices[1] = substr($text, $from, $to - $from);
1216
    $slices[2] = substr($text, $to);
1217
    return $slices;
1218
}
1219
1220
/**
1221
 * Joins wiki text slices
1222
 *
1223
 * function to join the text slices.
1224
 * When the pretty parameter is set to true it adds additional empty
1225
 * lines between sections if needed (used on saving).
1226
 *
1227
 * @author Andreas Gohr <[email protected]>
1228
 *
1229
 * @param string $pre   prefix
1230
 * @param string $text  text in the middle
1231
 * @param string $suf   suffix
1232
 * @param bool $pretty add additional empty lines between sections
1233
 * @return string
1234
 */
1235
function con($pre, $text, $suf, $pretty = false) {
1236
    if($pretty) {
1237
        if($pre !== '' && substr($pre, -1) !== "\n" &&
1238
            substr($text, 0, 1) !== "\n"
1239
        ) {
1240
            $pre .= "\n";
1241
        }
1242
        if($suf !== '' && substr($text, -1) !== "\n" &&
1243
            substr($suf, 0, 1) !== "\n"
1244
        ) {
1245
            $text .= "\n";
1246
        }
1247
    }
1248
1249
    return $pre.$text.$suf;
1250
}
1251
1252
/**
1253
 * Checks if the current page version is newer than the last entry in the page's
1254
 * changelog. If so, we assume it has been an external edit and we create an
1255
 * attic copy and add a proper changelog line.
1256
 *
1257
 * This check is only executed when the page is about to be saved again from the
1258
 * wiki, triggered in @see saveWikiText()
1259
 *
1260
 * @param string $id the page ID
1261
 */
1262
function detectExternalEdit($id) {
1263
    global $lang;
1264
1265
    $fileLastMod = wikiFN($id);
1266
    $lastMod     = @filemtime($fileLastMod); // from page
1267
    $pagelog     = new PageChangeLog($id, 1024);
1268
    $lastRev     = $pagelog->getRevisions(-1, 1); // from changelog
1269
    $lastRev     = (int) (empty($lastRev) ? 0 : $lastRev[0]);
1270
1271
    if(!file_exists(wikiFN($id, $lastMod)) && file_exists($fileLastMod) && $lastMod >= $lastRev) {
1272
        // add old revision to the attic if missing
1273
        saveOldRevision($id);
1274
        // add a changelog entry if this edit came from outside dokuwiki
1275
        if($lastMod > $lastRev) {
1276
            $fileLastRev = wikiFN($id, $lastRev);
1277
            $revinfo = $pagelog->getRevisionInfo($lastRev);
1278
            if(empty($lastRev) || !file_exists($fileLastRev) || $revinfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
1279
                $filesize_old = 0;
1280
            } else {
1281
                $filesize_old = io_getSizeFile($fileLastRev);
1282
            }
1283
            $filesize_new = filesize($fileLastMod);
1284
            $sizechange = $filesize_new - $filesize_old;
1285
1286
            addLogEntry(
1287
                $lastMod,
1288
                $id,
1289
                DOKU_CHANGE_TYPE_EDIT,
1290
                $lang['external_edit'],
1291
                '',
1292
                array('ExternalEdit' => true),
1293
                $sizechange
1294
            );
1295
            // remove soon to be stale instructions
1296
            $cache = new cache_instructions($id, $fileLastMod);
1297
            $cache->removeCache();
1298
        }
1299
    }
1300
}
1301
1302
/**
1303
 * Saves a wikitext by calling io_writeWikiPage.
1304
 * Also directs changelog and attic updates.
1305
 *
1306
 * @author Andreas Gohr <[email protected]>
1307
 * @author Ben Coburn <[email protected]>
1308
 *
1309
 * @param string $id       page id
1310
 * @param string $text     wikitext being saved
1311
 * @param string $summary  summary of text update
1312
 * @param bool   $minor    mark this saved version as minor update
1313
 */
1314
function saveWikiText($id, $text, $summary, $minor = false) {
1315
    /* Note to developers:
1316
       This code is subtle and delicate. Test the behavior of
1317
       the attic and changelog with dokuwiki and external edits
1318
       after any changes. External edits change the wiki page
1319
       directly without using php or dokuwiki.
1320
     */
1321
    global $conf;
1322
    global $lang;
1323
    global $REV;
1324
    /* @var Input $INPUT */
1325
    global $INPUT;
1326
1327
    // prepare data for event
1328
    $svdta = array();
1329
    $svdta['id']             = $id;
1330
    $svdta['file']           = wikiFN($id);
1331
    $svdta['revertFrom']     = $REV;
1332
    $svdta['oldRevision']    = @filemtime($svdta['file']);
1333
    $svdta['newRevision']    = 0;
1334
    $svdta['newContent']     = $text;
1335
    $svdta['oldContent']     = rawWiki($id);
1336
    $svdta['summary']        = $summary;
1337
    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1338
    $svdta['changeInfo']     = '';
1339
    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
1340
    $svdta['sizechange']     = null;
1341
1342
    // select changelog line type
1343
    if($REV) {
1344
        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1345
        $svdta['changeInfo'] = $REV;
1346
    } else if(!file_exists($svdta['file'])) {
1347
        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1348
    } else if(trim($text) == '') {
1349
        // empty or whitespace only content deletes
1350
        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1351
        // autoset summary on deletion
1352
        if(blank($svdta['summary'])) {
1353
            $svdta['summary'] = $lang['deleted'];
1354
        }
1355
    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1356
        //minor edits only for logged in users
1357
        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1358
    }
1359
1360
    $event = new Doku_Event('COMMON_WIKIPAGE_SAVE', $svdta);
1361
    if(!$event->advise_before()) return;
1362
1363
    // if the content has not been changed, no save happens (plugins may override this)
1364
    if(!$svdta['contentChanged']) return;
1365
1366
    detectExternalEdit($id);
1367
1368
    if(
1369
        $svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE ||
1370
        ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file']))
1371
    ) {
1372
        $filesize_old = 0;
1373
    } else {
1374
        $filesize_old = filesize($svdta['file']);
1375
    }
1376
    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
1377
        // Send "update" event with empty data, so plugins can react to page deletion
1378
        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
1379
        trigger_event('IO_WIKIPAGE_WRITE', $data);
1380
        // pre-save deleted revision
1381
        @touch($svdta['file']);
1382
        clearstatcache();
1383
        $svdta['newRevision'] = saveOldRevision($id);
1384
        // remove empty file
1385
        @unlink($svdta['file']);
1386
        $filesize_new = 0;
1387
        // don't remove old meta info as it should be saved, plugins can use
1388
        // IO_WIKIPAGE_WRITE for removing their metadata...
1389
        // purge non-persistant meta data
1390
        p_purge_metadata($id);
1391
        // remove empty namespaces
1392
        io_sweepNS($id, 'datadir');
1393
        io_sweepNS($id, 'mediadir');
1394
    } else {
1395
        // save file (namespace dir is created in io_writeWikiPage)
1396
        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
1397
        // pre-save the revision, to keep the attic in sync
1398
        $svdta['newRevision'] = saveOldRevision($id);
1399
        $filesize_new = filesize($svdta['file']);
1400
    }
1401
    $svdta['sizechange'] = $filesize_new - $filesize_old;
1402
1403
    $event->advise_after();
1404
1405
    addLogEntry(
1406
        $svdta['newRevision'],
1407
        $svdta['id'],
1408
        $svdta['changeType'],
1409
        $svdta['summary'],
1410
        $svdta['changeInfo'],
1411
        null,
1412
        $svdta['sizechange']
1413
    );
1414
1415
    // send notify mails
1416
    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
1417
    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
1418
1419
    // update the purgefile (timestamp of the last time anything within the wiki was changed)
1420
    io_saveFile($conf['cachedir'].'/purgefile', time());
1421
1422
    // if useheading is enabled, purge the cache of all linking pages
1423
    if(useHeading('content')) {
1424
        $pages = ft_backlinks($id, true);
1425
        foreach($pages as $page) {
1426
            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1427
            $cache->removeCache();
1428
        }
1429
    }
1430
}
1431
1432
/**
1433
 * moves the current version to the attic and returns its
1434
 * revision date
1435
 *
1436
 * @author Andreas Gohr <[email protected]>
1437
 *
1438
 * @param string $id page id
1439
 * @return int|string revision timestamp
1440
 */
1441
function saveOldRevision($id) {
1442
    $oldf = wikiFN($id);
1443
    if(!file_exists($oldf)) return '';
1444
    $date = filemtime($oldf);
1445
    $newf = wikiFN($id, $date);
1446
    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1447
    return $date;
1448
}
1449
1450
/**
1451
 * Sends a notify mail on page change or registration
1452
 *
1453
 * @param string     $id       The changed page
1454
 * @param string     $who      Who to notify (admin|subscribers|register)
1455
 * @param int|string $rev Old page revision
1456
 * @param string     $summary  What changed
1457
 * @param boolean    $minor    Is this a minor edit?
1458
 * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
1459
 * @return bool
1460
 *
1461
 * @author Andreas Gohr <[email protected]>
1462
 */
1463
function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1464
    global $conf;
1465
    /* @var Input $INPUT */
1466
    global $INPUT;
1467
1468
    // decide if there is something to do, eg. whom to mail
1469
    if($who == 'admin') {
1470
        if(empty($conf['notify'])) return false; //notify enabled?
1471
        $tpl = 'mailtext';
1472
        $to  = $conf['notify'];
1473
    } elseif($who == 'subscribers') {
1474
        if(!actionOK('subscribe')) return false; //subscribers enabled?
1475
        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
1476
        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
1477
        trigger_event(
1478
            'COMMON_NOTIFY_ADDRESSLIST', $data,
1479
            array(new Subscription(), 'notifyaddresses')
1480
        );
1481
        $to = $data['addresslist'];
1482
        if(empty($to)) return false;
1483
        $tpl = 'subscr_single';
1484
    } else {
1485
        return false; //just to be safe
1486
    }
1487
1488
    // prepare content
1489
    $subscription = new Subscription();
1490
    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1491
}
1492
1493
/**
1494
 * extracts the query from a search engine referrer
1495
 *
1496
 * @author Andreas Gohr <[email protected]>
1497
 * @author Todd Augsburger <[email protected]>
1498
 *
1499
 * @return array|string
1500
 */
1501
function getGoogleQuery() {
1502
    /* @var Input $INPUT */
1503
    global $INPUT;
1504
1505
    if(!$INPUT->server->has('HTTP_REFERER')) {
1506
        return '';
1507
    }
1508
    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1509
1510
    // only handle common SEs
1511
    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1512
1513
    $query = array();
1514
    // temporary workaround against PHP bug #49733
1515
    // see http://bugs.php.net/bug.php?id=49733
1516
    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1517
    parse_str($url['query'], $query);
1518
    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1519
1520
    $q = '';
1521
    if(isset($query['q'])){
1522
        $q = $query['q'];
1523
    }elseif(isset($query['p'])){
1524
        $q = $query['p'];
1525
    }elseif(isset($query['query'])){
1526
        $q = $query['query'];
1527
    }
1528
    $q = trim($q);
1529
1530
    if(!$q) return '';
1531
    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1532
    return $q;
1533
}
1534
1535
/**
1536
 * Return the human readable size of a file
1537
 *
1538
 * @param int $size A file size
1539
 * @param int $dec A number of decimal places
1540
 * @return string human readable size
1541
 *
1542
 * @author      Martin Benjamin <[email protected]>
1543
 * @author      Aidan Lister <[email protected]>
1544
 * @version     1.0.0
1545
 */
1546
function filesize_h($size, $dec = 1) {
1547
    $sizes = array('B', 'KB', 'MB', 'GB');
1548
    $count = count($sizes);
1549
    $i     = 0;
1550
1551
    while($size >= 1024 && ($i < $count - 1)) {
1552
        $size /= 1024;
1553
        $i++;
1554
    }
1555
1556
    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1557
}
1558
1559
/**
1560
 * Return the given timestamp as human readable, fuzzy age
1561
 *
1562
 * @author Andreas Gohr <[email protected]>
1563
 *
1564
 * @param int $dt timestamp
1565
 * @return string
1566
 */
1567
function datetime_h($dt) {
1568
    global $lang;
1569
1570
    $ago = time() - $dt;
1571
    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1572
        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1573
    }
1574
    if($ago > 24 * 60 * 60 * 30 * 2) {
1575
        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1576
    }
1577
    if($ago > 24 * 60 * 60 * 7 * 2) {
1578
        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1579
    }
1580
    if($ago > 24 * 60 * 60 * 2) {
1581
        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1582
    }
1583
    if($ago > 60 * 60 * 2) {
1584
        return sprintf($lang['hours'], round($ago / (60 * 60)));
1585
    }
1586
    if($ago > 60 * 2) {
1587
        return sprintf($lang['minutes'], round($ago / (60)));
1588
    }
1589
    return sprintf($lang['seconds'], $ago);
1590
}
1591
1592
/**
1593
 * Wraps around strftime but provides support for fuzzy dates
1594
 *
1595
 * The format default to $conf['dformat']. It is passed to
1596
 * strftime - %f can be used to get the value from datetime_h()
1597
 *
1598
 * @see datetime_h
1599
 * @author Andreas Gohr <[email protected]>
1600
 *
1601
 * @param int|null $dt      timestamp when given, null will take current timestamp
1602
 * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1603
 * @return string
1604
 */
1605
function dformat($dt = null, $format = '') {
1606
    global $conf;
1607
1608
    if(is_null($dt)) $dt = time();
1609
    $dt = (int) $dt;
1610
    if(!$format) $format = $conf['dformat'];
1611
1612
    $format = str_replace('%f', datetime_h($dt), $format);
1613
    return strftime($format, $dt);
1614
}
1615
1616
/**
1617
 * Formats a timestamp as ISO 8601 date
1618
 *
1619
 * @author <ungu at terong dot com>
1620
 * @link http://php.net/manual/en/function.date.php#54072
1621
 *
1622
 * @param int $int_date current date in UNIX timestamp
1623
 * @return string
1624
 */
1625
function date_iso8601($int_date) {
1626
    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1627
    $pre_timezone = date('O', $int_date);
1628
    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1629
    $date_mod .= $time_zone;
1630
    return $date_mod;
1631
}
1632
1633
/**
1634
 * return an obfuscated email address in line with $conf['mailguard'] setting
1635
 *
1636
 * @author Harry Fuecks <[email protected]>
1637
 * @author Christopher Smith <[email protected]>
1638
 *
1639
 * @param string $email email address
1640
 * @return string
1641
 */
1642
function obfuscate($email) {
1643
    global $conf;
1644
1645
    switch($conf['mailguard']) {
1646
        case 'visible' :
1647
            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1648
            return strtr($email, $obfuscate);
1649
1650
        case 'hex' :
1651
            $encode = '';
1652
            $len    = strlen($email);
1653
            for($x = 0; $x < $len; $x++) {
1654
                $encode .= '&#x'.bin2hex($email{$x}).';';
1655
            }
1656
            return $encode;
1657
1658
        case 'none' :
1659
        default :
1660
            return $email;
1661
    }
1662
}
1663
1664
/**
1665
 * Removes quoting backslashes
1666
 *
1667
 * @author Andreas Gohr <[email protected]>
1668
 *
1669
 * @param string $string
1670
 * @param string $char backslashed character
1671
 * @return string
1672
 */
1673
function unslash($string, $char = "'") {
1674
    return str_replace('\\'.$char, $char, $string);
1675
}
1676
1677
/**
1678
 * Convert php.ini shorthands to byte
1679
 *
1680
 * @author <gilthans dot NO dot SPAM at gmail dot com>
1681
 * @link   http://php.net/manual/en/ini.core.php#79564
1682
 *
1683
 * @param string $v shorthands
1684
 * @return int|string
1685
 */
1686
function php_to_byte($v) {
1687
    $l   = substr($v, -1);
1688
    $ret = substr($v, 0, -1);
1689
    switch(strtoupper($l)) {
1690
        /** @noinspection PhpMissingBreakStatementInspection */
1691
        case 'P':
1692
            $ret *= 1024;
1693
        /** @noinspection PhpMissingBreakStatementInspection */
1694
        case 'T':
1695
            $ret *= 1024;
1696
        /** @noinspection PhpMissingBreakStatementInspection */
1697
        case 'G':
1698
            $ret *= 1024;
1699
        /** @noinspection PhpMissingBreakStatementInspection */
1700
        case 'M':
1701
            $ret *= 1024;
1702
        /** @noinspection PhpMissingBreakStatementInspection */
1703
        case 'K':
1704
            $ret *= 1024;
1705
            break;
1706
        default;
1707
            $ret *= 10;
1708
            break;
1709
    }
1710
    return $ret;
1711
}
1712
1713
/**
1714
 * Wrapper around preg_quote adding the default delimiter
1715
 *
1716
 * @param string $string
1717
 * @return string
1718
 */
1719
function preg_quote_cb($string) {
1720
    return preg_quote($string, '/');
1721
}
1722
1723
/**
1724
 * Shorten a given string by removing data from the middle
1725
 *
1726
 * You can give the string in two parts, the first part $keep
1727
 * will never be shortened. The second part $short will be cut
1728
 * in the middle to shorten but only if at least $min chars are
1729
 * left to display it. Otherwise it will be left off.
1730
 *
1731
 * @param string $keep   the part to keep
1732
 * @param string $short  the part to shorten
1733
 * @param int    $max    maximum chars you want for the whole string
1734
 * @param int    $min    minimum number of chars to have left for middle shortening
1735
 * @param string $char   the shortening character to use
1736
 * @return string
1737
 */
1738
function shorten($keep, $short, $max, $min = 9, $char = '…') {
1739
    $max = $max - utf8_strlen($keep);
1740
    if($max < $min) return $keep;
1741
    $len = utf8_strlen($short);
1742
    if($len <= $max) return $keep.$short;
1743
    $half = floor($max / 2);
1744
    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1745
}
1746
1747
/**
1748
 * Return the users real name or e-mail address for use
1749
 * in page footer and recent changes pages
1750
 *
1751
 * @param string|null $username or null when currently logged-in user should be used
1752
 * @param bool $textonly true returns only plain text, true allows returning html
1753
 * @return string html or plain text(not escaped) of formatted user name
1754
 *
1755
 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1756
 */
1757
function editorinfo($username, $textonly = false) {
1758
    return userlink($username, $textonly);
1759
}
1760
1761
/**
1762
 * Returns users realname w/o link
1763
 *
1764
 * @param string|null $username or null when currently logged-in user should be used
1765
 * @param bool $textonly true returns only plain text, true allows returning html
1766
 * @return string html or plain text(not escaped) of formatted user name
1767
 *
1768
 * @triggers COMMON_USER_LINK
1769
 */
1770
function userlink($username = null, $textonly = false) {
1771
    global $conf, $INFO;
1772
    /** @var DokuWiki_Auth_Plugin $auth */
1773
    global $auth;
1774
    /** @var Input $INPUT */
1775
    global $INPUT;
1776
1777
    // prepare initial event data
1778
    $data = array(
1779
        'username' => $username, // the unique user name
1780
        'name' => '',
1781
        'link' => array( //setting 'link' to false disables linking
1782
                         'target' => '',
1783
                         'pre' => '',
1784
                         'suf' => '',
1785
                         'style' => '',
1786
                         'more' => '',
1787
                         'url' => '',
1788
                         'title' => '',
1789
                         'class' => ''
1790
        ),
1791
        'userlink' => '', // formatted user name as will be returned
1792
        'textonly' => $textonly
1793
    );
1794
    if($username === null) {
1795
        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
1796
        if($textonly){
1797
            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
1798
        }else {
1799
            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
1800
                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
1801
        }
1802
    }
1803
1804
    $evt = new Doku_Event('COMMON_USER_LINK', $data);
1805
    if($evt->advise_before(true)) {
1806
        if(empty($data['name'])) {
1807
            if($auth) $info = $auth->getUserData($username);
1808
            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1809
                switch($conf['showuseras']) {
1810
                    case 'username':
1811
                    case 'username_link':
1812
                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
1813
                        break;
1814
                    case 'email':
1815
                    case 'email_link':
1816
                        $data['name'] = obfuscate($info['mail']);
1817
                        break;
1818
                }
1819
            } else {
1820
                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
1821
            }
1822
        }
1823
1824
        /** @var Doku_Renderer_xhtml $xhtml_renderer */
1825
        static $xhtml_renderer = null;
1826
1827
        if(!$data['textonly'] && empty($data['link']['url'])) {
1828
1829
            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
1830
                if(!isset($info)) {
1831
                    if($auth) $info = $auth->getUserData($username);
1832
                }
1833
                if(isset($info) && $info) {
1834
                    if($conf['showuseras'] == 'email_link') {
1835
                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1836
                    } else {
1837
                        if(is_null($xhtml_renderer)) {
1838
                            $xhtml_renderer = p_get_renderer('xhtml');
1839
                        }
1840
                        if(empty($xhtml_renderer->interwiki)) {
1841
                            $xhtml_renderer->interwiki = getInterwiki();
1842
                        }
1843
                        $shortcut = 'user';
1844
                        $exists = null;
1845
                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
1846
                        $data['link']['class'] .= ' interwiki iw_user';
1847
                        if($exists !== null) {
1848
                            if($exists) {
1849
                                $data['link']['class'] .= ' wikilink1';
1850
                            } else {
1851
                                $data['link']['class'] .= ' wikilink2';
1852
                                $data['link']['rel'] = 'nofollow';
1853
                            }
1854
                        }
1855
                    }
1856
                } else {
1857
                    $data['textonly'] = true;
1858
                }
1859
1860
            } else {
1861
                $data['textonly'] = true;
1862
            }
1863
        }
1864
1865
        if($data['textonly']) {
1866
            $data['userlink'] = $data['name'];
1867
        } else {
1868
            $data['link']['name'] = $data['name'];
1869
            if(is_null($xhtml_renderer)) {
1870
                $xhtml_renderer = p_get_renderer('xhtml');
1871
            }
1872
            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
1873
        }
1874
    }
1875
    $evt->advise_after();
1876
    unset($evt);
1877
1878
    return $data['userlink'];
1879
}
1880
1881
/**
1882
 * Returns the path to a image file for the currently chosen license.
1883
 * When no image exists, returns an empty string
1884
 *
1885
 * @author Andreas Gohr <[email protected]>
1886
 *
1887
 * @param  string $type - type of image 'badge' or 'button'
1888
 * @return string
1889
 */
1890
function license_img($type) {
1891
    global $license;
1892
    global $conf;
1893
    if(!$conf['license']) return '';
1894
    if(!is_array($license[$conf['license']])) return '';
1895
    $try   = array();
1896
    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1897
    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1898
    if(substr($conf['license'], 0, 3) == 'cc-') {
1899
        $try[] = 'lib/images/license/'.$type.'/cc.png';
1900
    }
1901
    foreach($try as $src) {
1902
        if(file_exists(DOKU_INC.$src)) return $src;
1903
    }
1904
    return '';
1905
}
1906
1907
/**
1908
 * Checks if the given amount of memory is available
1909
 *
1910
 * If the memory_get_usage() function is not available the
1911
 * function just assumes $bytes of already allocated memory
1912
 *
1913
 * @author Filip Oscadal <[email protected]>
1914
 * @author Andreas Gohr <[email protected]>
1915
 *
1916
 * @param int  $mem    Size of memory you want to allocate in bytes
1917
 * @param int  $bytes  already allocated memory (see above)
1918
 * @return bool
1919
 */
1920
function is_mem_available($mem, $bytes = 1048576) {
1921
    $limit = trim(ini_get('memory_limit'));
1922
    if(empty($limit)) return true; // no limit set!
1923
1924
    // parse limit to bytes
1925
    $limit = php_to_byte($limit);
1926
1927
    // get used memory if possible
1928
    if(function_exists('memory_get_usage')) {
1929
        $used = memory_get_usage();
1930
    } else {
1931
        $used = $bytes;
1932
    }
1933
1934
    if($used + $mem > $limit) {
1935
        return false;
1936
    }
1937
1938
    return true;
1939
}
1940
1941
/**
1942
 * Send a HTTP redirect to the browser
1943
 *
1944
 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1945
 *
1946
 * @link   http://support.microsoft.com/kb/q176113/
1947
 * @author Andreas Gohr <[email protected]>
1948
 *
1949
 * @param string $url url being directed to
1950
 */
1951
function send_redirect($url) {
1952
    $url = stripctl($url); // defend against HTTP Response Splitting
1953
1954
    /* @var Input $INPUT */
1955
    global $INPUT;
1956
1957
    //are there any undisplayed messages? keep them in session for display
1958
    global $MSG;
1959
    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
1960
        //reopen session, store data and close session again
1961
        @session_start();
1962
        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1963
    }
1964
1965
    // always close the session
1966
    session_write_close();
1967
1968
    // check if running on IIS < 6 with CGI-PHP
1969
    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1970
        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1971
        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
1972
        $matches[1] < 6
1973
    ) {
1974
        header('Refresh: 0;url='.$url);
1975
    } else {
1976
        header('Location: '.$url);
1977
    }
1978
1979
    // no exits during unit tests
1980
    if(defined('DOKU_UNITTEST')) {
1981
        // pass info about the redirect back to the test suite
1982
        $testRequest = TestRequest::getRunning();
1983
        if($testRequest !== null) {
1984
            $testRequest->addData('send_redirect', $url);
1985
        }
1986
        return;
1987
    }
1988
1989
    exit;
1990
}
1991
1992
/**
1993
 * Validate a value using a set of valid values
1994
 *
1995
 * This function checks whether a specified value is set and in the array
1996
 * $valid_values. If not, the function returns a default value or, if no
1997
 * default is specified, throws an exception.
1998
 *
1999
 * @param string $param        The name of the parameter
2000
 * @param array  $valid_values A set of valid values; Optionally a default may
2001
 *                             be marked by the key “default”.
2002
 * @param array  $array        The array containing the value (typically $_POST
2003
 *                             or $_GET)
2004
 * @param string $exc          The text of the raised exception
2005
 *
2006
 * @throws Exception
2007
 * @return mixed
2008
 * @author Adrian Lang <[email protected]>
2009
 */
2010
function valid_input_set($param, $valid_values, $array, $exc = '') {
2011
    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
2012
        return $array[$param];
2013
    } elseif(isset($valid_values['default'])) {
2014
        return $valid_values['default'];
2015
    } else {
2016
        throw new Exception($exc);
2017
    }
2018
}
2019
2020
/**
2021
 * Read a preference from the DokuWiki cookie
2022
 * (remembering both keys & values are urlencoded)
2023
 *
2024
 * @param string $pref     preference key
2025
 * @param mixed  $default  value returned when preference not found
2026
 * @return string preference value
2027
 */
2028
function get_doku_pref($pref, $default) {
2029
    $enc_pref = urlencode($pref);
2030
    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
2031
        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
2032
        $cnt   = count($parts);
2033
        for($i = 0; $i < $cnt; $i += 2) {
2034
            if($parts[$i] == $enc_pref) {
2035
                return urldecode($parts[$i + 1]);
2036
            }
2037
        }
2038
    }
2039
    return $default;
2040
}
2041
2042
/**
2043
 * Add a preference to the DokuWiki cookie
2044
 * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
2045
 * Remove it by setting $val to false
2046
 *
2047
 * @param string $pref  preference key
2048
 * @param string $val   preference value
2049
 */
2050
function set_doku_pref($pref, $val) {
2051
    global $conf;
2052
    $orig = get_doku_pref($pref, false);
2053
    $cookieVal = '';
2054
2055
    if($orig && ($orig != $val)) {
2056
        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
2057
        $cnt   = count($parts);
2058
        // urlencode $pref for the comparison
2059
        $enc_pref = rawurlencode($pref);
2060
        for($i = 0; $i < $cnt; $i += 2) {
2061
            if($parts[$i] == $enc_pref) {
2062
                if ($val !== false) {
2063
                    $parts[$i + 1] = rawurlencode($val);
2064
                } else {
2065
                    unset($parts[$i]);
2066
                    unset($parts[$i + 1]);
2067
                }
2068
                break;
2069
            }
2070
        }
2071
        $cookieVal = implode('#', $parts);
2072
    } else if (!$orig && $val !== false) {
2073
        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').
2074
            rawurlencode($pref).'#'.rawurlencode($val);
2075
    }
2076
2077
    if (!empty($cookieVal)) {
2078
        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
2079
        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
2080
    }
2081
}
2082
2083
/**
2084
 * Strips source mapping declarations from given text #601
2085
 *
2086
 * @param string &$text reference to the CSS or JavaScript code to clean
2087
 */
2088
function stripsourcemaps(&$text){
2089
    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2090
}
2091
2092
/**
2093
 * Returns the contents of a given SVG file for embedding
2094
 *
2095
 * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
2096
 * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
2097
 * files are embedded.
2098
 *
2099
 * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
2100
 *
2101
 * @param string $file full path to the SVG file
2102
 * @param int $maxsize maximum allowed size for the SVG to be embedded
2103
 * @return string|false the SVG content, false if the file couldn't be loaded
2104
 */
2105
function inlineSVG($file, $maxsize = 2048) {
2106
    $file = trim($file);
2107
    if($file === '') return false;
2108
    if(!file_exists($file)) return false;
2109
    if(filesize($file) > $maxsize) return false;
2110
    if(!is_readable($file)) return false;
2111
    $content = file_get_contents($file);
2112
    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
2113
    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
2114
    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
2115
    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
2116
    $content = trim($content);
2117
    if(substr($content, 0, 5) !== '<svg ') return false;
2118
    return $content;
2119
}
2120
2121
//Setup VIM: ex: et ts=2 :
2122