xref: /dokuwiki/inc/common.php (revision 0ea5ebb45da8a1df502d7537e959df1f153a1e3e)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Common DokuWiki functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
815fae107Sandi
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10f3f0262cSandi
11f3f0262cSandi/**
12b6912aeaSAndreas Gohr * These constants are used with the recents function
13b6912aeaSAndreas Gohr */
14b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_DELETED', 2);
15b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_MINORS', 4);
16b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_SUBSPACES', 8);
170b926329SKate Arzamastsevadefine('RECENTS_MEDIA_CHANGES', 16);
180b926329SKate Arzamastsevadefine('RECENTS_MEDIA_PAGES_MIXED', 32);
19b6912aeaSAndreas Gohr
20b6912aeaSAndreas Gohr/**
21d5197206Schris * Wrapper around htmlspecialchars()
22d5197206Schris *
23d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
24d5197206Schris * @see    htmlspecialchars()
25140cfbcdSGerrit Uitslag *
26140cfbcdSGerrit Uitslag * @param string $string the string being converted
27140cfbcdSGerrit Uitslag * @return string converted string
28d5197206Schris */
29d5197206Schrisfunction hsc($string) {
30d5197206Schris    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
31d5197206Schris}
32d5197206Schris
33d5197206Schris/**
345b571377SAndreas Gohr * Checks if the given input is blank
355b571377SAndreas Gohr *
365b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
375b571377SAndreas Gohr *
3867234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
3967234204SAndreas Gohr * with a NULL value without warning.
4067234204SAndreas Gohr *
4167234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
4267234204SAndreas Gohr *
4367234204SAndreas Gohr * (isset($foo) && !blank($foo))
4467234204SAndreas Gohr * (!isset($foo) || blank($foo))
4567234204SAndreas Gohr *
465b571377SAndreas Gohr * @param $in
475b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
485b571377SAndreas Gohr * @return bool
495b571377SAndreas Gohr */
505b571377SAndreas Gohrfunction blank(&$in, $trim = false) {
515b571377SAndreas Gohr    if(is_null($in)) return true;
525b571377SAndreas Gohr    if(is_array($in)) return empty($in);
535b571377SAndreas Gohr    if($in === "\0") return true;
545b571377SAndreas Gohr    if($trim && trim($in) === '') return true;
555b571377SAndreas Gohr    if(strlen($in) > 0) return false;
565b571377SAndreas Gohr    return empty($in);
575b571377SAndreas Gohr}
585b571377SAndreas Gohr
595b571377SAndreas Gohr/**
60d5197206Schris * print a newline terminated string
61d5197206Schris *
62d5197206Schris * You can give an indention as optional parameter
63d5197206Schris *
64d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
65140cfbcdSGerrit Uitslag *
66140cfbcdSGerrit Uitslag * @param string $string  line of text
67140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
68d5197206Schris */
6925ec097bSChris Smithfunction ptln($string, $indent = 0) {
7025ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
7102b0b681SAndreas Gohr}
7202b0b681SAndreas Gohr
7302b0b681SAndreas Gohr/**
7402b0b681SAndreas Gohr * strips control characters (<32) from the given string
7502b0b681SAndreas Gohr *
7602b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
77140cfbcdSGerrit Uitslag *
7842ea7f44SGerrit Uitslag * @param string $string being stripped
79140cfbcdSGerrit Uitslag * @return string
8002b0b681SAndreas Gohr */
8102b0b681SAndreas Gohrfunction stripctl($string) {
8202b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
83d5197206Schris}
84d5197206Schris
85d5197206Schris/**
86634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
87634d7150SAndreas Gohr *
88634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
89634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
90634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
9142ea7f44SGerrit Uitslag *
92634d7150SAndreas Gohr * @return  string
93634d7150SAndreas Gohr */
94634d7150SAndreas Gohrfunction getSecurityToken() {
95585bf44eSChristopher Smith    /** @var Input $INPUT */
96585bf44eSChristopher Smith    global $INPUT;
973680e2cdSAndreas Gohr
983680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
993680e2cdSAndreas Gohr    $session = session_id();
1003680e2cdSAndreas Gohr
1013680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1023680e2cdSAndreas Gohr    if(trim($user) == '' || trim($session) == '') return '';
1033680e2cdSAndreas Gohr    return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
104634d7150SAndreas Gohr}
105634d7150SAndreas Gohr
106634d7150SAndreas Gohr/**
107634d7150SAndreas Gohr * Check the secret CSRF token
108140cfbcdSGerrit Uitslag *
109140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
110140cfbcdSGerrit Uitslag * @return bool success if the token matched
111634d7150SAndreas Gohr */
112634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
113585bf44eSChristopher Smith    /** @var Input $INPUT */
1147d01a0eaSTom N Harris    global $INPUT;
115585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
116df97eaacSAndreas Gohr
1177d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
118634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
119634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
120634d7150SAndreas Gohr        return false;
121634d7150SAndreas Gohr    }
122634d7150SAndreas Gohr    return true;
123634d7150SAndreas Gohr}
124634d7150SAndreas Gohr
125634d7150SAndreas Gohr/**
126634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
127634d7150SAndreas Gohr *
128634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
129140cfbcdSGerrit Uitslag *
130140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
13142ea7f44SGerrit Uitslag * @return string html of hidden form field
132634d7150SAndreas Gohr */
133634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1342404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1353272d797SAndreas Gohr    if($print) echo $ret;
136634d7150SAndreas Gohr    return $ret;
137634d7150SAndreas Gohr}
138634d7150SAndreas Gohr
139634d7150SAndreas Gohr/**
1401015a57dSChristopher Smith * Determine basic information for a request of $id
14115fae107Sandi *
14215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1437e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
144140cfbcdSGerrit Uitslag *
145140cfbcdSGerrit Uitslag * @param string $id         pageid
146140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
147140cfbcdSGerrit Uitslag * @return array with info for a request of $id
148140cfbcdSGerrit Uitslag *
149f3f0262cSandi */
1501015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
151f3f0262cSandi    global $USERINFO;
152585bf44eSChristopher Smith    /* @var Input $INPUT */
153585bf44eSChristopher Smith    global $INPUT;
1546afe8dcaSchris
155c66972f2SAdrian Lang    // set info about manager/admin status.
15659bc3b48SGerrit Uitslag    $info = array();
157c66972f2SAdrian Lang    $info['isadmin']   = false;
158c66972f2SAdrian Lang    $info['ismanager'] = false;
159585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
160f3f0262cSandi        $info['userinfo']   = $USERINFO;
1611015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
162585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
16317ee7f66SAndreas Gohr
164f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
165f8cc712eSAndreas Gohr            $info['isadmin']   = true;
166f8cc712eSAndreas Gohr            $info['ismanager'] = true;
167f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
168f8cc712eSAndreas Gohr            $info['ismanager'] = true;
169f8cc712eSAndreas Gohr        }
170f8cc712eSAndreas Gohr
17117ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
17217ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
173585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
17417ee7f66SAndreas Gohr        }
175ee4c4a1bSAndreas Gohr
176f3f0262cSandi    } else {
1771015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
178ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
179f3f0262cSandi    }
180f3f0262cSandi
1811015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1821015a57dSChristopher Smith
1831015a57dSChristopher Smith    // mobile detection
1841015a57dSChristopher Smith    if ($htmlClient) {
1851015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1861015a57dSChristopher Smith    }
1871015a57dSChristopher Smith
1881015a57dSChristopher Smith    return $info;
1891015a57dSChristopher Smith }
1901015a57dSChristopher Smith
1911015a57dSChristopher Smith/**
1921015a57dSChristopher Smith * Return info about the current document as associative
1931015a57dSChristopher Smith * array.
1941015a57dSChristopher Smith *
1951015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
196140cfbcdSGerrit Uitslag *
197140cfbcdSGerrit Uitslag * @return array with info about current document
1981015a57dSChristopher Smith */
1991015a57dSChristopher Smithfunction pageinfo() {
2001015a57dSChristopher Smith    global $ID;
2011015a57dSChristopher Smith    global $REV;
2021015a57dSChristopher Smith    global $RANGE;
2031015a57dSChristopher Smith    global $lang;
204585bf44eSChristopher Smith    /* @var Input $INPUT */
205585bf44eSChristopher Smith    global $INPUT;
2061015a57dSChristopher Smith
2071015a57dSChristopher Smith    $info = basicinfo($ID);
2081015a57dSChristopher Smith
2091015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2101015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2111015a57dSChristopher Smith    $info['id']  = $ID;
2121015a57dSChristopher Smith    $info['rev'] = $REV;
2131015a57dSChristopher Smith
214585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
2157e87a794SChristopher Smith        $sub = new Subscription();
2167e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
2177e87a794SChristopher Smith    } else {
2187e87a794SChristopher Smith        $info['subscribed'] = false;
2197e87a794SChristopher Smith    }
2207e87a794SChristopher Smith
221f3f0262cSandi    $info['locked']     = checklock($ID);
222317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
22379e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
22401c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2252ca9d91cSBen Coburn    if($REV) {
2262ca9d91cSBen Coburn        //check if current revision was meant
22701c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
2282ca9d91cSBen Coburn            $REV = '';
2297b3a6803SAndreas Gohr        } elseif($RANGE) {
2307b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2317b3a6803SAndreas Gohr            $REV   = '';
2327b3a6803SAndreas Gohr            $RANGE = '';
2337b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2342ca9d91cSBen Coburn        } else {
2352ca9d91cSBen Coburn            //really use old revision
236317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
23779e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
238f3f0262cSandi        }
239f3f0262cSandi    }
240c112d578Sandi    $info['rev'] = $REV;
241f3f0262cSandi    if($info['exists']) {
242f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
243f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
244f3f0262cSandi    } else {
245f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
246f3f0262cSandi    }
24750e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
248f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
249f3f0262cSandi
25071726d78SBen Coburn    //load page meta data
25171726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
25271726d78SBen Coburn
253652610a2Sandi    //who's the editor
254047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
255652610a2Sandi    if($REV) {
256f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
257652610a2Sandi    } else {
2580e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
259aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
260aa27cf05SAndreas Gohr        } else {
261f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
262cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
263cd00a034SBen Coburn            if($revinfo !== false) {
264cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
265cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
266cd00a034SBen Coburn            }
267cd00a034SBen Coburn        }
268cd00a034SBen Coburn    }
269cd00a034SBen Coburn    //and check for an external edit
270cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
271cd00a034SBen Coburn        // cached changelog line no longer valid
272cd00a034SBen Coburn        $revinfo                     = false;
273cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
274cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
275652610a2Sandi    }
276bb4866bdSchris
277652610a2Sandi    $info['ip']   = $revinfo['ip'];
278652610a2Sandi    $info['user'] = $revinfo['user'];
279652610a2Sandi    $info['sum']  = $revinfo['sum'];
28071726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
281ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
28259f257aeSchris
28388f522e9Sandi    if($revinfo['user']) {
28488f522e9Sandi        $info['editor'] = $revinfo['user'];
28588f522e9Sandi    } else {
28688f522e9Sandi        $info['editor'] = $revinfo['ip'];
28788f522e9Sandi    }
288652610a2Sandi
289ee4c4a1bSAndreas Gohr    // draft
290ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
29179e79377SAndreas Gohr    if(file_exists($draft)) {
292ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
293ee4c4a1bSAndreas Gohr            // remove stale draft
294ee4c4a1bSAndreas Gohr            @unlink($draft);
295ee4c4a1bSAndreas Gohr        } else {
296ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
297ee4c4a1bSAndreas Gohr        }
298ee4c4a1bSAndreas Gohr    }
299ee4c4a1bSAndreas Gohr
3001015a57dSChristopher Smith    return $info;
3011015a57dSChristopher Smith}
3021015a57dSChristopher Smith
3031015a57dSChristopher Smith/**
3041015a57dSChristopher Smith * Return information about the current media item as an associative array.
305140cfbcdSGerrit Uitslag *
306140cfbcdSGerrit Uitslag * @return array with info about current media item
3071015a57dSChristopher Smith */
3081015a57dSChristopher Smithfunction mediainfo(){
3091015a57dSChristopher Smith    global $NS;
3101015a57dSChristopher Smith    global $IMG;
3111015a57dSChristopher Smith
3121015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3131015a57dSChristopher Smith    $info['image'] = $IMG;
3141c548ebeSAndreas Gohr
315f3f0262cSandi    return $info;
316f3f0262cSandi}
317f3f0262cSandi
318f3f0262cSandi/**
3192684e50aSAndreas Gohr * Build an string of URL parameters
3202684e50aSAndreas Gohr *
3212684e50aSAndreas Gohr * @author Andreas Gohr
322140cfbcdSGerrit Uitslag *
323140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
324140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
325140cfbcdSGerrit Uitslag * @return string query string
3262684e50aSAndreas Gohr */
327b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3282684e50aSAndreas Gohr    $url = '';
3292684e50aSAndreas Gohr    $amp = false;
3302684e50aSAndreas Gohr    foreach($params as $key => $val) {
331b174aeaeSchris        if($amp) $url .= $sep;
3322684e50aSAndreas Gohr
33385e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3343a50618cSgweissbach        $url .= rawurlencode((string) $val);
3352684e50aSAndreas Gohr        $amp = true;
3362684e50aSAndreas Gohr    }
3372684e50aSAndreas Gohr    return $url;
3382684e50aSAndreas Gohr}
3392684e50aSAndreas Gohr
3402684e50aSAndreas Gohr/**
3412684e50aSAndreas Gohr * Build an string of html tag attributes
3422684e50aSAndreas Gohr *
3437bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3447bff22c0SAndreas Gohr *
3452684e50aSAndreas Gohr * @author Andreas Gohr
346140cfbcdSGerrit Uitslag *
347140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
348140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
349140cfbcdSGerrit Uitslag * @return string
3502684e50aSAndreas Gohr */
3514b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3522684e50aSAndreas Gohr    $url   = '';
3539063ec14SAdrian Lang    $white = false;
3542684e50aSAndreas Gohr    foreach($params as $key => $val) {
3557bff22c0SAndreas Gohr        if($key{0} == '_') continue;
356b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3579063ec14SAdrian Lang        if($white) $url .= ' ';
3587bff22c0SAndreas Gohr
3592684e50aSAndreas Gohr        $url .= $key.'="';
3602684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3612684e50aSAndreas Gohr        $url .= '"';
3629063ec14SAdrian Lang        $white = true;
3632684e50aSAndreas Gohr    }
3642684e50aSAndreas Gohr    return $url;
3652684e50aSAndreas Gohr}
3662684e50aSAndreas Gohr
3672684e50aSAndreas Gohr/**
36815fae107Sandi * This builds the breadcrumb trail and returns it as array
36915fae107Sandi *
37015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
371140cfbcdSGerrit Uitslag *
372e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
373f3f0262cSandi */
374f3f0262cSandifunction breadcrumbs() {
3758746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3768746e727Sandi    static $crumbs = null;
3778746e727Sandi    if($crumbs != null) return $crumbs;
3788746e727Sandi
379f3f0262cSandi    global $ID;
380f3f0262cSandi    global $ACT;
381f3f0262cSandi    global $conf;
382*0ea5ebb4SB_S666    global $INFO;
383f3f0262cSandi
384f3f0262cSandi    //first visit?
385c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
386f3f0262cSandi    //we only save on show and existing wiki documents
387a77f5846Sjan    $file = wikiFN($ID);
388*0ea5ebb4SB_S666    if($ACT != 'show' || $INFO['perm'] < AUTH_READ || !file_exists($file)) {
389e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
390f3f0262cSandi        return $crumbs;
391f3f0262cSandi    }
392a77f5846Sjan
393a77f5846Sjan    // page names
3941a84a0f3SAnika Henke    $name = noNSorNS($ID);
395fe9ec250SChris Smith    if(useHeading('navigation')) {
396a77f5846Sjan        // get page title
39767c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
398a77f5846Sjan        if($title) {
399a77f5846Sjan            $name = $title;
400a77f5846Sjan        }
401a77f5846Sjan    }
402a77f5846Sjan
403f3f0262cSandi    //remove ID from array
404a77f5846Sjan    if(isset($crumbs[$ID])) {
405a77f5846Sjan        unset($crumbs[$ID]);
406f3f0262cSandi    }
407f3f0262cSandi
408f3f0262cSandi    //add to array
409a77f5846Sjan    $crumbs[$ID] = $name;
410f3f0262cSandi    //reduce size
411f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
412f3f0262cSandi        array_shift($crumbs);
413f3f0262cSandi    }
414f3f0262cSandi    //save to session
415e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
416f3f0262cSandi    return $crumbs;
417f3f0262cSandi}
418f3f0262cSandi
419f3f0262cSandi/**
42015fae107Sandi * Filter for page IDs
42115fae107Sandi *
422f3f0262cSandi * This is run on a ID before it is outputted somewhere
423f3f0262cSandi * currently used to replace the colon with something else
424907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
425907f24f7SAndreas Gohr *
426907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
427907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
428907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
42915fae107Sandi *
43049c713a3Sandi * Urlencoding is ommitted when the second parameter is false
43149c713a3Sandi *
43215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
433140cfbcdSGerrit Uitslag *
434140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
435140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
436140cfbcdSGerrit Uitslag * @return string
437f3f0262cSandi */
43849c713a3Sandifunction idfilter($id, $ue = true) {
439f3f0262cSandi    global $conf;
440585bf44eSChristopher Smith    /* @var Input $INPUT */
441585bf44eSChristopher Smith    global $INPUT;
442585bf44eSChristopher Smith
443f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
444f3f0262cSandi        $id = strtr($id, ':', '/');
445f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
44658bedc8aSborekb        $conf['userewrite'] &&
447585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4483272d797SAndreas Gohr    ) {
449f3f0262cSandi        $id = strtr($id, ':', ';');
450f3f0262cSandi    }
45149c713a3Sandi    if($ue) {
452b6c6979fSAndreas Gohr        $id = rawurlencode($id);
453f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
454edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
455f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
45649c713a3Sandi    }
457f3f0262cSandi    return $id;
458f3f0262cSandi}
459f3f0262cSandi
460f3f0262cSandi/**
461ed7b5f09Sandi * This builds a link to a wikipage
46215fae107Sandi *
4634bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4646c7843b5Sandi *
46515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4664bc480e5SAndreas Gohr *
4674bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4684bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4694bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4704bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4714bc480e5SAndreas Gohr * @return string
472f3f0262cSandi */
47316f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
474f3f0262cSandi    global $conf;
47516f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
4764bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
4777b62b42dSlisps        if(isset($urlParameters['at']) && $conf['date_at_format']) $urlParameters['at'] = date($conf['date_at_format'],$urlParameters['at']);
47816f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4796de3759aSAndreas Gohr    } else {
48016f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4816de3759aSAndreas Gohr    }
48216f15a81SDominik Eckelmann    if($id === '') {
48316f15a81SDominik Eckelmann        $id = $conf['start'];
48416f15a81SDominik Eckelmann    }
485f3f0262cSandi    $id = idfilter($id);
48616f15a81SDominik Eckelmann    if($absolute) {
487ed7b5f09Sandi        $xlink = DOKU_URL;
488ed7b5f09Sandi    } else {
489ed7b5f09Sandi        $xlink = DOKU_BASE;
490ed7b5f09Sandi    }
491f3f0262cSandi
4926c7843b5Sandi    if($conf['userewrite'] == 2) {
4936c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
49416f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4956c7843b5Sandi    } elseif($conf['userewrite']) {
496f3f0262cSandi        $xlink .= $id;
49716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
498bce3726dSAndreas Gohr    } elseif($id) {
4996c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
50016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
501bce3726dSAndreas Gohr    } else {
502bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
50316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
504f3f0262cSandi    }
505f3f0262cSandi
506f3f0262cSandi    return $xlink;
507f3f0262cSandi}
508f3f0262cSandi
509f3f0262cSandi/**
510f5c2808fSBen Coburn * This builds a link to an alternate page format
511f5c2808fSBen Coburn *
512f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
513f5c2808fSBen Coburn *
514f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5154bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5164bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5174bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5184bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5194bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5204bc480e5SAndreas Gohr * @return string
521f5c2808fSBen Coburn */
5224bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
523f5c2808fSBen Coburn    global $conf;
5244bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5254bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
526f5c2808fSBen Coburn    } else {
5274bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
528f5c2808fSBen Coburn    }
529f5c2808fSBen Coburn
530f5c2808fSBen Coburn    $format = rawurlencode($format);
531f5c2808fSBen Coburn    $id     = idfilter($id);
532f5c2808fSBen Coburn    if($abs) {
533f5c2808fSBen Coburn        $xlink = DOKU_URL;
534f5c2808fSBen Coburn    } else {
535f5c2808fSBen Coburn        $xlink = DOKU_BASE;
536f5c2808fSBen Coburn    }
537f5c2808fSBen Coburn
538f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
539f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5404bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
541f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
542f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5434bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
544f5c2808fSBen Coburn    } else {
545f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5464bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
547f5c2808fSBen Coburn    }
548f5c2808fSBen Coburn
549f5c2808fSBen Coburn    return $xlink;
550f5c2808fSBen Coburn}
551f5c2808fSBen Coburn
552f5c2808fSBen Coburn/**
5536de3759aSAndreas Gohr * Build a link to a media file
5546de3759aSAndreas Gohr *
5556de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5568c08db0aSAndreas Gohr *
5578c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5588c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5598c08db0aSAndreas Gohr *
5603272d797SAndreas Gohr * @param string  $id     the media file id or URL
5613272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5623272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5633272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5643272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5653272d797SAndreas Gohr * @return string
5666de3759aSAndreas Gohr */
56755b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5686de3759aSAndreas Gohr    global $conf;
569b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
570826d2766SKlap-in    if(!$isexternalimage) {
571826d2766SKlap-in        $id = cleanID($id);
572826d2766SKlap-in    }
573826d2766SKlap-in
5746de3759aSAndreas Gohr    if(is_array($more)) {
5750f4e0092SChristopher Smith        // add token for resized images
576443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5770f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5780f4e0092SChristopher Smith        }
5798c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5808c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
581443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
582443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5838c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
58478b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
585b174aeaeSchris        $more = buildURLparams($more, $sep);
5866de3759aSAndreas Gohr    } else {
5875e7db1e2SChristopher Smith        $matches = array();
588cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
5895e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
5905e7db1e2SChristopher Smith            foreach ($matches as $match){
5915e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
5925e7db1e2SChristopher Smith            }
593cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
594cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
5955e7db1e2SChristopher Smith        }
5968c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
5978c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
598b174aeaeSchris        $more = str_replace(',', $sep, $more);
5996de3759aSAndreas Gohr    }
6006de3759aSAndreas Gohr
60155b2b31bSAndreas Gohr    if($abs) {
60255b2b31bSAndreas Gohr        $xlink = DOKU_URL;
60355b2b31bSAndreas Gohr    } else {
6046de3759aSAndreas Gohr        $xlink = DOKU_BASE;
60555b2b31bSAndreas Gohr    }
6066de3759aSAndreas Gohr
6076de3759aSAndreas Gohr    // external URLs are always direct without rewriting
608826d2766SKlap-in    if($isexternalimage) {
6096de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
610cc036f74SKlap-in        $xlink .= '?'.$more;
611b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6126de3759aSAndreas Gohr        return $xlink;
6136de3759aSAndreas Gohr    }
6146de3759aSAndreas Gohr
6156de3759aSAndreas Gohr    $id = idfilter($id);
6166de3759aSAndreas Gohr
6176de3759aSAndreas Gohr    // decide on scriptname
6186de3759aSAndreas Gohr    if($direct) {
6196de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6206de3759aSAndreas Gohr            $script = '_media';
6216de3759aSAndreas Gohr        } else {
6226de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6236de3759aSAndreas Gohr        }
6246de3759aSAndreas Gohr    } else {
6256de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6266de3759aSAndreas Gohr            $script = '_detail';
6276de3759aSAndreas Gohr        } else {
6286de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
6296de3759aSAndreas Gohr        }
6306de3759aSAndreas Gohr    }
6316de3759aSAndreas Gohr
6326de3759aSAndreas Gohr    // build URL based on rewrite mode
6336de3759aSAndreas Gohr    if($conf['userewrite']) {
6346de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6356de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6366de3759aSAndreas Gohr    } else {
6376de3759aSAndreas Gohr        if($more) {
638a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
639b174aeaeSchris            $xlink .= $sep.'media='.$id;
6406de3759aSAndreas Gohr        } else {
641a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6426de3759aSAndreas Gohr        }
6436de3759aSAndreas Gohr    }
6446de3759aSAndreas Gohr
6456de3759aSAndreas Gohr    return $xlink;
6466de3759aSAndreas Gohr}
6476de3759aSAndreas Gohr
6486de3759aSAndreas Gohr/**
64925ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
65015fae107Sandi *
65125ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
65225ca5b17SAndreas Gohr *
65315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
654140cfbcdSGerrit Uitslag *
655140cfbcdSGerrit Uitslag * @return string
656f3f0262cSandi */
65725ca5b17SAndreas Gohrfunction script() {
658ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
659f3f0262cSandi}
660f3f0262cSandi
661f3f0262cSandi/**
66215fae107Sandi * Spamcheck against wordlist
66315fae107Sandi *
664f3f0262cSandi * Checks the wikitext against a list of blocked expressions
665f3f0262cSandi * returns true if the text contains any bad words
66615fae107Sandi *
667e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
668e403cc58SMichael Klier *
669e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
670e403cc58SMichael Klier *  and gain information about the user who was blocked.
671e403cc58SMichael Klier *
672e403cc58SMichael Klier *  Event data:
673e403cc58SMichael Klier *    data['matches']  - array of matches
674e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
675e403cc58SMichael Klier *      [ip]           - ip address
676e403cc58SMichael Klier *      [user]         - username (if logged in)
677e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
678e403cc58SMichael Klier *      [name]         - real name (if logged in)
679e403cc58SMichael Klier *
68015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6816dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
682140cfbcdSGerrit Uitslag *
6836dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6846dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
685f3f0262cSandi */
6866dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
687f3f0262cSandi    global $TEXT;
6886dffa0e0SAndreas Gohr    global $PRE;
6896dffa0e0SAndreas Gohr    global $SUF;
690e0086ca2SAndreas Gohr    global $SUM;
691f3f0262cSandi    global $conf;
692e403cc58SMichael Klier    global $INFO;
693585bf44eSChristopher Smith    /* @var Input $INPUT */
694585bf44eSChristopher Smith    global $INPUT;
695f3f0262cSandi
696f3f0262cSandi    if(!$conf['usewordblock']) return false;
697f3f0262cSandi
698e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
6996dffa0e0SAndreas Gohr
700041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
7016dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
702041d1964SAndreas Gohr
703b9ac8716Schris    $wordblocks = getWordblocks();
7043e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
7053e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
7063e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
7073e2965d7Sandi        // backreferences are used - the maximum is 99
7083e2965d7Sandi        // this is very bad performancewise and may even be too high still
7093e2965d7Sandi        $chunksize = 40;
7103e2965d7Sandi    } else {
711a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
7123e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
713a51d08efSAndreas Gohr        $chunksize = 200;
7143e2965d7Sandi    }
715b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
716f3f0262cSandi        $re = array();
71749eb6e38SAndreas Gohr        // build regexp from blocks
718f3f0262cSandi        foreach($blocks as $block) {
719f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
720f3f0262cSandi            $block = trim($block);
721f3f0262cSandi            if(empty($block)) continue;
722f3f0262cSandi            $re[] = $block;
723f3f0262cSandi        }
724e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
725e403cc58SMichael Klier            // prepare event data
72659bc3b48SGerrit Uitslag            $data = array();
727e403cc58SMichael Klier            $data['matches']        = $matches;
728585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
729585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
730585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
731e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
732e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
733e403cc58SMichael Klier            }
734bad6fc0dSAndreas Gohr            $callback = function () {
735bad6fc0dSAndreas Gohr                return true;
736bad6fc0dSAndreas Gohr            };
737e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
738b9ac8716Schris        }
739703f6fdeSandi    }
740f3f0262cSandi    return false;
741f3f0262cSandi}
742f3f0262cSandi
743f3f0262cSandi/**
74415fae107Sandi * Return the IP of the client
74515fae107Sandi *
7466d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
74715fae107Sandi *
7486d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7496d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7506d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7516d8affe6SAndreas Gohr * headers
7526d8affe6SAndreas Gohr *
75315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
754140cfbcdSGerrit Uitslag *
7553272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7563272d797SAndreas Gohr * @return string
757f3f0262cSandi */
7586d8affe6SAndreas Gohrfunction clientIP($single = false) {
759585bf44eSChristopher Smith    /* @var Input $INPUT */
760585bf44eSChristopher Smith    global $INPUT;
761585bf44eSChristopher Smith
7626d8affe6SAndreas Gohr    $ip   = array();
763585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
764585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
765585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
766585bf44eSChristopher Smith    }
767585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
768585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
769585bf44eSChristopher Smith    }
7706d8affe6SAndreas Gohr
771dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
772dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
773dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
774dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
775dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
776dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
777dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
778dc14c6d1SGuy Brand    $IPv6Address =
779dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
780dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
781dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
782dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
783dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
784dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
785dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
786dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
787dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
788dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
789dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
790dc14c6d1SGuy Brand
7916d8affe6SAndreas Gohr    // remove any non-IP stuff
7926d8affe6SAndreas Gohr    $cnt   = count($ip);
7934ff28443Schris    $match = array();
7946d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
795dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
7964ff28443Schris            $ip[$i] = $match[0];
7974ff28443Schris        } else {
7984ff28443Schris            $ip[$i] = '';
7994ff28443Schris        }
8006d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
801f3f0262cSandi    }
8026d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
8036d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8046d8affe6SAndreas Gohr
8056d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
8066d8affe6SAndreas Gohr
8076d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
8086d8affe6SAndreas Gohr    $ip = array_reverse($ip);
8096d8affe6SAndreas Gohr    foreach($ip as $i) {
8102343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
8116d8affe6SAndreas Gohr            continue;
8126d8affe6SAndreas Gohr        } else {
8136d8affe6SAndreas Gohr            return $i;
8146d8affe6SAndreas Gohr        }
8156d8affe6SAndreas Gohr    }
8166d8affe6SAndreas Gohr    // still here? just use the first (last) address
8176d8affe6SAndreas Gohr    return $ip[0];
818f3f0262cSandi}
819f3f0262cSandi
820f3f0262cSandi/**
8211c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8221c548ebeSAndreas Gohr *
8231c548ebeSAndreas Gohr * Adapted from the example code at url below
8241c548ebeSAndreas Gohr *
8251c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
826140cfbcdSGerrit Uitslag *
827140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8281c548ebeSAndreas Gohr */
8291c548ebeSAndreas Gohrfunction clientismobile() {
830585bf44eSChristopher Smith    /* @var Input $INPUT */
831585bf44eSChristopher Smith    global $INPUT;
8321c548ebeSAndreas Gohr
833585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8341c548ebeSAndreas Gohr
835585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8361c548ebeSAndreas Gohr
837585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8381c548ebeSAndreas Gohr
8391c548ebeSAndreas Gohr    $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';
8401c548ebeSAndreas Gohr
841585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8421c548ebeSAndreas Gohr
8431c548ebeSAndreas Gohr    return false;
8441c548ebeSAndreas Gohr}
8451c548ebeSAndreas Gohr
8461c548ebeSAndreas Gohr/**
8476efc45a2SDmitry Katsubo * check if a given link is interwiki link
8486efc45a2SDmitry Katsubo *
8496efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8506efc45a2SDmitry Katsubo * @return bool
8516efc45a2SDmitry Katsubo */
8526efc45a2SDmitry Katsubofunction link_isinterwiki($link){
8536efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
8546efc45a2SDmitry Katsubo    return false;
8556efc45a2SDmitry Katsubo}
8566efc45a2SDmitry Katsubo
8576efc45a2SDmitry Katsubo/**
85863211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
85963211f61SGlen Harris *
86022ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
86122ef1e32SAndreas Gohr *
86263211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
863140cfbcdSGerrit Uitslag *
8643272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8653272d797SAndreas Gohr * @return string a comma separated list of hostnames
86663211f61SGlen Harris */
86763211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
86822ef1e32SAndreas Gohr    global $conf;
86922ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
87022ef1e32SAndreas Gohr
87163211f61SGlen Harris    $hosts = array();
87263211f61SGlen Harris    $ips   = explode(',', $ips);
873551a720fSMichael Klier
874551a720fSMichael Klier    if(is_array($ips)) {
8753886270dSAndreas Gohr        foreach($ips as $ip) {
876551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
87763211f61SGlen Harris        }
878551a720fSMichael Klier        return join(',', $hosts);
879551a720fSMichael Klier    } else {
880551a720fSMichael Klier        return gethostbyaddr(trim($ips));
881551a720fSMichael Klier    }
88263211f61SGlen Harris}
88363211f61SGlen Harris
88463211f61SGlen Harris/**
88515fae107Sandi * Checks if a given page is currently locked.
88615fae107Sandi *
887f3f0262cSandi * removes stale lockfiles
88815fae107Sandi *
88915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
890140cfbcdSGerrit Uitslag *
891140cfbcdSGerrit Uitslag * @param string $id page id
892140cfbcdSGerrit Uitslag * @return bool page is locked?
893f3f0262cSandi */
894f3f0262cSandifunction checklock($id) {
895f3f0262cSandi    global $conf;
896585bf44eSChristopher Smith    /* @var Input $INPUT */
897585bf44eSChristopher Smith    global $INPUT;
898585bf44eSChristopher Smith
899c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
900f3f0262cSandi
901f3f0262cSandi    //no lockfile
90279e79377SAndreas Gohr    if(!file_exists($lock)) return false;
903f3f0262cSandi
904f3f0262cSandi    //lockfile expired
905f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
906d8186216SBen Coburn        @unlink($lock);
907f3f0262cSandi        return false;
908f3f0262cSandi    }
909f3f0262cSandi
910f3f0262cSandi    //my own lock
9116d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
9120712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
913f3f0262cSandi        return false;
914f3f0262cSandi    }
915f3f0262cSandi
916f3f0262cSandi    return $ip;
917f3f0262cSandi}
918f3f0262cSandi
919f3f0262cSandi/**
92015fae107Sandi * Lock a page for editing
92115fae107Sandi *
92215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
923140cfbcdSGerrit Uitslag *
924140cfbcdSGerrit Uitslag * @param string $id page id to lock
925f3f0262cSandi */
926f3f0262cSandifunction lock($id) {
927544ed901SDaniel Calviño Sánchez    global $conf;
928585bf44eSChristopher Smith    /* @var Input $INPUT */
929585bf44eSChristopher Smith    global $INPUT;
930544ed901SDaniel Calviño Sánchez
931544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
932544ed901SDaniel Calviño Sánchez        return;
933544ed901SDaniel Calviño Sánchez    }
934544ed901SDaniel Calviño Sánchez
935c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
936585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
937585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
938f3f0262cSandi    } else {
93985fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
940f3f0262cSandi    }
941f3f0262cSandi}
942f3f0262cSandi
943f3f0262cSandi/**
94415fae107Sandi * Unlock a page if it was locked by the user
945f3f0262cSandi *
94615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
947140cfbcdSGerrit Uitslag *
9483272d797SAndreas Gohr * @param string $id page id to unlock
94915fae107Sandi * @return bool true if a lock was removed
950f3f0262cSandi */
951f3f0262cSandifunction unlock($id) {
952585bf44eSChristopher Smith    /* @var Input $INPUT */
953585bf44eSChristopher Smith    global $INPUT;
954585bf44eSChristopher Smith
955c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
95679e79377SAndreas Gohr    if(file_exists($lock)) {
9576d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
958585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
959f3f0262cSandi            @unlink($lock);
960f3f0262cSandi            return true;
961f3f0262cSandi        }
962f3f0262cSandi    }
963f3f0262cSandi    return false;
964f3f0262cSandi}
965f3f0262cSandi
966f3f0262cSandi/**
967f3f0262cSandi * convert line ending to unix format
968f3f0262cSandi *
9696db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9706db7468bSAndreas Gohr *
97115fae107Sandi * @see    formText() for 2crlf conversion
97215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
973140cfbcdSGerrit Uitslag *
974140cfbcdSGerrit Uitslag * @param string $text
975140cfbcdSGerrit Uitslag * @return string
976f3f0262cSandi */
977f3f0262cSandifunction cleanText($text) {
978f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9796db7468bSAndreas Gohr
9806db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9816db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9826db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9836db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
9846db7468bSAndreas Gohr
985f3f0262cSandi    return $text;
986f3f0262cSandi}
987f3f0262cSandi
988f3f0262cSandi/**
989f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
990f3f0262cSandi * It also converts line endings to Windows format which is
991f3f0262cSandi * pseudo standard for webforms.
992f3f0262cSandi *
99315fae107Sandi * @see    cleanText() for 2unix conversion
99415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
995140cfbcdSGerrit Uitslag *
996140cfbcdSGerrit Uitslag * @param string $text
997140cfbcdSGerrit Uitslag * @return string
998f3f0262cSandi */
999f3f0262cSandifunction formText($text) {
10005b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
1001f3f0262cSandi    return htmlspecialchars($text);
1002f3f0262cSandi}
1003f3f0262cSandi
1004f3f0262cSandi/**
100515fae107Sandi * Returns the specified local text in raw format
100615fae107Sandi *
100715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1008140cfbcdSGerrit Uitslag *
1009140cfbcdSGerrit Uitslag * @param string $id   page id
1010140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1011140cfbcdSGerrit Uitslag * @return string
1012f3f0262cSandi */
10132adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
10142adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1015f3f0262cSandi}
1016f3f0262cSandi
1017f3f0262cSandi/**
1018f3f0262cSandi * Returns the raw WikiText
101915fae107Sandi *
102015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1021140cfbcdSGerrit Uitslag *
1022140cfbcdSGerrit Uitslag * @param string $id   page id
1023e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1024140cfbcdSGerrit Uitslag * @return string
1025f3f0262cSandi */
1026f3f0262cSandifunction rawWiki($id, $rev = '') {
1027cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1028f3f0262cSandi}
1029f3f0262cSandi
1030f3f0262cSandi/**
10317146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10327146cee2SAndreas Gohr *
10337b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10347146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1035140cfbcdSGerrit Uitslag *
1036140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1037140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10387146cee2SAndreas Gohr */
1039fe17917eSAdrian Langfunction pageTemplate($id) {
1040a15ce62dSEsther Brunner    global $conf;
1041e29549feSAndreas Gohr
1042fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1043e29549feSAndreas Gohr
10447b84afa2SAndreas Gohr    // prepare initial event data
10457b84afa2SAndreas Gohr    $data = array(
10467b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10477b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10487b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10497b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10507b84afa2SAndreas Gohr    );
10517b84afa2SAndreas Gohr
10527b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10537b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10547b84afa2SAndreas Gohr        // the before event might have loaded the content already
10557b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10567b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10577b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1058fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
105979e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10607b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1061e29549feSAndreas Gohr                } else {
1062e29549feSAndreas Gohr                    // search upper namespaces for templates
1063e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1064e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
106579e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10667b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1067e29549feSAndreas Gohr                            break;
1068e29549feSAndreas Gohr                        }
1069e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1070e29549feSAndreas Gohr                    }
1071e29549feSAndreas Gohr                }
10727b84afa2SAndreas Gohr            }
10737b84afa2SAndreas Gohr            // load the content
10743d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10757b84afa2SAndreas Gohr        }
1076a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10777b84afa2SAndreas Gohr    }
10787b84afa2SAndreas Gohr    $evt->advise_after();
10797b84afa2SAndreas Gohr    unset($evt);
10807b84afa2SAndreas Gohr
1081fe17917eSAdrian Lang    return $data['tpl'];
10822b1223ecSAdrian Lang}
10832b1223ecSAdrian Lang
10842b1223ecSAdrian Lang/**
10852b1223ecSAdrian Lang * Performs common page template replacements
10867b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10872b1223ecSAdrian Lang *
10882b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1089140cfbcdSGerrit Uitslag *
1090140cfbcdSGerrit Uitslag * @param array $data array with event data
1091140cfbcdSGerrit Uitslag * @return string
10922b1223ecSAdrian Lang */
1093d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
10943272d797SAndreas Gohr    /**
10953272d797SAndreas Gohr     * @var string $id        the id of the page to be created
10963272d797SAndreas Gohr     * @var string $tpl       the text used as template
10973272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
10983272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
10993272d797SAndreas Gohr     */
1100fe17917eSAdrian Lang    extract($data);
1101fe17917eSAdrian Lang
1102b856f7dfSAdrian Lang    global $USERINFO;
1103bce53b1fSAdrian Lang    global $conf;
1104585bf44eSChristopher Smith    /* @var Input $INPUT */
1105585bf44eSChristopher Smith    global $INPUT;
1106e29549feSAndreas Gohr
1107e29549feSAndreas Gohr    // replace placeholders
110826ece5a7SAndreas Gohr    $file = noNS($id);
110937c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
111026ece5a7SAndreas Gohr
11113272d797SAndreas Gohr    $tpl = str_replace(
11123272d797SAndreas Gohr        array(
111326ece5a7SAndreas Gohr             '@ID@',
111426ece5a7SAndreas Gohr             '@NS@',
111526ece5a7SAndreas Gohr             '@FILE@',
111626ece5a7SAndreas Gohr             '@!FILE@',
111726ece5a7SAndreas Gohr             '@!FILE!@',
111826ece5a7SAndreas Gohr             '@PAGE@',
111926ece5a7SAndreas Gohr             '@!PAGE@',
112026ece5a7SAndreas Gohr             '@!!PAGE@',
112126ece5a7SAndreas Gohr             '@!PAGE!@',
112226ece5a7SAndreas Gohr             '@USER@',
112326ece5a7SAndreas Gohr             '@NAME@',
112426ece5a7SAndreas Gohr             '@MAIL@',
112526ece5a7SAndreas Gohr             '@DATE@',
112626ece5a7SAndreas Gohr        ),
112726ece5a7SAndreas Gohr        array(
112826ece5a7SAndreas Gohr             $id,
112926ece5a7SAndreas Gohr             getNS($id),
113026ece5a7SAndreas Gohr             $file,
113126ece5a7SAndreas Gohr             utf8_ucfirst($file),
113226ece5a7SAndreas Gohr             utf8_strtoupper($file),
113326ece5a7SAndreas Gohr             $page,
113426ece5a7SAndreas Gohr             utf8_ucfirst($page),
113526ece5a7SAndreas Gohr             utf8_ucwords($page),
113626ece5a7SAndreas Gohr             utf8_strtoupper($page),
1137585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1138b856f7dfSAdrian Lang             $USERINFO['name'],
1139b856f7dfSAdrian Lang             $USERINFO['mail'],
114026ece5a7SAndreas Gohr             $conf['dformat'],
11413272d797SAndreas Gohr        ), $tpl
11423272d797SAndreas Gohr    );
114326ece5a7SAndreas Gohr
11447d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1145bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1146bad6fc0dSAndreas Gohr        '/%./',
1147bad6fc0dSAndreas Gohr        function ($m) {
1148bad6fc0dSAndreas Gohr            return strftime($m[0]);
1149bad6fc0dSAndreas Gohr        },
1150bad6fc0dSAndreas Gohr        $tpl
1151bad6fc0dSAndreas Gohr    );
1152d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1153a15ce62dSEsther Brunner    return $tpl;
11547146cee2SAndreas Gohr}
11557146cee2SAndreas Gohr
11567146cee2SAndreas Gohr/**
115715fae107Sandi * Returns the raw Wiki Text in three slices.
115815fae107Sandi *
115915fae107Sandi * The range parameter needs to have the form "from-to"
116015cfe303Sandi * and gives the range of the section in bytes - no
116115cfe303Sandi * UTF-8 awareness is needed.
1162f3f0262cSandi * The returned order is prefix, section and suffix.
116315fae107Sandi *
116415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1165140cfbcdSGerrit Uitslag *
1166140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1167140cfbcdSGerrit Uitslag * @param string $id    page id
1168140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
116942ea7f44SGerrit Uitslag * @return string[] with three slices
1170f3f0262cSandi */
1171f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1172cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1173f3f0262cSandi
117480fcb268SAdrian Lang    // Parse range
117580fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
117680fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
117780fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
117880fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
117980fcb268SAdrian Lang
118059bc3b48SGerrit Uitslag    $slices = array();
118180fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
118280fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
118315cfe303Sandi    $slices[2] = substr($text, $to);
1184f3f0262cSandi    return $slices;
1185f3f0262cSandi}
1186f3f0262cSandi
1187f3f0262cSandi/**
118815fae107Sandi * Joins wiki text slices
118915fae107Sandi *
119080fcb268SAdrian Lang * function to join the text slices.
1191f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1192f3f0262cSandi * lines between sections if needed (used on saving).
119315fae107Sandi *
119415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1195140cfbcdSGerrit Uitslag *
1196140cfbcdSGerrit Uitslag * @param string $pre   prefix
1197140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1198140cfbcdSGerrit Uitslag * @param string $suf   suffix
1199140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1200140cfbcdSGerrit Uitslag * @return string
1201f3f0262cSandi */
1202f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1203f3f0262cSandi    if($pretty) {
120480fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
12053272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
12063272d797SAndreas Gohr        ) {
120780fcb268SAdrian Lang            $pre .= "\n";
120880fcb268SAdrian Lang        }
120980fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
12103272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
12113272d797SAndreas Gohr        ) {
121280fcb268SAdrian Lang            $text .= "\n";
121380fcb268SAdrian Lang        }
1214f3f0262cSandi    }
1215f3f0262cSandi
1216f3f0262cSandi    return $pre.$text.$suf;
1217f3f0262cSandi}
1218f3f0262cSandi
1219f3f0262cSandi/**
1220b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1221b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1222b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1223b24d9195SAndreas Gohr *
1224b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1225b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1226b24d9195SAndreas Gohr *
1227b24d9195SAndreas Gohr * @param string $id the page ID
1228b24d9195SAndreas Gohr */
1229b24d9195SAndreas Gohrfunction detectExternalEdit($id) {
1230b24d9195SAndreas Gohr    global $lang;
1231b24d9195SAndreas Gohr
12328c7319beSGerrit Uitslag    $fileLastMod = wikiFN($id);
12338c7319beSGerrit Uitslag    $lastMod     = @filemtime($fileLastMod); // from page
1234b24d9195SAndreas Gohr    $pagelog     = new PageChangeLog($id, 1024);
12358c7319beSGerrit Uitslag    $lastRev     = $pagelog->getRevisions(-1, 1); // from changelog
12368c7319beSGerrit Uitslag    $lastRev     = (int) (empty($lastRev) ? 0 : $lastRev[0]);
1237b24d9195SAndreas Gohr
12388c7319beSGerrit Uitslag    if(!file_exists(wikiFN($id, $lastMod)) && file_exists($fileLastMod) && $lastMod >= $lastRev) {
1239b24d9195SAndreas Gohr        // add old revision to the attic if missing
1240b24d9195SAndreas Gohr        saveOldRevision($id);
1241b24d9195SAndreas Gohr        // add a changelog entry if this edit came from outside dokuwiki
12428c7319beSGerrit Uitslag        if($lastMod > $lastRev) {
12438c7319beSGerrit Uitslag            $fileLastRev = wikiFN($id, $lastRev);
12448c7319beSGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($lastRev);
12453c48b1d0SGerrit Uitslag            if(empty($lastRev) || !file_exists($fileLastRev) || $revinfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
12464b5aebc1SGerrit Uitslag                $filesize_old = 0;
12474b5aebc1SGerrit Uitslag            } else {
12488c7319beSGerrit Uitslag                $filesize_old = io_getSizeFile($fileLastRev);
12494b5aebc1SGerrit Uitslag            }
12508c7319beSGerrit Uitslag            $filesize_new = filesize($fileLastMod);
12512966355bSGerrit Uitslag            $sizechange = $filesize_new - $filesize_old;
12522966355bSGerrit Uitslag
12538c7319beSGerrit Uitslag            addLogEntry($lastMod, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true), $sizechange);
1254b24d9195SAndreas Gohr            // remove soon to be stale instructions
12558c7319beSGerrit Uitslag            $cache = new cache_instructions($id, $fileLastMod);
1256b24d9195SAndreas Gohr            $cache->removeCache();
1257b24d9195SAndreas Gohr        }
1258b24d9195SAndreas Gohr    }
1259b24d9195SAndreas Gohr}
1260b24d9195SAndreas Gohr
1261b24d9195SAndreas Gohr/**
1262a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1263a701424fSBen Coburn * Also directs changelog and attic updates.
126415fae107Sandi *
126515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
126671726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1267140cfbcdSGerrit Uitslag *
1268140cfbcdSGerrit Uitslag * @param string $id       page id
1269140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1270140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1271140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1272f3f0262cSandi */
1273b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1274a701424fSBen Coburn    /* Note to developers:
1275a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1276a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1277a701424fSBen Coburn       after any changes. External edits change the wiki page
1278a701424fSBen Coburn       directly without using php or dokuwiki.
1279a701424fSBen Coburn     */
1280f3f0262cSandi    global $conf;
1281f3f0262cSandi    global $lang;
128271726d78SBen Coburn    global $REV;
1283585bf44eSChristopher Smith    /* @var Input $INPUT */
1284585bf44eSChristopher Smith    global $INPUT;
1285585bf44eSChristopher Smith
1286b24d9195SAndreas Gohr    // prepare data for event
1287b24d9195SAndreas Gohr    $svdta = array();
1288b24d9195SAndreas Gohr    $svdta['id']             = $id;
1289b24d9195SAndreas Gohr    $svdta['file']           = wikiFN($id);
1290b24d9195SAndreas Gohr    $svdta['revertFrom']     = $REV;
1291b24d9195SAndreas Gohr    $svdta['oldRevision']    = @filemtime($svdta['file']);
1292b24d9195SAndreas Gohr    $svdta['newRevision']    = 0;
1293b24d9195SAndreas Gohr    $svdta['newContent']     = $text;
1294b24d9195SAndreas Gohr    $svdta['oldContent']     = rawWiki($id);
1295b24d9195SAndreas Gohr    $svdta['summary']        = $summary;
1296b24d9195SAndreas Gohr    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1297b24d9195SAndreas Gohr    $svdta['changeInfo']     = '';
1298b24d9195SAndreas Gohr    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
12992966355bSGerrit Uitslag    $svdta['sizechange']     = null;
1300b24d9195SAndreas Gohr
1301b24d9195SAndreas Gohr    // select changelog line type
1302b24d9195SAndreas Gohr    if($REV) {
1303b24d9195SAndreas Gohr        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1304b24d9195SAndreas Gohr        $svdta['changeInfo'] = $REV;
1305b24d9195SAndreas Gohr    } else if(!file_exists($svdta['file'])) {
1306b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1307b24d9195SAndreas Gohr    } else if(trim($text) == '') {
1308b24d9195SAndreas Gohr        // empty or whitespace only content deletes
1309b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1310b24d9195SAndreas Gohr        // autoset summary on deletion
1311655ddc1dSGerrit Uitslag        if(blank($svdta['summary'])) {
1312655ddc1dSGerrit Uitslag            $svdta['summary'] = $lang['deleted'];
1313655ddc1dSGerrit Uitslag        }
1314b24d9195SAndreas Gohr    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1315b24d9195SAndreas Gohr        //minor edits only for logged in users
1316b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1317f3f0262cSandi    }
1318f3f0262cSandi
1319b24d9195SAndreas Gohr    $event = new Doku_Event('COMMON_WIKIPAGE_SAVE', $svdta);
1320b24d9195SAndreas Gohr    if(!$event->advise_before()) return;
1321f3f0262cSandi
1322b24d9195SAndreas Gohr    // if the content has not been changed, no save happens (plugins may override this)
1323b24d9195SAndreas Gohr    if(!$svdta['contentChanged']) return;
1324b24d9195SAndreas Gohr
1325b24d9195SAndreas Gohr    detectExternalEdit($id);
1326f3f0262cSandi
13274b5aebc1SGerrit Uitslag    if(
13284b5aebc1SGerrit Uitslag        $svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE ||
13294b5aebc1SGerrit Uitslag        ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file']))
13304b5aebc1SGerrit Uitslag    ) {
1331ac3ed4afSGerrit Uitslag        $filesize_old = 0;
1332ac3ed4afSGerrit Uitslag    } else {
13332966355bSGerrit Uitslag        $filesize_old = filesize($svdta['file']);
1334ac3ed4afSGerrit Uitslag    }
1335b24d9195SAndreas Gohr    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
133630725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
1337b24d9195SAndreas Gohr        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
133830725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1339e45b34cdSBen Coburn        // pre-save deleted revision
1340b24d9195SAndreas Gohr        @touch($svdta['file']);
134146844156SBen Coburn        clearstatcache();
13422d69eb44SMichael Hamann        $svdta['newRevision'] = saveOldRevision($id);
1343e1f3d9e1SEsther Brunner        // remove empty file
1344b24d9195SAndreas Gohr        @unlink($svdta['file']);
1345ac3ed4afSGerrit Uitslag        $filesize_new = 0;
1346c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1347c5f92742SMichael Hamann        // purge non-persistant meta data
13483d1f9ec3SMichael Klier        p_purge_metadata($id);
134953d6ccfeSandi        // remove empty namespaces
1350cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1351cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1352f3f0262cSandi    } else {
1353cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
135433d979e7SMichael Große        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
135546844156SBen Coburn        // pre-save the revision, to keep the attic in sync
1356b24d9195SAndreas Gohr        $svdta['newRevision'] = saveOldRevision($id);
13572966355bSGerrit Uitslag        $filesize_new = filesize($svdta['file']);
1358f3f0262cSandi    }
13592966355bSGerrit Uitslag    $svdta['sizechange'] = $filesize_new - $filesize_old;
1360f3f0262cSandi
1361b24d9195SAndreas Gohr    $event->advise_after();
136271726d78SBen Coburn
13632966355bSGerrit Uitslag    addLogEntry($svdta['newRevision'], $svdta['id'], $svdta['changeType'], $svdta['summary'], $svdta['changeInfo'], null, $svdta['sizechange']);
1364ac3ed4afSGerrit Uitslag
136526a0801fSAndreas Gohr    // send notify mails
1366b24d9195SAndreas Gohr    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
1367b24d9195SAndreas Gohr    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
1368f3f0262cSandi
1369ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
137098407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
13712eccbdaaSGina Haeussge
13722eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1373fe9ec250SChris Smith    if(useHeading('content')) {
137407ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
13752eccbdaaSGina Haeussge        foreach($pages as $page) {
13762eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
13772eccbdaaSGina Haeussge            $cache->removeCache();
13782eccbdaaSGina Haeussge        }
13792eccbdaaSGina Haeussge    }
1380f3f0262cSandi}
1381f3f0262cSandi
1382f3f0262cSandi/**
1383f3f0262cSandi * moves the current version to the attic and returns its
1384f3f0262cSandi * revision date
138515fae107Sandi *
138615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1387140cfbcdSGerrit Uitslag *
1388140cfbcdSGerrit Uitslag * @param string $id page id
1389140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1390f3f0262cSandi */
1391f3f0262cSandifunction saveOldRevision($id) {
1392f3f0262cSandi    $oldf = wikiFN($id);
139379e79377SAndreas Gohr    if(!file_exists($oldf)) return '';
1394f3f0262cSandi    $date = filemtime($oldf);
1395f3f0262cSandi    $newf = wikiFN($id, $date);
1396cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1397f3f0262cSandi    return $date;
1398f3f0262cSandi}
1399f3f0262cSandi
1400f3f0262cSandi/**
1401fde10de4SAdrian Lang * Sends a notify mail on page change or registration
140226a0801fSAndreas Gohr *
140326a0801fSAndreas Gohr * @param string     $id       The changed page
1404fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
14053272d797SAndreas Gohr * @param int|string $rev Old page revision
140626a0801fSAndreas Gohr * @param string     $summary  What changed
140790033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
140842ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
14093272d797SAndreas Gohr * @return bool
1410140cfbcdSGerrit Uitslag *
141115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1412f3f0262cSandi */
141302a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1414f3f0262cSandi    global $conf;
1415585bf44eSChristopher Smith    /* @var Input $INPUT */
1416585bf44eSChristopher Smith    global $INPUT;
1417b158d625SSteven Danz
14186df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
141926a0801fSAndreas Gohr    if($who == 'admin') {
14203272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
14212ed38036SAndreas Gohr        $tpl = 'mailtext';
142226a0801fSAndreas Gohr        $to  = $conf['notify'];
142326a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
142484c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1425585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
14260bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
14273272d797SAndreas Gohr        trigger_event(
14283272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1429835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
14303272d797SAndreas Gohr        );
14312ed38036SAndreas Gohr        $to = $data['addresslist'];
14322ed38036SAndreas Gohr        if(empty($to)) return false;
14332ed38036SAndreas Gohr        $tpl = 'subscr_single';
143426a0801fSAndreas Gohr    } else {
14353272d797SAndreas Gohr        return false; //just to be safe
143626a0801fSAndreas Gohr    }
143726a0801fSAndreas Gohr
14386df843eeSAndreas Gohr    // prepare content
14392ed38036SAndreas Gohr    $subscription = new Subscription();
14402ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1441f3f0262cSandi}
14422ed38036SAndreas Gohr
144315fae107Sandi/**
144471f7bde7SAndreas Gohr * extracts the query from a search engine referrer
144515fae107Sandi *
144615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
144771f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1448140cfbcdSGerrit Uitslag *
1449140cfbcdSGerrit Uitslag * @return array|string
1450f3f0262cSandi */
1451f3f0262cSandifunction getGoogleQuery() {
1452585bf44eSChristopher Smith    /* @var Input $INPUT */
1453585bf44eSChristopher Smith    global $INPUT;
1454585bf44eSChristopher Smith
1455585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1456c66972f2SAdrian Lang        return '';
1457c66972f2SAdrian Lang    }
1458585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1459f3f0262cSandi
1460079b3ac1SAndreas Gohr    // only handle common SEs
1461079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1462e4d8a516SKazutaka Miyasaka
1463079b3ac1SAndreas Gohr    $query = array();
1464e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1465e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1466e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1467f3f0262cSandi    parse_str($url['query'], $query);
1468e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1469e4d8a516SKazutaka Miyasaka
1470c66972f2SAdrian Lang    $q = '';
1471079b3ac1SAndreas Gohr    if(isset($query['q'])){
1472079b3ac1SAndreas Gohr        $q = $query['q'];
1473079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1474079b3ac1SAndreas Gohr        $q = $query['p'];
1475079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1476079b3ac1SAndreas Gohr        $q = $query['query'];
1477079b3ac1SAndreas Gohr    }
1478079b3ac1SAndreas Gohr    $q = trim($q);
1479f3f0262cSandi
1480079b3ac1SAndreas Gohr    if(!$q) return '';
14816531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1482f93b3b50SAndreas Gohr    return $q;
1483f3f0262cSandi}
1484f3f0262cSandi
1485f3f0262cSandi/**
1486f3f0262cSandi * Return the human readable size of a file
1487f3f0262cSandi *
1488f3f0262cSandi * @param int $size A file size
1489f3f0262cSandi * @param int $dec A number of decimal places
149074160ca1SGerrit Uitslag * @return string human readable size
1491140cfbcdSGerrit Uitslag *
1492f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1493f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1494f3f0262cSandi * @version     1.0.0
1495f3f0262cSandi */
1496f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1497f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1498f3f0262cSandi    $count = count($sizes);
1499f3f0262cSandi    $i     = 0;
1500f3f0262cSandi
1501f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1502f3f0262cSandi        $size /= 1024;
1503f3f0262cSandi        $i++;
1504f3f0262cSandi    }
1505f3f0262cSandi
1506ef08383eSAndreas Gohr    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1507f3f0262cSandi}
1508f3f0262cSandi
150915fae107Sandi/**
1510c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1511c57e365eSAndreas Gohr *
1512c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1513140cfbcdSGerrit Uitslag *
1514140cfbcdSGerrit Uitslag * @param int $dt timestamp
1515140cfbcdSGerrit Uitslag * @return string
1516c57e365eSAndreas Gohr */
1517c57e365eSAndreas Gohrfunction datetime_h($dt) {
1518c57e365eSAndreas Gohr    global $lang;
1519c57e365eSAndreas Gohr
1520c57e365eSAndreas Gohr    $ago = time() - $dt;
1521c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1522c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1523c57e365eSAndreas Gohr    }
1524c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1525c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1526c57e365eSAndreas Gohr    }
1527c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1528c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1529c57e365eSAndreas Gohr    }
1530c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1531c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1532c57e365eSAndreas Gohr    }
1533c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1534c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1535c57e365eSAndreas Gohr    }
1536c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1537c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1538c57e365eSAndreas Gohr    }
1539c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1540c57e365eSAndreas Gohr}
1541c57e365eSAndreas Gohr
1542c57e365eSAndreas Gohr/**
1543f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1544f2263577SAndreas Gohr *
1545f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1546f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1547f2263577SAndreas Gohr *
1548f2263577SAndreas Gohr * @see datetime_h
1549f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1550140cfbcdSGerrit Uitslag *
1551140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1552140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1553140cfbcdSGerrit Uitslag * @return string
1554f2263577SAndreas Gohr */
1555f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1556f2263577SAndreas Gohr    global $conf;
1557f2263577SAndreas Gohr
1558f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1559f2263577SAndreas Gohr    $dt = (int) $dt;
1560f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1561f2263577SAndreas Gohr
1562f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1563f2263577SAndreas Gohr    return strftime($format, $dt);
1564f2263577SAndreas Gohr}
1565f2263577SAndreas Gohr
1566f2263577SAndreas Gohr/**
1567c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1568c4f79b71SMichael Hamann *
1569c4f79b71SMichael Hamann * @author <ungu at terong dot com>
157059752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1571140cfbcdSGerrit Uitslag *
15727e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
15733272d797SAndreas Gohr * @return string
1574c4f79b71SMichael Hamann */
1575c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1576c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1577c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1578c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1579c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1580c4f79b71SMichael Hamann    return $date_mod;
1581c4f79b71SMichael Hamann}
1582c4f79b71SMichael Hamann
1583c4f79b71SMichael Hamann/**
158400a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
158500a7b5adSEsther Brunner *
158600a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
158700a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1588140cfbcdSGerrit Uitslag *
1589140cfbcdSGerrit Uitslag * @param string $email email address
1590140cfbcdSGerrit Uitslag * @return string
159100a7b5adSEsther Brunner */
159200a7b5adSEsther Brunnerfunction obfuscate($email) {
159300a7b5adSEsther Brunner    global $conf;
159400a7b5adSEsther Brunner
159500a7b5adSEsther Brunner    switch($conf['mailguard']) {
159600a7b5adSEsther Brunner        case 'visible' :
159700a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
159800a7b5adSEsther Brunner            return strtr($email, $obfuscate);
159900a7b5adSEsther Brunner
160000a7b5adSEsther Brunner        case 'hex' :
160100a7b5adSEsther Brunner            $encode = '';
160249eb6e38SAndreas Gohr            $len    = strlen($email);
160349eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
160449eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
160549eb6e38SAndreas Gohr            }
160600a7b5adSEsther Brunner            return $encode;
160700a7b5adSEsther Brunner
160800a7b5adSEsther Brunner        case 'none' :
160900a7b5adSEsther Brunner        default :
161000a7b5adSEsther Brunner            return $email;
161100a7b5adSEsther Brunner    }
161200a7b5adSEsther Brunner}
161300a7b5adSEsther Brunner
161400a7b5adSEsther Brunner/**
161589541d4bSAndreas Gohr * Removes quoting backslashes
161689541d4bSAndreas Gohr *
161789541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1618140cfbcdSGerrit Uitslag *
1619140cfbcdSGerrit Uitslag * @param string $string
1620140cfbcdSGerrit Uitslag * @param string $char backslashed character
1621140cfbcdSGerrit Uitslag * @return string
162289541d4bSAndreas Gohr */
162389541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
162489541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
162589541d4bSAndreas Gohr}
162689541d4bSAndreas Gohr
162773038c47SAndreas Gohr/**
162873038c47SAndreas Gohr * Convert php.ini shorthands to byte
162973038c47SAndreas Gohr *
163073038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
163159752844SAnders Sandblad * @link   http://php.net/manual/en/ini.core.php#79564
1632140cfbcdSGerrit Uitslag *
1633140cfbcdSGerrit Uitslag * @param string $v shorthands
1634140cfbcdSGerrit Uitslag * @return int|string
163573038c47SAndreas Gohr */
163673038c47SAndreas Gohrfunction php_to_byte($v) {
163773038c47SAndreas Gohr    $l   = substr($v, -1);
163873038c47SAndreas Gohr    $ret = substr($v, 0, -1);
163973038c47SAndreas Gohr    switch(strtoupper($l)) {
164074160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
164173038c47SAndreas Gohr        case 'P':
164273038c47SAndreas Gohr            $ret *= 1024;
164374160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
164473038c47SAndreas Gohr        case 'T':
164573038c47SAndreas Gohr            $ret *= 1024;
164674160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
164773038c47SAndreas Gohr        case 'G':
164873038c47SAndreas Gohr            $ret *= 1024;
164974160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
165073038c47SAndreas Gohr        case 'M':
165173038c47SAndreas Gohr            $ret *= 1024;
1652f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
165373038c47SAndreas Gohr        case 'K':
165473038c47SAndreas Gohr            $ret *= 1024;
165573038c47SAndreas Gohr            break;
165649cbd23eSOtto Vainio        default;
165749cbd23eSOtto Vainio            $ret *= 10;
165849cbd23eSOtto Vainio            break;
165973038c47SAndreas Gohr    }
166073038c47SAndreas Gohr    return $ret;
166173038c47SAndreas Gohr}
166273038c47SAndreas Gohr
1663546d3a99SAndreas Gohr/**
1664546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1665140cfbcdSGerrit Uitslag *
1666140cfbcdSGerrit Uitslag * @param string $string
1667140cfbcdSGerrit Uitslag * @return string
1668546d3a99SAndreas Gohr */
1669546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1670546d3a99SAndreas Gohr    return preg_quote($string, '/');
1671546d3a99SAndreas Gohr}
167273038c47SAndreas Gohr
1673bd2f6c2fSAndreas Gohr/**
1674bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1675bd2f6c2fSAndreas Gohr *
1676c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1677bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1678bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1679bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1680bd2f6c2fSAndreas Gohr *
1681bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1682bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1683bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1684bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1685bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
16863272d797SAndreas Gohr * @return string
1687bd2f6c2fSAndreas Gohr */
1688a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1689bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1690bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1691bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1692bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1693bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1694bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1695bd2f6c2fSAndreas Gohr}
1696bd2f6c2fSAndreas Gohr
1697dc58b6f4SAndy Webber/**
1698dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1699dc58b6f4SAndy Webber * in page footer and recent changes pages
1700dc58b6f4SAndy Webber *
1701b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
170215f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1703c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
170415f3bc49SGerrit Uitslag *
1705dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1706dc58b6f4SAndy Webber */
170715f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1708cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1709dc58b6f4SAndy Webber}
1710dc58b6f4SAndy Webber
171160a396c8SGerrit Uitslag/**
171260a396c8SGerrit Uitslag * Returns users realname w/o link
171360a396c8SGerrit Uitslag *
1714f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
171515f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1716c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
171760a396c8SGerrit Uitslag *
171860a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
171960a396c8SGerrit Uitslag */
1720cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
172160a396c8SGerrit Uitslag    global $conf, $INFO;
172260a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
172360a396c8SGerrit Uitslag    global $auth;
172430f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
172530f6ec4bSGerrit Uitslag    global $INPUT;
172660a396c8SGerrit Uitslag
172760a396c8SGerrit Uitslag    // prepare initial event data
172860a396c8SGerrit Uitslag    $data = array(
172960a396c8SGerrit Uitslag        'username' => $username, // the unique user name
173060a396c8SGerrit Uitslag        'name' => '',
173160a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
173260a396c8SGerrit Uitslag                         'target' => '',
173360a396c8SGerrit Uitslag                         'pre' => '',
173460a396c8SGerrit Uitslag                         'suf' => '',
173560a396c8SGerrit Uitslag                         'style' => '',
173660a396c8SGerrit Uitslag                         'more' => '',
173760a396c8SGerrit Uitslag                         'url' => '',
173860a396c8SGerrit Uitslag                         'title' => '',
173960a396c8SGerrit Uitslag                         'class' => ''
174060a396c8SGerrit Uitslag        ),
17414d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
174215f3bc49SGerrit Uitslag        'textonly' => $textonly
174360a396c8SGerrit Uitslag    );
174462c8004eSGerrit Uitslag    if($username === null) {
174530f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
174615f3bc49SGerrit Uitslag        if($textonly){
174715f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
174815f3bc49SGerrit Uitslag        }else {
174930f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
175060a396c8SGerrit Uitslag        }
175115f3bc49SGerrit Uitslag    }
175260a396c8SGerrit Uitslag
175360a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
175460a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
175560a396c8SGerrit Uitslag        if(empty($data['name'])) {
175660a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
175765833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1758dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1759dc58b6f4SAndy Webber                    case 'username':
17607f081821SGerrit Uitslag                    case 'username_link':
176115f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
176260a396c8SGerrit Uitslag                        break;
1763dc58b6f4SAndy Webber                    case 'email':
1764dc58b6f4SAndy Webber                    case 'email_link':
176560a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
176660a396c8SGerrit Uitslag                        break;
1767dc58b6f4SAndy Webber                }
176865833968SGerrit Uitslag            } else {
176965833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
177060a396c8SGerrit Uitslag            }
177160a396c8SGerrit Uitslag        }
17727f081821SGerrit Uitslag
17737f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
17747f081821SGerrit Uitslag        static $xhtml_renderer = null;
17757f081821SGerrit Uitslag
177615f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
17777f081821SGerrit Uitslag
17787f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
177960a396c8SGerrit Uitslag                if(!isset($info)) {
178060a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
178160a396c8SGerrit Uitslag                }
178260a396c8SGerrit Uitslag                if(isset($info) && $info) {
17837f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
178460a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1785dc58b6f4SAndy Webber                    } else {
17867f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
17877f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
17887f081821SGerrit Uitslag                        }
17897f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
17907f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
17917f081821SGerrit Uitslag                        }
17927f081821SGerrit Uitslag                        $shortcut = 'user';
1793533772e1SGerrit Uitslag                        $exists = null;
17946496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
17952a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
17966496c33fSGerrit Uitslag                        if($exists !== null) {
17976496c33fSGerrit Uitslag                            if($exists) {
17986496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17996496c33fSGerrit Uitslag                            } else {
18006496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
18016496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
18026496c33fSGerrit Uitslag                            }
18036496c33fSGerrit Uitslag                        }
1804dc58b6f4SAndy Webber                    }
1805dc58b6f4SAndy Webber                } else {
180615f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1807dc58b6f4SAndy Webber                }
180860a396c8SGerrit Uitslag
180960a396c8SGerrit Uitslag            } else {
181015f3bc49SGerrit Uitslag                $data['textonly'] = true;
181160a396c8SGerrit Uitslag            }
181260a396c8SGerrit Uitslag        }
181360a396c8SGerrit Uitslag
181415f3bc49SGerrit Uitslag        if($data['textonly']) {
18154d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
181660a396c8SGerrit Uitslag        } else {
181760a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
181860a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
181960a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
182060a396c8SGerrit Uitslag            }
18214d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
182260a396c8SGerrit Uitslag        }
182360a396c8SGerrit Uitslag    }
182460a396c8SGerrit Uitslag    $evt->advise_after();
182560a396c8SGerrit Uitslag    unset($evt);
182660a396c8SGerrit Uitslag
18274d5fc927SGerrit Uitslag    return $data['userlink'];
1828066fee30SAndreas Gohr}
1829066fee30SAndreas Gohr
1830066fee30SAndreas Gohr/**
1831066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1832066fee30SAndreas Gohr * When no image exists, returns an empty string
1833066fee30SAndreas Gohr *
1834066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1835140cfbcdSGerrit Uitslag *
1836066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
18373272d797SAndreas Gohr * @return string
1838066fee30SAndreas Gohr */
1839066fee30SAndreas Gohrfunction license_img($type) {
1840066fee30SAndreas Gohr    global $license;
1841066fee30SAndreas Gohr    global $conf;
1842066fee30SAndreas Gohr    if(!$conf['license']) return '';
1843066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1844066fee30SAndreas Gohr    $try   = array();
1845066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1846066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1847066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1848066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1849066fee30SAndreas Gohr    }
1850066fee30SAndreas Gohr    foreach($try as $src) {
185179e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1852066fee30SAndreas Gohr    }
1853066fee30SAndreas Gohr    return '';
1854dc58b6f4SAndy Webber}
1855dc58b6f4SAndy Webber
185613c08e2fSMichael Klier/**
185713c08e2fSMichael Klier * Checks if the given amount of memory is available
185813c08e2fSMichael Klier *
185913c08e2fSMichael Klier * If the memory_get_usage() function is not available the
186013c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
186113c08e2fSMichael Klier *
186213c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
186313c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
18643272d797SAndreas Gohr *
18653272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1866140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
18673272d797SAndreas Gohr * @return bool
186813c08e2fSMichael Klier */
186913c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
187013c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
187113c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
187213c08e2fSMichael Klier
187313c08e2fSMichael Klier    // parse limit to bytes
187413c08e2fSMichael Klier    $limit = php_to_byte($limit);
187513c08e2fSMichael Klier
187613c08e2fSMichael Klier    // get used memory if possible
187713c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
187813c08e2fSMichael Klier        $used = memory_get_usage();
187949eb6e38SAndreas Gohr    } else {
188049eb6e38SAndreas Gohr        $used = $bytes;
188113c08e2fSMichael Klier    }
188213c08e2fSMichael Klier
188313c08e2fSMichael Klier    if($used + $mem > $limit) {
188413c08e2fSMichael Klier        return false;
188513c08e2fSMichael Klier    }
188613c08e2fSMichael Klier
188713c08e2fSMichael Klier    return true;
188813c08e2fSMichael Klier}
188913c08e2fSMichael Klier
1890af2408d5SAndreas Gohr/**
1891af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1892af2408d5SAndreas Gohr *
1893af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1894af2408d5SAndreas Gohr *
1895af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1896af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1897140cfbcdSGerrit Uitslag *
1898140cfbcdSGerrit Uitslag * @param string $url url being directed to
1899af2408d5SAndreas Gohr */
1900af2408d5SAndreas Gohrfunction send_redirect($url) {
190198ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
190298ca30d2SAndreas Gohr
1903585bf44eSChristopher Smith    /* @var Input $INPUT */
1904585bf44eSChristopher Smith    global $INPUT;
1905585bf44eSChristopher Smith
19060181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
19070181f021SAndreas Gohr    global $MSG;
19080181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
19090181f021SAndreas Gohr        //reopen session, store data and close session again
19100181f021SAndreas Gohr        @session_start();
19110181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
19120181f021SAndreas Gohr    }
19130181f021SAndreas Gohr
1914d4869846SAndreas Gohr    // always close the session
1915d4869846SAndreas Gohr    session_write_close();
1916d4869846SAndreas Gohr
1917af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1918585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1919585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1920585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
19213272d797SAndreas Gohr        $matches[1] < 6
19223272d797SAndreas Gohr    ) {
1923af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1924af2408d5SAndreas Gohr    } else {
1925af2408d5SAndreas Gohr        header('Location: '.$url);
1926af2408d5SAndreas Gohr    }
192781781cb6SAndreas Gohr
192881781cb6SAndreas Gohr    if(defined('DOKU_UNITTEST')) return; // no exits during unit tests
1929af2408d5SAndreas Gohr    exit;
1930af2408d5SAndreas Gohr}
1931af2408d5SAndreas Gohr
19325b75cd1fSAdrian Lang/**
19335b75cd1fSAdrian Lang * Validate a value using a set of valid values
19345b75cd1fSAdrian Lang *
19355b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
19365b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
19375b75cd1fSAdrian Lang * default is specified, throws an exception.
19385b75cd1fSAdrian Lang *
19395b75cd1fSAdrian Lang * @param string $param        The name of the parameter
19405b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
19415b75cd1fSAdrian Lang *                             be marked by the key “default”.
19425b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
19435b75cd1fSAdrian Lang *                             or $_GET)
19445b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
19455b75cd1fSAdrian Lang *
19463272d797SAndreas Gohr * @throws Exception
19473272d797SAndreas Gohr * @return mixed
19485b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
19495b75cd1fSAdrian Lang */
19505b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
19515b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
19525b75cd1fSAdrian Lang        return $array[$param];
19535b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
19545b75cd1fSAdrian Lang        return $valid_values['default'];
19555b75cd1fSAdrian Lang    } else {
19565b75cd1fSAdrian Lang        throw new Exception($exc);
19575b75cd1fSAdrian Lang    }
19585b75cd1fSAdrian Lang}
19595b75cd1fSAdrian Lang
196063703ba5SAndreas Gohr/**
196163703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1962646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1963140cfbcdSGerrit Uitslag *
1964140cfbcdSGerrit Uitslag * @param string $pref     preference key
1965b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1966140cfbcdSGerrit Uitslag * @return string preference value
196763703ba5SAndreas Gohr */
1968554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1969646a531aSChristopher Smith    $enc_pref = urlencode($pref);
197006c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1971554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
197263703ba5SAndreas Gohr        $cnt   = count($parts);
197363703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1974646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1975646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1976554a8c9fSAdrian Lang            }
1977554a8c9fSAdrian Lang        }
1978554a8c9fSAdrian Lang    }
1979554a8c9fSAdrian Lang    return $default;
1980554a8c9fSAdrian Lang}
1981554a8c9fSAdrian Lang
19823c94d07bSAnika Henke/**
19833c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
198436ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
19853a970889SAnika Henke * Remove it by setting $val to false
1986140cfbcdSGerrit Uitslag *
1987140cfbcdSGerrit Uitslag * @param string $pref  preference key
1988140cfbcdSGerrit Uitslag * @param string $val   preference value
19893c94d07bSAnika Henke */
19903c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
19913c94d07bSAnika Henke    global $conf;
19923c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19933c94d07bSAnika Henke    $cookieVal = '';
19943c94d07bSAnika Henke
19953c94d07bSAnika Henke    if($orig && ($orig != $val)) {
19963c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19973c94d07bSAnika Henke        $cnt   = count($parts);
199836ec377eSChristopher Smith        // urlencode $pref for the comparison
199936ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
20003c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
200136ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
20023a970889SAnika Henke                if ($val !== false) {
200336ec377eSChristopher Smith                    $parts[$i + 1] = rawurlencode($val);
20043a970889SAnika Henke                } else {
20053a970889SAnika Henke                    unset($parts[$i]);
20063a970889SAnika Henke                    unset($parts[$i + 1]);
20073a970889SAnika Henke                }
200850f261f7SMichael Hamann                break;
20093c94d07bSAnika Henke            }
20103c94d07bSAnika Henke        }
20113c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
20123a970889SAnika Henke    } else if (!$orig && $val !== false) {
201336ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
20143c94d07bSAnika Henke    }
20153c94d07bSAnika Henke
20163c94d07bSAnika Henke    if (!empty($cookieVal)) {
201775e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
201875e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
20193c94d07bSAnika Henke    }
20203c94d07bSAnika Henke}
20213c94d07bSAnika Henke
2022f8fb2d18SAndreas Gohr/**
2023f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
2024f8fb2d18SAndreas Gohr *
202542ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
2026f8fb2d18SAndreas Gohr */
2027f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
2028f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2029f8fb2d18SAndreas Gohr}
2030f8fb2d18SAndreas Gohr
20313c27983bSAndreas Gohr/**
203271de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
20333c27983bSAndreas Gohr *
20343c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
20353c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
20363c27983bSAndreas Gohr * files are embedded.
20373c27983bSAndreas Gohr *
203871de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
203971de5572SAndreas Gohr *
20403c27983bSAndreas Gohr * @param string $file full path to the SVG file
20413c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
204271de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
20433c27983bSAndreas Gohr */
20444cd2074fSAndreas Gohrfunction inlineSVG($file, $maxsize = 2048) {
20453c27983bSAndreas Gohr    $file = trim($file);
20463c27983bSAndreas Gohr    if($file === '') return false;
20473c27983bSAndreas Gohr    if(!file_exists($file)) return false;
20483c27983bSAndreas Gohr    if(filesize($file) > $maxsize) return false;
20493c27983bSAndreas Gohr    if(!is_readable($file)) return false;
20503c27983bSAndreas Gohr    $content = file_get_contents($file);
20510849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
20520849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
20530849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
20540849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
20553c27983bSAndreas Gohr    $content = trim($content);
20563c27983bSAndreas Gohr    if(substr($content, 0, 5) !== '<svg ') return false;
205771de5572SAndreas Gohr    return $content;
20583c27983bSAndreas Gohr}
20593c27983bSAndreas Gohr
2060e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2061