Completed
Push — phpsizeshorthand ( c6e971 )
by Andreas
13:41 queued 06:29
created

common.php ➔ php_to_byte()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
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
if(!defined('DOKU_INC')) die('meh.');
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());
0 ignored issues
show
Bug introduced by
It seems like auth_cookiesalt() can also be of type boolean; however, PassHash::hmac() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
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) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $title of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
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']) $urlParameters['at'] = date($conf['date_at_format'],$urlParameters['at']);
489
        $urlParameters = buildURLparams($urlParameters, $separator);
490
    } else {
491
        $urlParameters = str_replace(',', $separator, $urlParameters);
492
    }
493
    if($id === '') {
494
        $id = $conf['start'];
495
    }
496
    $id = idfilter($id);
497
    if($absolute) {
498
        $xlink = DOKU_URL;
499
    } else {
500
        $xlink = DOKU_BASE;
501
    }
502
503
    if($conf['userewrite'] == 2) {
504
        $xlink .= DOKU_SCRIPT.'/'.$id;
505
        if($urlParameters) $xlink .= '?'.$urlParameters;
506
    } elseif($conf['userewrite']) {
507
        $xlink .= $id;
508
        if($urlParameters) $xlink .= '?'.$urlParameters;
509
    } elseif($id !== '') {
510
        $xlink .= DOKU_SCRIPT.'?id='.$id;
511
        if($urlParameters) $xlink .= $separator.$urlParameters;
512
    } else {
513
        $xlink .= DOKU_SCRIPT;
514
        if($urlParameters) $xlink .= '?'.$urlParameters;
515
    }
516
517
    return $xlink;
518
}
519
520
/**
521
 * This builds a link to an alternate page format
522
 *
523
 * Handles URL rewriting if enabled. Follows the style of wl().
524
 *
525
 * @author Ben Coburn <[email protected]>
526
 * @param string       $id             page id, defaults to start page
527
 * @param string       $format         the export renderer to use
528
 * @param string|array $urlParameters  URL parameters, associative array recommended
529
 * @param bool         $abs            request an absolute URL instead of relative
530
 * @param string       $sep            parameter separator
531
 * @return string
532
 */
533
function exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
534
    global $conf;
535
    if(is_array($urlParameters)) {
536
        $urlParameters = buildURLparams($urlParameters, $sep);
537
    } else {
538
        $urlParameters = str_replace(',', $sep, $urlParameters);
539
    }
540
541
    $format = rawurlencode($format);
542
    $id     = idfilter($id);
543
    if($abs) {
544
        $xlink = DOKU_URL;
545
    } else {
546
        $xlink = DOKU_BASE;
547
    }
548
549
    if($conf['userewrite'] == 2) {
550
        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
551
        if($urlParameters) $xlink .= $sep.$urlParameters;
552
    } elseif($conf['userewrite'] == 1) {
553
        $xlink .= '_export/'.$format.'/'.$id;
554
        if($urlParameters) $xlink .= '?'.$urlParameters;
555
    } else {
556
        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
557
        if($urlParameters) $xlink .= $sep.$urlParameters;
558
    }
559
560
    return $xlink;
561
}
562
563
/**
564
 * Build a link to a media file
565
 *
566
 * Will return a link to the detail page if $direct is false
567
 *
568
 * The $more parameter should always be given as array, the function then
569
 * will strip default parameters to produce even cleaner URLs
570
 *
571
 * @param string  $id     the media file id or URL
572
 * @param mixed   $more   string or array with additional parameters
573
 * @param bool    $direct link to detail page if false
574
 * @param string  $sep    URL parameter separator
575
 * @param bool    $abs    Create an absolute URL
576
 * @return string
577
 */
578
function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
579
    global $conf;
580
    $isexternalimage = media_isexternal($id);
581
    if(!$isexternalimage) {
582
        $id = cleanID($id);
583
    }
584
585
    if(is_array($more)) {
586
        // add token for resized images
587
        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
588
            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
589
        }
590
        // strip defaults for shorter URLs
591
        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
592
        if(empty($more['w'])) unset($more['w']);
593
        if(empty($more['h'])) unset($more['h']);
594
        if(isset($more['id']) && $direct) unset($more['id']);
595
        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
596
        $more = buildURLparams($more, $sep);
597
    } else {
598
        $matches = array();
599
        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
600
            $resize = array('w'=>0, 'h'=>0);
601
            foreach ($matches as $match){
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
602
                $resize[$match[1]] = $match[2];
603
            }
604
            $more .= $more === '' ? '' : $sep;
605
            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
606
        }
607
        $more = str_replace('cache=cache', '', $more); //skip default
608
        $more = str_replace(',,', ',', $more);
609
        $more = str_replace(',', $sep, $more);
610
    }
611
612
    if($abs) {
613
        $xlink = DOKU_URL;
614
    } else {
615
        $xlink = DOKU_BASE;
616
    }
617
618
    // external URLs are always direct without rewriting
619
    if($isexternalimage) {
620
        $xlink .= 'lib/exe/fetch.php';
621
        $xlink .= '?'.$more;
622
        $xlink .= $sep.'media='.rawurlencode($id);
623
        return $xlink;
624
    }
625
626
    $id = idfilter($id);
627
628
    // decide on scriptname
629
    if($direct) {
630
        if($conf['userewrite'] == 1) {
631
            $script = '_media';
632
        } else {
633
            $script = 'lib/exe/fetch.php';
634
        }
635
    } else {
636
        if($conf['userewrite'] == 1) {
637
            $script = '_detail';
638
        } else {
639
            $script = 'lib/exe/detail.php';
640
        }
641
    }
642
643
    // build URL based on rewrite mode
644
    if($conf['userewrite']) {
645
        $xlink .= $script.'/'.$id;
646
        if($more) $xlink .= '?'.$more;
647
    } else {
648
        if($more) {
649
            $xlink .= $script.'?'.$more;
650
            $xlink .= $sep.'media='.$id;
651
        } else {
652
            $xlink .= $script.'?media='.$id;
653
        }
654
    }
655
656
    return $xlink;
657
}
658
659
/**
660
 * Returns the URL to the DokuWiki base script
661
 *
662
 * Consider using wl() instead, unless you absoutely need the doku.php endpoint
663
 *
664
 * @author Andreas Gohr <[email protected]>
665
 *
666
 * @return string
667
 */
668
function script() {
669
    return DOKU_BASE.DOKU_SCRIPT;
670
}
671
672
/**
673
 * Spamcheck against wordlist
674
 *
675
 * Checks the wikitext against a list of blocked expressions
676
 * returns true if the text contains any bad words
677
 *
678
 * Triggers COMMON_WORDBLOCK_BLOCKED
679
 *
680
 *  Action Plugins can use this event to inspect the blocked data
681
 *  and gain information about the user who was blocked.
682
 *
683
 *  Event data:
684
 *    data['matches']  - array of matches
685
 *    data['userinfo'] - information about the blocked user
686
 *      [ip]           - ip address
687
 *      [user]         - username (if logged in)
688
 *      [mail]         - mail address (if logged in)
689
 *      [name]         - real name (if logged in)
690
 *
691
 * @author Andreas Gohr <[email protected]>
692
 * @author Michael Klier <[email protected]>
693
 *
694
 * @param  string $text - optional text to check, if not given the globals are used
695
 * @return bool         - true if a spam word was found
696
 */
697
function checkwordblock($text = '') {
698
    global $TEXT;
699
    global $PRE;
700
    global $SUF;
701
    global $SUM;
702
    global $conf;
703
    global $INFO;
704
    /* @var Input $INPUT */
705
    global $INPUT;
706
707
    if(!$conf['usewordblock']) return false;
708
709
    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
710
711
    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
712
    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
713
714
    $wordblocks = getWordblocks();
715
    // how many lines to read at once (to work around some PCRE limits)
716
    if(version_compare(phpversion(), '4.3.0', '<')) {
717
        // old versions of PCRE define a maximum of parenthesises even if no
718
        // backreferences are used - the maximum is 99
719
        // this is very bad performancewise and may even be too high still
720
        $chunksize = 40;
721
    } else {
722
        // read file in chunks of 200 - this should work around the
723
        // MAX_PATTERN_SIZE in modern PCRE
724
        $chunksize = 200;
725
    }
726
    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
727
        $re = array();
728
        // build regexp from blocks
729
        foreach($blocks as $block) {
730
            $block = preg_replace('/#.*$/', '', $block);
731
            $block = trim($block);
732
            if(empty($block)) continue;
733
            $re[] = $block;
734
        }
735
        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
736
            // prepare event data
737
            $data = array();
738
            $data['matches']        = $matches;
739
            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
740
            if($INPUT->server->str('REMOTE_USER')) {
741
                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
742
                $data['userinfo']['name'] = $INFO['userinfo']['name'];
743
                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
744
            }
745
            $callback = function () {
746
                return true;
747
            };
748
            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
749
        }
750
    }
751
    return false;
752
}
753
754
/**
755
 * Return the IP of the client
756
 *
757
 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
758
 *
759
 * It returns a comma separated list of IPs if the above mentioned
760
 * headers are set. If the single parameter is set, it tries to return
761
 * a routable public address, prefering the ones suplied in the X
762
 * headers
763
 *
764
 * @author Andreas Gohr <[email protected]>
765
 *
766
 * @param  boolean $single If set only a single IP is returned
767
 * @return string
768
 */
769
function clientIP($single = false) {
770
    /* @var Input $INPUT */
771
    global $INPUT;
772
773
    $ip   = array();
774
    $ip[] = $INPUT->server->str('REMOTE_ADDR');
775
    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
776
        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
777
    }
778
    if($INPUT->server->str('HTTP_X_REAL_IP')) {
779
        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
780
    }
781
782
    // some IPv4/v6 regexps borrowed from Feyd
783
    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
784
    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
785
    $hex_digit   = '[A-Fa-f0-9]';
786
    $h16         = "{$hex_digit}{1,4}";
787
    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
788
    $ls32        = "(?:$h16:$h16|$IPv4Address)";
789
    $IPv6Address =
790
        "(?:(?:{$IPv4Address})|(?:".
791
            "(?:$h16:){6}$ls32".
792
            "|::(?:$h16:){5}$ls32".
793
            "|(?:$h16)?::(?:$h16:){4}$ls32".
794
            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
795
            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
796
            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
797
            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
798
            "|(?:(?:$h16:){0,5}$h16)?::$h16".
799
            "|(?:(?:$h16:){0,6}$h16)?::".
800
            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
801
802
    // remove any non-IP stuff
803
    $cnt   = count($ip);
804
    $match = array();
805
    for($i = 0; $i < $cnt; $i++) {
806
        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
807
            $ip[$i] = $match[0];
808
        } else {
809
            $ip[$i] = '';
810
        }
811
        if(empty($ip[$i])) unset($ip[$i]);
812
    }
813
    $ip = array_values(array_unique($ip));
814
    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
815
816
    if(!$single) return join(',', $ip);
817
818
    // decide which IP to use, trying to avoid local addresses
819
    $ip = array_reverse($ip);
820
    foreach($ip as $i) {
821
        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
822
            continue;
823
        } else {
824
            return $i;
825
        }
826
    }
827
    // still here? just use the first (last) address
828
    return $ip[0];
829
}
830
831
/**
832
 * Check if the browser is on a mobile device
833
 *
834
 * Adapted from the example code at url below
835
 *
836
 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
837
 *
838
 * @return bool if true, client is mobile browser; otherwise false
839
 */
840
function clientismobile() {
841
    /* @var Input $INPUT */
842
    global $INPUT;
843
844
    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
845
846
    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
847
848
    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
849
850
    $uamatches = 'midp|j2me|avantg|docomo|novarra|palmos|palmsource|240x320|opwv|chtml|pda|windows ce|mmp\/|blackberry|mib\/|symbian|wireless|nokia|hand|mobi|phone|cdm|up\.b|audio|SIE\-|SEC\-|samsung|HTC|mot\-|mitsu|sagem|sony|alcatel|lg|erics|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch|rover|pocket|benq|java|pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|\d\d\di|moto';
851
852
    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
853
854
    return false;
855
}
856
857
/**
858
 * check if a given link is interwiki link
859
 *
860
 * @param string $link the link, e.g. "wiki>page"
861
 * @return bool
862
 */
863
function link_isinterwiki($link){
864
    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
865
    return false;
866
}
867
868
/**
869
 * Convert one or more comma separated IPs to hostnames
870
 *
871
 * If $conf['dnslookups'] is disabled it simply returns the input string
872
 *
873
 * @author Glen Harris <[email protected]>
874
 *
875
 * @param  string $ips comma separated list of IP addresses
876
 * @return string a comma separated list of hostnames
877
 */
878
function gethostsbyaddrs($ips) {
879
    global $conf;
880
    if(!$conf['dnslookups']) return $ips;
881
882
    $hosts = array();
883
    $ips   = explode(',', $ips);
884
885
    if(is_array($ips)) {
886
        foreach($ips as $ip) {
887
            $hosts[] = gethostbyaddr(trim($ip));
888
        }
889
        return join(',', $hosts);
890
    } else {
891
        return gethostbyaddr(trim($ips));
892
    }
893
}
894
895
/**
896
 * Checks if a given page is currently locked.
897
 *
898
 * removes stale lockfiles
899
 *
900
 * @author Andreas Gohr <[email protected]>
901
 *
902
 * @param string $id page id
903
 * @return bool page is locked?
904
 */
905
function checklock($id) {
906
    global $conf;
907
    /* @var Input $INPUT */
908
    global $INPUT;
909
910
    $lock = wikiLockFN($id);
911
912
    //no lockfile
913
    if(!file_exists($lock)) return false;
914
915
    //lockfile expired
916
    if((time() - filemtime($lock)) > $conf['locktime']) {
917
        @unlink($lock);
918
        return false;
919
    }
920
921
    //my own lock
922
    @list($ip, $session) = explode("\n", io_readFile($lock));
923
    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
924
        return false;
925
    }
926
927
    return $ip;
928
}
929
930
/**
931
 * Lock a page for editing
932
 *
933
 * @author Andreas Gohr <[email protected]>
934
 *
935
 * @param string $id page id to lock
936
 */
937
function lock($id) {
938
    global $conf;
939
    /* @var Input $INPUT */
940
    global $INPUT;
941
942
    if($conf['locktime'] == 0) {
943
        return;
944
    }
945
946
    $lock = wikiLockFN($id);
947
    if($INPUT->server->str('REMOTE_USER')) {
948
        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
949
    } else {
950
        io_saveFile($lock, clientIP()."\n".session_id());
951
    }
952
}
953
954
/**
955
 * Unlock a page if it was locked by the user
956
 *
957
 * @author Andreas Gohr <[email protected]>
958
 *
959
 * @param string $id page id to unlock
960
 * @return bool true if a lock was removed
961
 */
962
function unlock($id) {
963
    /* @var Input $INPUT */
964
    global $INPUT;
965
966
    $lock = wikiLockFN($id);
967
    if(file_exists($lock)) {
968
        @list($ip, $session) = explode("\n", io_readFile($lock));
969
        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
970
            @unlink($lock);
971
            return true;
972
        }
973
    }
974
    return false;
975
}
976
977
/**
978
 * convert line ending to unix format
979
 *
980
 * also makes sure the given text is valid UTF-8
981
 *
982
 * @see    formText() for 2crlf conversion
983
 * @author Andreas Gohr <[email protected]>
984
 *
985
 * @param string $text
986
 * @return string
987
 */
988
function cleanText($text) {
989
    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
990
991
    // if the text is not valid UTF-8 we simply assume latin1
992
    // this won't break any worse than it breaks with the wrong encoding
993
    // but might actually fix the problem in many cases
994
    if(!utf8_check($text)) $text = utf8_encode($text);
995
996
    return $text;
997
}
998
999
/**
1000
 * Prepares text for print in Webforms by encoding special chars.
1001
 * It also converts line endings to Windows format which is
1002
 * pseudo standard for webforms.
1003
 *
1004
 * @see    cleanText() for 2unix conversion
1005
 * @author Andreas Gohr <[email protected]>
1006
 *
1007
 * @param string $text
1008
 * @return string
1009
 */
1010
function formText($text) {
1011
    $text = str_replace("\012", "\015\012", $text);
1012
    return htmlspecialchars($text);
1013
}
1014
1015
/**
1016
 * Returns the specified local text in raw format
1017
 *
1018
 * @author Andreas Gohr <[email protected]>
1019
 *
1020
 * @param string $id   page id
1021
 * @param string $ext  extension of file being read, default 'txt'
1022
 * @return string
1023
 */
1024
function rawLocale($id, $ext = 'txt') {
1025
    return io_readFile(localeFN($id, $ext));
1026
}
1027
1028
/**
1029
 * Returns the raw WikiText
1030
 *
1031
 * @author Andreas Gohr <[email protected]>
1032
 *
1033
 * @param string $id   page id
1034
 * @param string|int $rev  timestamp when a revision of wikitext is desired
1035
 * @return string
1036
 */
1037
function rawWiki($id, $rev = '') {
1038
    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1039
}
1040
1041
/**
1042
 * Returns the pagetemplate contents for the ID's namespace
1043
 *
1044
 * @triggers COMMON_PAGETPL_LOAD
1045
 * @author Andreas Gohr <[email protected]>
1046
 *
1047
 * @param string $id the id of the page to be created
1048
 * @return string parsed pagetemplate content
1049
 */
1050
function pageTemplate($id) {
1051
    global $conf;
1052
1053
    if(is_array($id)) $id = $id[0];
1054
1055
    // prepare initial event data
1056
    $data = array(
1057
        'id'        => $id, // the id of the page to be created
1058
        'tpl'       => '', // the text used as template
1059
        'tplfile'   => '', // the file above text was/should be loaded from
1060
        'doreplace' => true // should wildcard replacements be done on the text?
1061
    );
1062
1063
    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
1064
    if($evt->advise_before(true)) {
1065
        // the before event might have loaded the content already
1066
        if(empty($data['tpl'])) {
1067
            // if the before event did not set a template file, try to find one
1068
            if(empty($data['tplfile'])) {
1069
                $path = dirname(wikiFN($id));
1070
                if(file_exists($path.'/_template.txt')) {
1071
                    $data['tplfile'] = $path.'/_template.txt';
1072
                } else {
1073
                    // search upper namespaces for templates
1074
                    $len = strlen(rtrim($conf['datadir'], '/'));
1075
                    while(strlen($path) >= $len) {
1076
                        if(file_exists($path.'/__template.txt')) {
1077
                            $data['tplfile'] = $path.'/__template.txt';
1078
                            break;
1079
                        }
1080
                        $path = substr($path, 0, strrpos($path, '/'));
1081
                    }
1082
                }
1083
            }
1084
            // load the content
1085
            $data['tpl'] = io_readFile($data['tplfile']);
1086
        }
1087
        if($data['doreplace']) parsePageTemplate($data);
1088
    }
1089
    $evt->advise_after();
1090
    unset($evt);
1091
1092
    return $data['tpl'];
1093
}
1094
1095
/**
1096
 * Performs common page template replacements
1097
 * This works on data from COMMON_PAGETPL_LOAD
1098
 *
1099
 * @author Andreas Gohr <[email protected]>
1100
 *
1101
 * @param array $data array with event data
1102
 * @return string
1103
 */
1104
function parsePageTemplate(&$data) {
1105
    /**
1106
     * @var string $id        the id of the page to be created
1107
     * @var string $tpl       the text used as template
1108
     * @var string $tplfile   the file above text was/should be loaded from
1109
     * @var bool   $doreplace should wildcard replacements be done on the text?
1110
     */
1111
    extract($data);
1112
1113
    global $USERINFO;
1114
    global $conf;
1115
    /* @var Input $INPUT */
1116
    global $INPUT;
1117
1118
    // replace placeholders
1119
    $file = noNS($id);
1120
    $page = strtr($file, $conf['sepchar'], ' ');
1121
1122
    $tpl = str_replace(
1123
        array(
1124
             '@ID@',
1125
             '@NS@',
1126
             '@CURNS@',
1127
             '@FILE@',
1128
             '@!FILE@',
1129
             '@!FILE!@',
1130
             '@PAGE@',
1131
             '@!PAGE@',
1132
             '@!!PAGE@',
1133
             '@!PAGE!@',
1134
             '@USER@',
1135
             '@NAME@',
1136
             '@MAIL@',
1137
             '@DATE@',
1138
        ),
1139
        array(
1140
             $id,
1141
             getNS($id),
1142
             curNS($id),
1143
             $file,
1144
             utf8_ucfirst($file),
1145
             utf8_strtoupper($file),
1146
             $page,
1147
             utf8_ucfirst($page),
1148
             utf8_ucwords($page),
1149
             utf8_strtoupper($page),
1150
             $INPUT->server->str('REMOTE_USER'),
1151
             $USERINFO['name'],
1152
             $USERINFO['mail'],
1153
             $conf['dformat'],
1154
        ), $tpl
1155
    );
1156
1157
    // we need the callback to work around strftime's char limit
1158
    $tpl = preg_replace_callback(
1159
        '/%./',
1160
        function ($m) {
1161
            return strftime($m[0]);
1162
        },
1163
        $tpl
1164
    );
1165
    $data['tpl'] = $tpl;
1166
    return $tpl;
1167
}
1168
1169
/**
1170
 * Returns the raw Wiki Text in three slices.
1171
 *
1172
 * The range parameter needs to have the form "from-to"
1173
 * and gives the range of the section in bytes - no
1174
 * UTF-8 awareness is needed.
1175
 * The returned order is prefix, section and suffix.
1176
 *
1177
 * @author Andreas Gohr <[email protected]>
1178
 *
1179
 * @param string $range in form "from-to"
1180
 * @param string $id    page id
1181
 * @param string $rev   optional, the revision timestamp
1182
 * @return string[] with three slices
1183
 */
1184
function rawWikiSlices($range, $id, $rev = '') {
1185
    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1186
1187
    // Parse range
1188
    list($from, $to) = explode('-', $range, 2);
1189
    // Make range zero-based, use defaults if marker is missing
1190
    $from = !$from ? 0 : ($from - 1);
1191
    $to   = !$to ? strlen($text) : ($to - 1);
1192
1193
    $slices = array();
1194
    $slices[0] = substr($text, 0, $from);
1195
    $slices[1] = substr($text, $from, $to - $from);
1196
    $slices[2] = substr($text, $to);
1197
    return $slices;
1198
}
1199
1200
/**
1201
 * Joins wiki text slices
1202
 *
1203
 * function to join the text slices.
1204
 * When the pretty parameter is set to true it adds additional empty
1205
 * lines between sections if needed (used on saving).
1206
 *
1207
 * @author Andreas Gohr <[email protected]>
1208
 *
1209
 * @param string $pre   prefix
1210
 * @param string $text  text in the middle
1211
 * @param string $suf   suffix
1212
 * @param bool $pretty add additional empty lines between sections
1213
 * @return string
1214
 */
1215
function con($pre, $text, $suf, $pretty = false) {
1216
    if($pretty) {
1217
        if($pre !== '' && substr($pre, -1) !== "\n" &&
1218
            substr($text, 0, 1) !== "\n"
1219
        ) {
1220
            $pre .= "\n";
1221
        }
1222
        if($suf !== '' && substr($text, -1) !== "\n" &&
1223
            substr($suf, 0, 1) !== "\n"
1224
        ) {
1225
            $text .= "\n";
1226
        }
1227
    }
1228
1229
    return $pre.$text.$suf;
1230
}
1231
1232
/**
1233
 * Checks if the current page version is newer than the last entry in the page's
1234
 * changelog. If so, we assume it has been an external edit and we create an
1235
 * attic copy and add a proper changelog line.
1236
 *
1237
 * This check is only executed when the page is about to be saved again from the
1238
 * wiki, triggered in @see saveWikiText()
1239
 *
1240
 * @param string $id the page ID
1241
 */
1242
function detectExternalEdit($id) {
1243
    global $lang;
1244
1245
    $fileLastMod = wikiFN($id);
1246
    $lastMod     = @filemtime($fileLastMod); // from page
1247
    $pagelog     = new PageChangeLog($id, 1024);
1248
    $lastRev     = $pagelog->getRevisions(-1, 1); // from changelog
1249
    $lastRev     = (int) (empty($lastRev) ? 0 : $lastRev[0]);
1250
1251
    if(!file_exists(wikiFN($id, $lastMod)) && file_exists($fileLastMod) && $lastMod >= $lastRev) {
1252
        // add old revision to the attic if missing
1253
        saveOldRevision($id);
1254
        // add a changelog entry if this edit came from outside dokuwiki
1255
        if($lastMod > $lastRev) {
1256
            $fileLastRev = wikiFN($id, $lastRev);
1257
            $revinfo = $pagelog->getRevisionInfo($lastRev);
1258
            if(empty($lastRev) || !file_exists($fileLastRev) || $revinfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
1259
                $filesize_old = 0;
1260
            } else {
1261
                $filesize_old = io_getSizeFile($fileLastRev);
1262
            }
1263
            $filesize_new = filesize($fileLastMod);
1264
            $sizechange = $filesize_new - $filesize_old;
1265
1266
            addLogEntry($lastMod, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true), $sizechange);
1267
            // remove soon to be stale instructions
1268
            $cache = new cache_instructions($id, $fileLastMod);
1269
            $cache->removeCache();
1270
        }
1271
    }
1272
}
1273
1274
/**
1275
 * Saves a wikitext by calling io_writeWikiPage.
1276
 * Also directs changelog and attic updates.
1277
 *
1278
 * @author Andreas Gohr <[email protected]>
1279
 * @author Ben Coburn <[email protected]>
1280
 *
1281
 * @param string $id       page id
1282
 * @param string $text     wikitext being saved
1283
 * @param string $summary  summary of text update
1284
 * @param bool   $minor    mark this saved version as minor update
1285
 */
1286
function saveWikiText($id, $text, $summary, $minor = false) {
1287
    /* Note to developers:
1288
       This code is subtle and delicate. Test the behavior of
1289
       the attic and changelog with dokuwiki and external edits
1290
       after any changes. External edits change the wiki page
1291
       directly without using php or dokuwiki.
1292
     */
1293
    global $conf;
1294
    global $lang;
1295
    global $REV;
1296
    /* @var Input $INPUT */
1297
    global $INPUT;
1298
1299
    // prepare data for event
1300
    $svdta = array();
1301
    $svdta['id']             = $id;
1302
    $svdta['file']           = wikiFN($id);
1303
    $svdta['revertFrom']     = $REV;
1304
    $svdta['oldRevision']    = @filemtime($svdta['file']);
1305
    $svdta['newRevision']    = 0;
1306
    $svdta['newContent']     = $text;
1307
    $svdta['oldContent']     = rawWiki($id);
1308
    $svdta['summary']        = $summary;
1309
    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1310
    $svdta['changeInfo']     = '';
1311
    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
1312
    $svdta['sizechange']     = null;
1313
1314
    // select changelog line type
1315
    if($REV) {
1316
        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1317
        $svdta['changeInfo'] = $REV;
1318
    } else if(!file_exists($svdta['file'])) {
1319
        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1320
    } else if(trim($text) == '') {
1321
        // empty or whitespace only content deletes
1322
        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1323
        // autoset summary on deletion
1324
        if(blank($svdta['summary'])) {
1325
            $svdta['summary'] = $lang['deleted'];
1326
        }
1327
    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1328
        //minor edits only for logged in users
1329
        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1330
    }
1331
1332
    $event = new Doku_Event('COMMON_WIKIPAGE_SAVE', $svdta);
1333
    if(!$event->advise_before()) return;
1334
1335
    // if the content has not been changed, no save happens (plugins may override this)
1336
    if(!$svdta['contentChanged']) return;
1337
1338
    detectExternalEdit($id);
1339
1340
    if(
1341
        $svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE ||
1342
        ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file']))
1343
    ) {
1344
        $filesize_old = 0;
1345
    } else {
1346
        $filesize_old = filesize($svdta['file']);
1347
    }
1348
    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
1349
        // Send "update" event with empty data, so plugins can react to page deletion
1350
        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
1351
        trigger_event('IO_WIKIPAGE_WRITE', $data);
1352
        // pre-save deleted revision
1353
        @touch($svdta['file']);
1354
        clearstatcache();
1355
        $svdta['newRevision'] = saveOldRevision($id);
1356
        // remove empty file
1357
        @unlink($svdta['file']);
1358
        $filesize_new = 0;
1359
        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1360
        // purge non-persistant meta data
1361
        p_purge_metadata($id);
1362
        // remove empty namespaces
1363
        io_sweepNS($id, 'datadir');
1364
        io_sweepNS($id, 'mediadir');
1365
    } else {
1366
        // save file (namespace dir is created in io_writeWikiPage)
1367
        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
1368
        // pre-save the revision, to keep the attic in sync
1369
        $svdta['newRevision'] = saveOldRevision($id);
1370
        $filesize_new = filesize($svdta['file']);
1371
    }
1372
    $svdta['sizechange'] = $filesize_new - $filesize_old;
1373
1374
    $event->advise_after();
1375
1376
    addLogEntry($svdta['newRevision'], $svdta['id'], $svdta['changeType'], $svdta['summary'], $svdta['changeInfo'], null, $svdta['sizechange']);
1377
1378
    // send notify mails
1379
    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
1380
    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
1381
1382
    // update the purgefile (timestamp of the last time anything within the wiki was changed)
1383
    io_saveFile($conf['cachedir'].'/purgefile', time());
1384
1385
    // if useheading is enabled, purge the cache of all linking pages
1386
    if(useHeading('content')) {
1387
        $pages = ft_backlinks($id, true);
1388
        foreach($pages as $page) {
1389
            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1390
            $cache->removeCache();
1391
        }
1392
    }
1393
}
1394
1395
/**
1396
 * moves the current version to the attic and returns its
1397
 * revision date
1398
 *
1399
 * @author Andreas Gohr <[email protected]>
1400
 *
1401
 * @param string $id page id
1402
 * @return int|string revision timestamp
1403
 */
1404
function saveOldRevision($id) {
1405
    $oldf = wikiFN($id);
1406
    if(!file_exists($oldf)) return '';
1407
    $date = filemtime($oldf);
1408
    $newf = wikiFN($id, $date);
1409
    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1410
    return $date;
1411
}
1412
1413
/**
1414
 * Sends a notify mail on page change or registration
1415
 *
1416
 * @param string     $id       The changed page
1417
 * @param string     $who      Who to notify (admin|subscribers|register)
1418
 * @param int|string $rev Old page revision
1419
 * @param string     $summary  What changed
1420
 * @param boolean    $minor    Is this a minor edit?
1421
 * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
1422
 * @return bool
1423
 *
1424
 * @author Andreas Gohr <[email protected]>
1425
 */
1426
function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1427
    global $conf;
1428
    /* @var Input $INPUT */
1429
    global $INPUT;
1430
1431
    // decide if there is something to do, eg. whom to mail
1432
    if($who == 'admin') {
1433
        if(empty($conf['notify'])) return false; //notify enabled?
1434
        $tpl = 'mailtext';
1435
        $to  = $conf['notify'];
1436
    } elseif($who == 'subscribers') {
1437
        if(!actionOK('subscribe')) return false; //subscribers enabled?
1438
        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
1439
        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
1440
        trigger_event(
1441
            'COMMON_NOTIFY_ADDRESSLIST', $data,
1442
            array(new Subscription(), 'notifyaddresses')
1443
        );
1444
        $to = $data['addresslist'];
1445
        if(empty($to)) return false;
1446
        $tpl = 'subscr_single';
1447
    } else {
1448
        return false; //just to be safe
1449
    }
1450
1451
    // prepare content
1452
    $subscription = new Subscription();
1453
    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1454
}
1455
1456
/**
1457
 * extracts the query from a search engine referrer
1458
 *
1459
 * @author Andreas Gohr <[email protected]>
1460
 * @author Todd Augsburger <[email protected]>
1461
 *
1462
 * @return array|string
1463
 */
1464
function getGoogleQuery() {
1465
    /* @var Input $INPUT */
1466
    global $INPUT;
1467
1468
    if(!$INPUT->server->has('HTTP_REFERER')) {
1469
        return '';
1470
    }
1471
    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1472
1473
    // only handle common SEs
1474
    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1475
1476
    $query = array();
1477
    // temporary workaround against PHP bug #49733
1478
    // see http://bugs.php.net/bug.php?id=49733
1479
    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1480
    parse_str($url['query'], $query);
1481
    if(UTF8_MBSTRING) mb_internal_encoding($enc);
0 ignored issues
show
Bug introduced by
The variable $enc does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1482
1483
    $q = '';
1484
    if(isset($query['q'])){
1485
        $q = $query['q'];
1486
    }elseif(isset($query['p'])){
1487
        $q = $query['p'];
1488
    }elseif(isset($query['query'])){
1489
        $q = $query['query'];
1490
    }
1491
    $q = trim($q);
1492
1493
    if(!$q) return '';
1494
    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1495
    return $q;
1496
}
1497
1498
/**
1499
 * Return the human readable size of a file
1500
 *
1501
 * @param int $size A file size
1502
 * @param int $dec A number of decimal places
1503
 * @return string human readable size
1504
 *
1505
 * @author      Martin Benjamin <[email protected]>
1506
 * @author      Aidan Lister <[email protected]>
1507
 * @version     1.0.0
1508
 */
1509
function filesize_h($size, $dec = 1) {
1510
    $sizes = array('B', 'KB', 'MB', 'GB');
1511
    $count = count($sizes);
1512
    $i     = 0;
1513
1514
    while($size >= 1024 && ($i < $count - 1)) {
1515
        $size /= 1024;
1516
        $i++;
1517
    }
1518
1519
    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1520
}
1521
1522
/**
1523
 * Return the given timestamp as human readable, fuzzy age
1524
 *
1525
 * @author Andreas Gohr <[email protected]>
1526
 *
1527
 * @param int $dt timestamp
1528
 * @return string
1529
 */
1530
function datetime_h($dt) {
1531
    global $lang;
1532
1533
    $ago = time() - $dt;
1534
    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1535
        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1536
    }
1537
    if($ago > 24 * 60 * 60 * 30 * 2) {
1538
        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1539
    }
1540
    if($ago > 24 * 60 * 60 * 7 * 2) {
1541
        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1542
    }
1543
    if($ago > 24 * 60 * 60 * 2) {
1544
        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1545
    }
1546
    if($ago > 60 * 60 * 2) {
1547
        return sprintf($lang['hours'], round($ago / (60 * 60)));
1548
    }
1549
    if($ago > 60 * 2) {
1550
        return sprintf($lang['minutes'], round($ago / (60)));
1551
    }
1552
    return sprintf($lang['seconds'], $ago);
1553
}
1554
1555
/**
1556
 * Wraps around strftime but provides support for fuzzy dates
1557
 *
1558
 * The format default to $conf['dformat']. It is passed to
1559
 * strftime - %f can be used to get the value from datetime_h()
1560
 *
1561
 * @see datetime_h
1562
 * @author Andreas Gohr <[email protected]>
1563
 *
1564
 * @param int|null $dt      timestamp when given, null will take current timestamp
1565
 * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1566
 * @return string
1567
 */
1568
function dformat($dt = null, $format = '') {
1569
    global $conf;
1570
1571
    if(is_null($dt)) $dt = time();
1572
    $dt = (int) $dt;
1573
    if(!$format) $format = $conf['dformat'];
1574
1575
    $format = str_replace('%f', datetime_h($dt), $format);
1576
    return strftime($format, $dt);
1577
}
1578
1579
/**
1580
 * Formats a timestamp as ISO 8601 date
1581
 *
1582
 * @author <ungu at terong dot com>
1583
 * @link http://php.net/manual/en/function.date.php#54072
1584
 *
1585
 * @param int $int_date current date in UNIX timestamp
1586
 * @return string
1587
 */
1588
function date_iso8601($int_date) {
1589
    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1590
    $pre_timezone = date('O', $int_date);
1591
    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1592
    $date_mod .= $time_zone;
1593
    return $date_mod;
1594
}
1595
1596
/**
1597
 * return an obfuscated email address in line with $conf['mailguard'] setting
1598
 *
1599
 * @author Harry Fuecks <[email protected]>
1600
 * @author Christopher Smith <[email protected]>
1601
 *
1602
 * @param string $email email address
1603
 * @return string
1604
 */
1605
function obfuscate($email) {
1606
    global $conf;
1607
1608
    switch($conf['mailguard']) {
1609
        case 'visible' :
1610
            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1611
            return strtr($email, $obfuscate);
1612
1613
        case 'hex' :
1614
            $encode = '';
1615
            $len    = strlen($email);
1616
            for($x = 0; $x < $len; $x++) {
1617
                $encode .= '&#x'.bin2hex($email{$x}).';';
1618
            }
1619
            return $encode;
1620
1621
        case 'none' :
1622
        default :
1623
            return $email;
1624
    }
1625
}
1626
1627
/**
1628
 * Removes quoting backslashes
1629
 *
1630
 * @author Andreas Gohr <[email protected]>
1631
 *
1632
 * @param string $string
1633
 * @param string $char backslashed character
1634
 * @return string
1635
 */
1636
function unslash($string, $char = "'") {
1637
    return str_replace('\\'.$char, $char, $string);
1638
}
1639
1640
/**
1641
 * Convert php.ini shorthands to byte
1642
 *
1643
 * On 32 bit systems values >= 2GB will fail!
1644
 *
1645
 * -1 (infinite size) will be reported as -1
1646
 *
1647
 * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1648
 * @param string $value PHP size shorthand
1649
 * @return int
1650
 */
1651
function php_to_byte($value) {
1652
    switch (strtoupper($value[-1])) {
1653
        case 'G':
1654
            $ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024;
1655
            break;
1656
        case 'M':
1657
            $ret = intval(substr($value, 0, -1)) * 1024 * 1024;
1658
            break;
1659
        case 'K':
1660
            $ret = intval(substr($value, 0, -1)) * 1024;
1661
            break;
1662
        default;
1663
            $ret = intval($value);
1664
            break;
1665
    }
1666
    return $ret;
1667
}
1668
1669
/**
1670
 * Wrapper around preg_quote adding the default delimiter
1671
 *
1672
 * @param string $string
1673
 * @return string
1674
 */
1675
function preg_quote_cb($string) {
1676
    return preg_quote($string, '/');
1677
}
1678
1679
/**
1680
 * Shorten a given string by removing data from the middle
1681
 *
1682
 * You can give the string in two parts, the first part $keep
1683
 * will never be shortened. The second part $short will be cut
1684
 * in the middle to shorten but only if at least $min chars are
1685
 * left to display it. Otherwise it will be left off.
1686
 *
1687
 * @param string $keep   the part to keep
1688
 * @param string $short  the part to shorten
1689
 * @param int    $max    maximum chars you want for the whole string
1690
 * @param int    $min    minimum number of chars to have left for middle shortening
1691
 * @param string $char   the shortening character to use
1692
 * @return string
1693
 */
1694
function shorten($keep, $short, $max, $min = 9, $char = '…') {
1695
    $max = $max - utf8_strlen($keep);
1696
    if($max < $min) return $keep;
1697
    $len = utf8_strlen($short);
1698
    if($len <= $max) return $keep.$short;
1699
    $half = floor($max / 2);
1700
    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1701
}
1702
1703
/**
1704
 * Return the users real name or e-mail address for use
1705
 * in page footer and recent changes pages
1706
 *
1707
 * @param string|null $username or null when currently logged-in user should be used
1708
 * @param bool $textonly true returns only plain text, true allows returning html
1709
 * @return string html or plain text(not escaped) of formatted user name
1710
 *
1711
 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1712
 */
1713
function editorinfo($username, $textonly = false) {
1714
    return userlink($username, $textonly);
1715
}
1716
1717
/**
1718
 * Returns users realname w/o link
1719
 *
1720
 * @param string|null $username or null when currently logged-in user should be used
1721
 * @param bool $textonly true returns only plain text, true allows returning html
1722
 * @return string html or plain text(not escaped) of formatted user name
1723
 *
1724
 * @triggers COMMON_USER_LINK
1725
 */
1726
function userlink($username = null, $textonly = false) {
1727
    global $conf, $INFO;
1728
    /** @var DokuWiki_Auth_Plugin $auth */
1729
    global $auth;
1730
    /** @var Input $INPUT */
1731
    global $INPUT;
1732
1733
    // prepare initial event data
1734
    $data = array(
1735
        'username' => $username, // the unique user name
1736
        'name' => '',
1737
        'link' => array( //setting 'link' to false disables linking
1738
                         'target' => '',
1739
                         'pre' => '',
1740
                         'suf' => '',
1741
                         'style' => '',
1742
                         'more' => '',
1743
                         'url' => '',
1744
                         'title' => '',
1745
                         'class' => ''
1746
        ),
1747
        'userlink' => '', // formatted user name as will be returned
1748
        'textonly' => $textonly
1749
    );
1750
    if($username === null) {
1751
        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
1752
        if($textonly){
1753
            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
1754
        }else {
1755
            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
1756
        }
1757
    }
1758
1759
    $evt = new Doku_Event('COMMON_USER_LINK', $data);
1760
    if($evt->advise_before(true)) {
1761
        if(empty($data['name'])) {
1762
            if($auth) $info = $auth->getUserData($username);
1763
            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1764
                switch($conf['showuseras']) {
1765
                    case 'username':
1766
                    case 'username_link':
1767
                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
1768
                        break;
1769
                    case 'email':
1770
                    case 'email_link':
1771
                        $data['name'] = obfuscate($info['mail']);
1772
                        break;
1773
                }
1774
            } else {
1775
                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
1776
            }
1777
        }
1778
1779
        /** @var Doku_Renderer_xhtml $xhtml_renderer */
1780
        static $xhtml_renderer = null;
1781
1782
        if(!$data['textonly'] && empty($data['link']['url'])) {
1783
1784
            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
1785
                if(!isset($info)) {
1786
                    if($auth) $info = $auth->getUserData($username);
1787
                }
1788
                if(isset($info) && $info) {
1789
                    if($conf['showuseras'] == 'email_link') {
1790
                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1791
                    } else {
1792
                        if(is_null($xhtml_renderer)) {
1793
                            $xhtml_renderer = p_get_renderer('xhtml');
1794
                        }
1795
                        if(empty($xhtml_renderer->interwiki)) {
1796
                            $xhtml_renderer->interwiki = getInterwiki();
1797
                        }
1798
                        $shortcut = 'user';
1799
                        $exists = null;
1800
                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
1801
                        $data['link']['class'] .= ' interwiki iw_user';
1802
                        if($exists !== null) {
1803
                            if($exists) {
1804
                                $data['link']['class'] .= ' wikilink1';
1805
                            } else {
1806
                                $data['link']['class'] .= ' wikilink2';
1807
                                $data['link']['rel'] = 'nofollow';
1808
                            }
1809
                        }
1810
                    }
1811
                } else {
1812
                    $data['textonly'] = true;
1813
                }
1814
1815
            } else {
1816
                $data['textonly'] = true;
1817
            }
1818
        }
1819
1820
        if($data['textonly']) {
1821
            $data['userlink'] = $data['name'];
1822
        } else {
1823
            $data['link']['name'] = $data['name'];
1824
            if(is_null($xhtml_renderer)) {
1825
                $xhtml_renderer = p_get_renderer('xhtml');
1826
            }
1827
            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
1828
        }
1829
    }
1830
    $evt->advise_after();
1831
    unset($evt);
1832
1833
    return $data['userlink'];
1834
}
1835
1836
/**
1837
 * Returns the path to a image file for the currently chosen license.
1838
 * When no image exists, returns an empty string
1839
 *
1840
 * @author Andreas Gohr <[email protected]>
1841
 *
1842
 * @param  string $type - type of image 'badge' or 'button'
1843
 * @return string
1844
 */
1845
function license_img($type) {
1846
    global $license;
1847
    global $conf;
1848
    if(!$conf['license']) return '';
1849
    if(!is_array($license[$conf['license']])) return '';
1850
    $try   = array();
1851
    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1852
    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1853
    if(substr($conf['license'], 0, 3) == 'cc-') {
1854
        $try[] = 'lib/images/license/'.$type.'/cc.png';
1855
    }
1856
    foreach($try as $src) {
1857
        if(file_exists(DOKU_INC.$src)) return $src;
1858
    }
1859
    return '';
1860
}
1861
1862
/**
1863
 * Checks if the given amount of memory is available
1864
 *
1865
 * If the memory_get_usage() function is not available the
1866
 * function just assumes $bytes of already allocated memory
1867
 *
1868
 * @author Filip Oscadal <[email protected]>
1869
 * @author Andreas Gohr <[email protected]>
1870
 *
1871
 * @param int  $mem    Size of memory you want to allocate in bytes
1872
 * @param int  $bytes  already allocated memory (see above)
1873
 * @return bool
1874
 */
1875
function is_mem_available($mem, $bytes = 1048576) {
1876
    $limit = trim(ini_get('memory_limit'));
1877
    if(empty($limit)) return true; // no limit set!
1878
    if($limit == -1) return true; // unlimited
1879
1880
    // parse limit to bytes
1881
    $limit = php_to_byte($limit);
1882
1883
    // get used memory if possible
1884
    if(function_exists('memory_get_usage')) {
1885
        $used = memory_get_usage();
1886
    } else {
1887
        $used = $bytes;
1888
    }
1889
1890
    if($used + $mem > $limit) {
1891
        return false;
1892
    }
1893
1894
    return true;
1895
}
1896
1897
/**
1898
 * Send a HTTP redirect to the browser
1899
 *
1900
 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1901
 *
1902
 * @link   http://support.microsoft.com/kb/q176113/
1903
 * @author Andreas Gohr <[email protected]>
1904
 *
1905
 * @param string $url url being directed to
1906
 */
1907
function send_redirect($url) {
1908
    $url = stripctl($url); // defend against HTTP Response Splitting
1909
1910
    /* @var Input $INPUT */
1911
    global $INPUT;
1912
1913
    //are there any undisplayed messages? keep them in session for display
1914
    global $MSG;
1915
    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
1916
        //reopen session, store data and close session again
1917
        @session_start();
1918
        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1919
    }
1920
1921
    // always close the session
1922
    session_write_close();
1923
1924
    // check if running on IIS < 6 with CGI-PHP
1925
    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1926
        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1927
        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
1928
        $matches[1] < 6
1929
    ) {
1930
        header('Refresh: 0;url='.$url);
1931
    } else {
1932
        header('Location: '.$url);
1933
    }
1934
1935
    // no exits during unit tests
1936
    if(defined('DOKU_UNITTEST')) {
1937
        // pass info about the redirect back to the test suite
1938
        $testRequest = TestRequest::getRunning();
1939
        if($testRequest !== null) {
1940
            $testRequest->addData('send_redirect', $url);
1941
        }
1942
        return;
1943
    }
1944
1945
    exit;
1946
}
1947
1948
/**
1949
 * Validate a value using a set of valid values
1950
 *
1951
 * This function checks whether a specified value is set and in the array
1952
 * $valid_values. If not, the function returns a default value or, if no
1953
 * default is specified, throws an exception.
1954
 *
1955
 * @param string $param        The name of the parameter
1956
 * @param array  $valid_values A set of valid values; Optionally a default may
1957
 *                             be marked by the key “default”.
1958
 * @param array  $array        The array containing the value (typically $_POST
1959
 *                             or $_GET)
1960
 * @param string $exc          The text of the raised exception
1961
 *
1962
 * @throws Exception
1963
 * @return mixed
1964
 * @author Adrian Lang <[email protected]>
1965
 */
1966
function valid_input_set($param, $valid_values, $array, $exc = '') {
1967
    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
1968
        return $array[$param];
1969
    } elseif(isset($valid_values['default'])) {
1970
        return $valid_values['default'];
1971
    } else {
1972
        throw new Exception($exc);
1973
    }
1974
}
1975
1976
/**
1977
 * Read a preference from the DokuWiki cookie
1978
 * (remembering both keys & values are urlencoded)
1979
 *
1980
 * @param string $pref     preference key
1981
 * @param mixed  $default  value returned when preference not found
1982
 * @return string preference value
1983
 */
1984
function get_doku_pref($pref, $default) {
1985
    $enc_pref = urlencode($pref);
1986
    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1987
        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1988
        $cnt   = count($parts);
1989
1990
        // due to #2721 there might be duplicate entries,
1991
        // so we read from the end
1992
        for($i = $cnt-2; $i >= 0; $i -= 2) {
1993
            if($parts[$i] == $enc_pref) {
1994
                return urldecode($parts[$i + 1]);
1995
            }
1996
        }
1997
    }
1998
    return $default;
1999
}
2000
2001
/**
2002
 * Add a preference to the DokuWiki cookie
2003
 * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
2004
 * Remove it by setting $val to false
2005
 *
2006
 * @param string $pref  preference key
2007
 * @param string $val   preference value
2008
 */
2009
function set_doku_pref($pref, $val) {
2010
    global $conf;
2011
    $orig = get_doku_pref($pref, false);
2012
    $cookieVal = '';
2013
2014
    if($orig !== false && ($orig !== $val)) {
2015
        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
2016
        $cnt   = count($parts);
2017
        // urlencode $pref for the comparison
2018
        $enc_pref = rawurlencode($pref);
2019
        $seen = false;
2020
        for ($i = 0; $i < $cnt; $i += 2) {
2021
            if ($parts[$i] == $enc_pref) {
2022
                if (!$seen){
2023
                    if ($val !== false) {
2024
                        $parts[$i + 1] = rawurlencode($val);
2025
                    } else {
2026
                        unset($parts[$i]);
2027
                        unset($parts[$i + 1]);
2028
                    }
2029
                    $seen = true;
2030
                } else {
2031
                    // no break because we want to remove duplicate entries
2032
                    unset($parts[$i]);
2033
                    unset($parts[$i + 1]);
2034
                }
2035
            }
2036
        }
2037
        $cookieVal = implode('#', $parts);
2038
    } else if ($orig === false && $val !== false) {
2039
        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
2040
    }
2041
2042
    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
2043
    if(defined('DOKU_UNITTEST')) {
2044
        $_COOKIE['DOKU_PREFS'] = $cookieVal;
2045
    }else{
2046
        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
2047
    }
2048
}
2049
2050
/**
2051
 * Strips source mapping declarations from given text #601
2052
 *
2053
 * @param string &$text reference to the CSS or JavaScript code to clean
2054
 */
2055
function stripsourcemaps(&$text){
2056
    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2057
}
2058
2059
/**
2060
 * Returns the contents of a given SVG file for embedding
2061
 *
2062
 * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
2063
 * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
2064
 * files are embedded.
2065
 *
2066
 * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
2067
 *
2068
 * @param string $file full path to the SVG file
2069
 * @param int $maxsize maximum allowed size for the SVG to be embedded
2070
 * @return string|false the SVG content, false if the file couldn't be loaded
2071
 */
2072
function inlineSVG($file, $maxsize = 2048) {
2073
    $file = trim($file);
2074
    if($file === '') return false;
2075
    if(!file_exists($file)) return false;
2076
    if(filesize($file) > $maxsize) return false;
2077
    if(!is_readable($file)) return false;
2078
    $content = file_get_contents($file);
2079
    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
2080
    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
2081
    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
2082
    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
2083
    $content = trim($content);
2084
    if(substr($content, 0, 5) !== '<svg ') return false;
2085
    return $content;
2086
}
2087
2088
//Setup VIM: ex: et ts=2 :
2089