xref: /dokuwiki/inc/common.php (revision 925105e82bbaf10d0b6330b81350f14a5a176eb4)
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
90db5771eSMichael Großeuse dokuwiki\Cache\CacheInstructions;
100db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
110c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
12704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
1375d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
14e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
15e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
160c3a5702SAndreas Gohr
17f3f0262cSandi/**
18b6912aeaSAndreas Gohr * These constants are used with the recents function
19b6912aeaSAndreas Gohr */
20b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_DELETED', 2);
21b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_MINORS', 4);
22b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_SUBSPACES', 8);
230b926329SKate Arzamastsevadefine('RECENTS_MEDIA_CHANGES', 16);
240b926329SKate Arzamastsevadefine('RECENTS_MEDIA_PAGES_MIXED', 32);
25b6912aeaSAndreas Gohr
26b6912aeaSAndreas Gohr/**
27d5197206Schris * Wrapper around htmlspecialchars()
28d5197206Schris *
29d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
30d5197206Schris * @see    htmlspecialchars()
31140cfbcdSGerrit Uitslag *
32140cfbcdSGerrit Uitslag * @param string $string the string being converted
33140cfbcdSGerrit Uitslag * @return string converted string
34d5197206Schris */
35d5197206Schrisfunction hsc($string) {
36d5197206Schris    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
37d5197206Schris}
38d5197206Schris
39d5197206Schris/**
405b571377SAndreas Gohr * Checks if the given input is blank
415b571377SAndreas Gohr *
425b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
435b571377SAndreas Gohr *
4467234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
4567234204SAndreas Gohr * with a NULL value without warning.
4667234204SAndreas Gohr *
4767234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
4867234204SAndreas Gohr *
4967234204SAndreas Gohr * (isset($foo) && !blank($foo))
5067234204SAndreas Gohr * (!isset($foo) || blank($foo))
5167234204SAndreas Gohr *
525b571377SAndreas Gohr * @param $in
535b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
545b571377SAndreas Gohr * @return bool
555b571377SAndreas Gohr */
565b571377SAndreas Gohrfunction blank(&$in, $trim = false) {
575b571377SAndreas Gohr    if(is_null($in)) return true;
585b571377SAndreas Gohr    if(is_array($in)) return empty($in);
595b571377SAndreas Gohr    if($in === "\0") return true;
605b571377SAndreas Gohr    if($trim && trim($in) === '') return true;
615b571377SAndreas Gohr    if(strlen($in) > 0) return false;
625b571377SAndreas Gohr    return empty($in);
635b571377SAndreas Gohr}
645b571377SAndreas Gohr
655b571377SAndreas Gohr/**
66d5197206Schris * print a newline terminated string
67d5197206Schris *
68d5197206Schris * You can give an indention as optional parameter
69d5197206Schris *
70d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
71140cfbcdSGerrit Uitslag *
72140cfbcdSGerrit Uitslag * @param string $string  line of text
73140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
74d5197206Schris */
7525ec097bSChris Smithfunction ptln($string, $indent = 0) {
7625ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
7702b0b681SAndreas Gohr}
7802b0b681SAndreas Gohr
7902b0b681SAndreas Gohr/**
8002b0b681SAndreas Gohr * strips control characters (<32) from the given string
8102b0b681SAndreas Gohr *
8202b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
83140cfbcdSGerrit Uitslag *
8442ea7f44SGerrit Uitslag * @param string $string being stripped
85140cfbcdSGerrit Uitslag * @return string
8602b0b681SAndreas Gohr */
8702b0b681SAndreas Gohrfunction stripctl($string) {
8802b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
89d5197206Schris}
90d5197206Schris
91d5197206Schris/**
92634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
93634d7150SAndreas Gohr *
94634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
95634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
96634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
9742ea7f44SGerrit Uitslag *
98634d7150SAndreas Gohr * @return  string
99634d7150SAndreas Gohr */
100634d7150SAndreas Gohrfunction getSecurityToken() {
101585bf44eSChristopher Smith    /** @var Input $INPUT */
102585bf44eSChristopher Smith    global $INPUT;
1033680e2cdSAndreas Gohr
1043680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1053680e2cdSAndreas Gohr    $session = session_id();
1063680e2cdSAndreas Gohr
1073680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1083680e2cdSAndreas Gohr    if(trim($user) == '' || trim($session) == '') return '';
109c3cc6e05SAndreas Gohr    return \dokuwiki\PassHash::hmac('md5', $session.$user, auth_cookiesalt());
110634d7150SAndreas Gohr}
111634d7150SAndreas Gohr
112634d7150SAndreas Gohr/**
113634d7150SAndreas Gohr * Check the secret CSRF token
114140cfbcdSGerrit Uitslag *
115140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
116140cfbcdSGerrit Uitslag * @return bool success if the token matched
117634d7150SAndreas Gohr */
118634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
119585bf44eSChristopher Smith    /** @var Input $INPUT */
1207d01a0eaSTom N Harris    global $INPUT;
121585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
122df97eaacSAndreas Gohr
1237d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
124634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
125634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
126634d7150SAndreas Gohr        return false;
127634d7150SAndreas Gohr    }
128634d7150SAndreas Gohr    return true;
129634d7150SAndreas Gohr}
130634d7150SAndreas Gohr
131634d7150SAndreas Gohr/**
132634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
133634d7150SAndreas Gohr *
134634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
135140cfbcdSGerrit Uitslag *
136140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
13742ea7f44SGerrit Uitslag * @return string html of hidden form field
138634d7150SAndreas Gohr */
139634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1402404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1413272d797SAndreas Gohr    if($print) echo $ret;
142634d7150SAndreas Gohr    return $ret;
143634d7150SAndreas Gohr}
144634d7150SAndreas Gohr
145634d7150SAndreas Gohr/**
1461015a57dSChristopher Smith * Determine basic information for a request of $id
14715fae107Sandi *
14815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1497e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
150140cfbcdSGerrit Uitslag *
151140cfbcdSGerrit Uitslag * @param string $id         pageid
152140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
153140cfbcdSGerrit Uitslag * @return array with info for a request of $id
154140cfbcdSGerrit Uitslag *
155f3f0262cSandi */
1561015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
157f3f0262cSandi    global $USERINFO;
158585bf44eSChristopher Smith    /* @var Input $INPUT */
159585bf44eSChristopher Smith    global $INPUT;
1606afe8dcaSchris
161c66972f2SAdrian Lang    // set info about manager/admin status.
16259bc3b48SGerrit Uitslag    $info = array();
163c66972f2SAdrian Lang    $info['isadmin']   = false;
164c66972f2SAdrian Lang    $info['ismanager'] = false;
165585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
166f3f0262cSandi        $info['userinfo']   = $USERINFO;
1671015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
168585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
16917ee7f66SAndreas Gohr
170f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
171f8cc712eSAndreas Gohr            $info['isadmin']   = true;
172f8cc712eSAndreas Gohr            $info['ismanager'] = true;
173f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
174f8cc712eSAndreas Gohr            $info['ismanager'] = true;
175f8cc712eSAndreas Gohr        }
176f8cc712eSAndreas Gohr
17717ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
17817ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
179585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
18017ee7f66SAndreas Gohr        }
181ee4c4a1bSAndreas Gohr
182f3f0262cSandi    } else {
1831015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
184ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
185f3f0262cSandi    }
186f3f0262cSandi
1871015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1881015a57dSChristopher Smith
1891015a57dSChristopher Smith    // mobile detection
1901015a57dSChristopher Smith    if ($htmlClient) {
1911015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1921015a57dSChristopher Smith    }
1931015a57dSChristopher Smith
1941015a57dSChristopher Smith    return $info;
1951015a57dSChristopher Smith }
1961015a57dSChristopher Smith
1971015a57dSChristopher Smith/**
1981015a57dSChristopher Smith * Return info about the current document as associative
1991015a57dSChristopher Smith * array.
2001015a57dSChristopher Smith *
2011015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
202140cfbcdSGerrit Uitslag *
203140cfbcdSGerrit Uitslag * @return array with info about current document
2041015a57dSChristopher Smith */
2051015a57dSChristopher Smithfunction pageinfo() {
2061015a57dSChristopher Smith    global $ID;
2071015a57dSChristopher Smith    global $REV;
2081015a57dSChristopher Smith    global $RANGE;
2091015a57dSChristopher Smith    global $lang;
210585bf44eSChristopher Smith    /* @var Input $INPUT */
211585bf44eSChristopher Smith    global $INPUT;
2121015a57dSChristopher Smith
2131015a57dSChristopher Smith    $info = basicinfo($ID);
2141015a57dSChristopher Smith
2151015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2161015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2171015a57dSChristopher Smith    $info['id']  = $ID;
2181015a57dSChristopher Smith    $info['rev'] = $REV;
2191015a57dSChristopher Smith
220585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
22175d66495SMichael Große        $subManager = new SubscriberManager();
22275d66495SMichael Große        $info['subscribed'] = $subManager->userSubscription();
2237e87a794SChristopher Smith    } else {
2247e87a794SChristopher Smith        $info['subscribed'] = false;
2257e87a794SChristopher Smith    }
2267e87a794SChristopher Smith
227f3f0262cSandi    $info['locked']     = checklock($ID);
228317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
22979e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
23001c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2312ca9d91cSBen Coburn    if($REV) {
2322ca9d91cSBen Coburn        //check if current revision was meant
23301c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
2342ca9d91cSBen Coburn            $REV = '';
2357b3a6803SAndreas Gohr        } elseif($RANGE) {
2367b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2377b3a6803SAndreas Gohr            $REV   = '';
2387b3a6803SAndreas Gohr            $RANGE = '';
2397b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2402ca9d91cSBen Coburn        } else {
2412ca9d91cSBen Coburn            //really use old revision
242317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
24379e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
244f3f0262cSandi        }
245f3f0262cSandi    }
246c112d578Sandi    $info['rev'] = $REV;
247f3f0262cSandi    if($info['exists']) {
248f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
249f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
250f3f0262cSandi    } else {
251f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
252f3f0262cSandi    }
25350e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
254f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
255f3f0262cSandi
25671726d78SBen Coburn    //load page meta data
25771726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
25871726d78SBen Coburn
259652610a2Sandi    //who's the editor
260047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
261652610a2Sandi    if($REV) {
262f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
263652610a2Sandi    } else {
2640e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
265aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
266aa27cf05SAndreas Gohr        } else {
267f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
268cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
269cd00a034SBen Coburn            if($revinfo !== false) {
270cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
271cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
272cd00a034SBen Coburn            }
273cd00a034SBen Coburn        }
274cd00a034SBen Coburn    }
275cd00a034SBen Coburn    //and check for an external edit
276cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
277cd00a034SBen Coburn        // cached changelog line no longer valid
278cd00a034SBen Coburn        $revinfo                     = false;
279cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
280cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
281652610a2Sandi    }
282bb4866bdSchris
283652610a2Sandi    $info['ip']   = $revinfo['ip'];
284652610a2Sandi    $info['user'] = $revinfo['user'];
285652610a2Sandi    $info['sum']  = $revinfo['sum'];
28671726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
287ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
28859f257aeSchris
28988f522e9Sandi    if($revinfo['user']) {
29088f522e9Sandi        $info['editor'] = $revinfo['user'];
29188f522e9Sandi    } else {
29288f522e9Sandi        $info['editor'] = $revinfo['ip'];
29388f522e9Sandi    }
294652610a2Sandi
295ee4c4a1bSAndreas Gohr    // draft
2960aabe6f8SMichael Große    $draft = new \dokuwiki\Draft($ID, $info['client']);
2970aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
2980aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
299ee4c4a1bSAndreas Gohr    }
300ee4c4a1bSAndreas Gohr
3011015a57dSChristopher Smith    return $info;
3021015a57dSChristopher Smith}
3031015a57dSChristopher Smith
3041015a57dSChristopher Smith/**
3050c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3060c39d46cSMichael Große */
3070c39d46cSMichael Großefunction jsinfo() {
3080c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3090c39d46cSMichael Große
3100c39d46cSMichael Große    if (!is_array($JSINFO)) {
3110c39d46cSMichael Große        $JSINFO = [];
3120c39d46cSMichael Große    }
3130c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3140c39d46cSMichael Große    $JSINFO['id']                    = $ID;
3150c39d46cSMichael Große    $JSINFO['namespace']             = (string) $INFO['namespace'];
3160c39d46cSMichael Große    $JSINFO['ACT']                   = act_clean($ACT);
3170c39d46cSMichael Große    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
3180c39d46cSMichael Große    $JSINFO['useHeadingContent']     = (int) useHeading('content');
3190c39d46cSMichael Große}
3200c39d46cSMichael Große
3210c39d46cSMichael Große/**
3221015a57dSChristopher Smith * Return information about the current media item as an associative array.
323140cfbcdSGerrit Uitslag *
324140cfbcdSGerrit Uitslag * @return array with info about current media item
3251015a57dSChristopher Smith */
3261015a57dSChristopher Smithfunction mediainfo(){
3271015a57dSChristopher Smith    global $NS;
3281015a57dSChristopher Smith    global $IMG;
3291015a57dSChristopher Smith
3301015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3311015a57dSChristopher Smith    $info['image'] = $IMG;
3321c548ebeSAndreas Gohr
333f3f0262cSandi    return $info;
334f3f0262cSandi}
335f3f0262cSandi
336f3f0262cSandi/**
3372684e50aSAndreas Gohr * Build an string of URL parameters
3382684e50aSAndreas Gohr *
3392684e50aSAndreas Gohr * @author Andreas Gohr
340140cfbcdSGerrit Uitslag *
341140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
342140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
343140cfbcdSGerrit Uitslag * @return string query string
3442684e50aSAndreas Gohr */
345b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3462684e50aSAndreas Gohr    $url = '';
3472684e50aSAndreas Gohr    $amp = false;
3482684e50aSAndreas Gohr    foreach($params as $key => $val) {
349b174aeaeSchris        if($amp) $url .= $sep;
3502684e50aSAndreas Gohr
35185e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3523a50618cSgweissbach        $url .= rawurlencode((string) $val);
3532684e50aSAndreas Gohr        $amp = true;
3542684e50aSAndreas Gohr    }
3552684e50aSAndreas Gohr    return $url;
3562684e50aSAndreas Gohr}
3572684e50aSAndreas Gohr
3582684e50aSAndreas Gohr/**
3592684e50aSAndreas Gohr * Build an string of html tag attributes
3602684e50aSAndreas Gohr *
3617bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3627bff22c0SAndreas Gohr *
3632684e50aSAndreas Gohr * @author Andreas Gohr
364140cfbcdSGerrit Uitslag *
365140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
366140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
367140cfbcdSGerrit Uitslag * @return string
3682684e50aSAndreas Gohr */
3694b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3702684e50aSAndreas Gohr    $url   = '';
3719063ec14SAdrian Lang    $white = false;
3722684e50aSAndreas Gohr    foreach($params as $key => $val) {
3737bff22c0SAndreas Gohr        if($key{0} == '_') continue;
374b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3759063ec14SAdrian Lang        if($white) $url .= ' ';
3767bff22c0SAndreas Gohr
3772684e50aSAndreas Gohr        $url .= $key.'="';
3782684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3792684e50aSAndreas Gohr        $url .= '"';
3809063ec14SAdrian Lang        $white = true;
3812684e50aSAndreas Gohr    }
3822684e50aSAndreas Gohr    return $url;
3832684e50aSAndreas Gohr}
3842684e50aSAndreas Gohr
3852684e50aSAndreas Gohr/**
38615fae107Sandi * This builds the breadcrumb trail and returns it as array
38715fae107Sandi *
38815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
389140cfbcdSGerrit Uitslag *
390e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
391f3f0262cSandi */
392f3f0262cSandifunction breadcrumbs() {
3938746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3948746e727Sandi    static $crumbs = null;
3958746e727Sandi    if($crumbs != null) return $crumbs;
3968746e727Sandi
397f3f0262cSandi    global $ID;
398f3f0262cSandi    global $ACT;
399f3f0262cSandi    global $conf;
400f3f0262cSandi
401f3f0262cSandi    //first visit?
402c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
4034d1fee4cSB_S666    //we only save on show and existing visible wiki documents
404a77f5846Sjan    $file = wikiFN($ID);
4054d1fee4cSB_S666    if($ACT != 'show' || isHiddenPage($ID) || !file_exists($file)) {
406e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
407f3f0262cSandi        return $crumbs;
408f3f0262cSandi    }
409a77f5846Sjan
410a77f5846Sjan    // page names
4111a84a0f3SAnika Henke    $name = noNSorNS($ID);
412fe9ec250SChris Smith    if(useHeading('navigation')) {
413a77f5846Sjan        // get page title
41467c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
415a77f5846Sjan        if($title) {
416a77f5846Sjan            $name = $title;
417a77f5846Sjan        }
418a77f5846Sjan    }
419a77f5846Sjan
420f3f0262cSandi    //remove ID from array
421a77f5846Sjan    if(isset($crumbs[$ID])) {
422a77f5846Sjan        unset($crumbs[$ID]);
423f3f0262cSandi    }
424f3f0262cSandi
425f3f0262cSandi    //add to array
426a77f5846Sjan    $crumbs[$ID] = $name;
427f3f0262cSandi    //reduce size
428f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
429f3f0262cSandi        array_shift($crumbs);
430f3f0262cSandi    }
431f3f0262cSandi    //save to session
432e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
433f3f0262cSandi    return $crumbs;
434f3f0262cSandi}
435f3f0262cSandi
436f3f0262cSandi/**
43715fae107Sandi * Filter for page IDs
43815fae107Sandi *
439f3f0262cSandi * This is run on a ID before it is outputted somewhere
440f3f0262cSandi * currently used to replace the colon with something else
441907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
442907f24f7SAndreas Gohr *
443907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
444907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
445907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
44615fae107Sandi *
44749c713a3Sandi * Urlencoding is ommitted when the second parameter is false
44849c713a3Sandi *
44915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
450140cfbcdSGerrit Uitslag *
451140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
452140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
453140cfbcdSGerrit Uitslag * @return string
454f3f0262cSandi */
45549c713a3Sandifunction idfilter($id, $ue = true) {
456f3f0262cSandi    global $conf;
457585bf44eSChristopher Smith    /* @var Input $INPUT */
458585bf44eSChristopher Smith    global $INPUT;
459585bf44eSChristopher Smith
460f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
461f3f0262cSandi        $id = strtr($id, ':', '/');
462f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
46358bedc8aSborekb        $conf['userewrite'] &&
464585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4653272d797SAndreas Gohr    ) {
466f3f0262cSandi        $id = strtr($id, ':', ';');
467f3f0262cSandi    }
46849c713a3Sandi    if($ue) {
469b6c6979fSAndreas Gohr        $id = rawurlencode($id);
470f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
471edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
472f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
47349c713a3Sandi    }
474f3f0262cSandi    return $id;
475f3f0262cSandi}
476f3f0262cSandi
477f3f0262cSandi/**
478ed7b5f09Sandi * This builds a link to a wikipage
47915fae107Sandi *
4804bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4816c7843b5Sandi *
48215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4834bc480e5SAndreas Gohr *
4844bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4854bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4864bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4874bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4884bc480e5SAndreas Gohr * @return string
489f3f0262cSandi */
49016f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
491f3f0262cSandi    global $conf;
49216f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
4934bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
49464159a61SAndreas Gohr        if(isset($urlParameters['at']) && $conf['date_at_format']) {
49564159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
49664159a61SAndreas Gohr        }
49716f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4986de3759aSAndreas Gohr    } else {
49916f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5006de3759aSAndreas Gohr    }
50116f15a81SDominik Eckelmann    if($id === '') {
50216f15a81SDominik Eckelmann        $id = $conf['start'];
50316f15a81SDominik Eckelmann    }
504f3f0262cSandi    $id = idfilter($id);
50516f15a81SDominik Eckelmann    if($absolute) {
506ed7b5f09Sandi        $xlink = DOKU_URL;
507ed7b5f09Sandi    } else {
508ed7b5f09Sandi        $xlink = DOKU_BASE;
509ed7b5f09Sandi    }
510f3f0262cSandi
5116c7843b5Sandi    if($conf['userewrite'] == 2) {
5126c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
51316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
5146c7843b5Sandi    } elseif($conf['userewrite']) {
515f3f0262cSandi        $xlink .= $id;
51616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
51740b5fb5bSPhy    } elseif($id !== '') {
5186c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
51916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
520bce3726dSAndreas Gohr    } else {
521bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
52216f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
523f3f0262cSandi    }
524f3f0262cSandi
525f3f0262cSandi    return $xlink;
526f3f0262cSandi}
527f3f0262cSandi
528f3f0262cSandi/**
529f5c2808fSBen Coburn * This builds a link to an alternate page format
530f5c2808fSBen Coburn *
531f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
532f5c2808fSBen Coburn *
533f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5344bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5354bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5364bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5374bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5384bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5394bc480e5SAndreas Gohr * @return string
540f5c2808fSBen Coburn */
5414bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
542f5c2808fSBen Coburn    global $conf;
5434bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5444bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
545f5c2808fSBen Coburn    } else {
5464bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
547f5c2808fSBen Coburn    }
548f5c2808fSBen Coburn
549f5c2808fSBen Coburn    $format = rawurlencode($format);
550f5c2808fSBen Coburn    $id     = idfilter($id);
551f5c2808fSBen Coburn    if($abs) {
552f5c2808fSBen Coburn        $xlink = DOKU_URL;
553f5c2808fSBen Coburn    } else {
554f5c2808fSBen Coburn        $xlink = DOKU_BASE;
555f5c2808fSBen Coburn    }
556f5c2808fSBen Coburn
557f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
558f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5594bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
560f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
561f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5624bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
563f5c2808fSBen Coburn    } else {
564f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5654bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
566f5c2808fSBen Coburn    }
567f5c2808fSBen Coburn
568f5c2808fSBen Coburn    return $xlink;
569f5c2808fSBen Coburn}
570f5c2808fSBen Coburn
571f5c2808fSBen Coburn/**
5726de3759aSAndreas Gohr * Build a link to a media file
5736de3759aSAndreas Gohr *
5746de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5758c08db0aSAndreas Gohr *
5768c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5778c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5788c08db0aSAndreas Gohr *
5793272d797SAndreas Gohr * @param string  $id     the media file id or URL
5803272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5813272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5823272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5833272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5843272d797SAndreas Gohr * @return string
5856de3759aSAndreas Gohr */
58655b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5876de3759aSAndreas Gohr    global $conf;
588b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
589826d2766SKlap-in    if(!$isexternalimage) {
590826d2766SKlap-in        $id = cleanID($id);
591826d2766SKlap-in    }
592826d2766SKlap-in
5936de3759aSAndreas Gohr    if(is_array($more)) {
5940f4e0092SChristopher Smith        // add token for resized images
595443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5960f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5970f4e0092SChristopher Smith        }
5988c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5998c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
600443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
601443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
6028c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
60378b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
604b174aeaeSchris        $more = buildURLparams($more, $sep);
6056de3759aSAndreas Gohr    } else {
6065e7db1e2SChristopher Smith        $matches = array();
607cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
6085e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
6095e7db1e2SChristopher Smith            foreach ($matches as $match){
6105e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6115e7db1e2SChristopher Smith            }
612cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
613cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
6145e7db1e2SChristopher Smith        }
6158c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6168c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
617b174aeaeSchris        $more = str_replace(',', $sep, $more);
6186de3759aSAndreas Gohr    }
6196de3759aSAndreas Gohr
62055b2b31bSAndreas Gohr    if($abs) {
62155b2b31bSAndreas Gohr        $xlink = DOKU_URL;
62255b2b31bSAndreas Gohr    } else {
6236de3759aSAndreas Gohr        $xlink = DOKU_BASE;
62455b2b31bSAndreas Gohr    }
6256de3759aSAndreas Gohr
6266de3759aSAndreas Gohr    // external URLs are always direct without rewriting
627826d2766SKlap-in    if($isexternalimage) {
6286de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
629cc036f74SKlap-in        $xlink .= '?'.$more;
630b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6316de3759aSAndreas Gohr        return $xlink;
6326de3759aSAndreas Gohr    }
6336de3759aSAndreas Gohr
6346de3759aSAndreas Gohr    $id = idfilter($id);
6356de3759aSAndreas Gohr
6366de3759aSAndreas Gohr    // decide on scriptname
6376de3759aSAndreas Gohr    if($direct) {
6386de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6396de3759aSAndreas Gohr            $script = '_media';
6406de3759aSAndreas Gohr        } else {
6416de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6426de3759aSAndreas Gohr        }
6436de3759aSAndreas Gohr    } else {
6446de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6456de3759aSAndreas Gohr            $script = '_detail';
6466de3759aSAndreas Gohr        } else {
6476de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
6486de3759aSAndreas Gohr        }
6496de3759aSAndreas Gohr    }
6506de3759aSAndreas Gohr
6516de3759aSAndreas Gohr    // build URL based on rewrite mode
6526de3759aSAndreas Gohr    if($conf['userewrite']) {
6536de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6546de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6556de3759aSAndreas Gohr    } else {
6566de3759aSAndreas Gohr        if($more) {
657a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
658b174aeaeSchris            $xlink .= $sep.'media='.$id;
6596de3759aSAndreas Gohr        } else {
660a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6616de3759aSAndreas Gohr        }
6626de3759aSAndreas Gohr    }
6636de3759aSAndreas Gohr
6646de3759aSAndreas Gohr    return $xlink;
6656de3759aSAndreas Gohr}
6666de3759aSAndreas Gohr
6676de3759aSAndreas Gohr/**
66825ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
66915fae107Sandi *
67025ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
67125ca5b17SAndreas Gohr *
67215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
673140cfbcdSGerrit Uitslag *
674140cfbcdSGerrit Uitslag * @return string
675f3f0262cSandi */
67625ca5b17SAndreas Gohrfunction script() {
677ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
678f3f0262cSandi}
679f3f0262cSandi
680f3f0262cSandi/**
68115fae107Sandi * Spamcheck against wordlist
68215fae107Sandi *
683f3f0262cSandi * Checks the wikitext against a list of blocked expressions
684f3f0262cSandi * returns true if the text contains any bad words
68515fae107Sandi *
686e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
687e403cc58SMichael Klier *
688e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
689e403cc58SMichael Klier *  and gain information about the user who was blocked.
690e403cc58SMichael Klier *
691e403cc58SMichael Klier *  Event data:
692e403cc58SMichael Klier *    data['matches']  - array of matches
693e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
694e403cc58SMichael Klier *      [ip]           - ip address
695e403cc58SMichael Klier *      [user]         - username (if logged in)
696e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
697e403cc58SMichael Klier *      [name]         - real name (if logged in)
698e403cc58SMichael Klier *
69915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7006dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
701140cfbcdSGerrit Uitslag *
7026dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
7036dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
704f3f0262cSandi */
7056dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
706f3f0262cSandi    global $TEXT;
7076dffa0e0SAndreas Gohr    global $PRE;
7086dffa0e0SAndreas Gohr    global $SUF;
709e0086ca2SAndreas Gohr    global $SUM;
710f3f0262cSandi    global $conf;
711e403cc58SMichael Klier    global $INFO;
712585bf44eSChristopher Smith    /* @var Input $INPUT */
713585bf44eSChristopher Smith    global $INPUT;
714f3f0262cSandi
715f3f0262cSandi    if(!$conf['usewordblock']) return false;
716f3f0262cSandi
717e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
7186dffa0e0SAndreas Gohr
719041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
72064159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
72164159a61SAndreas Gohr    $text = preg_replace(
72264159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
72364159a61SAndreas Gohr        '\1http://\2 \2\3',
72464159a61SAndreas Gohr        $text
72564159a61SAndreas Gohr    );
72664159a61SAndreas Gohr    // phpcs:enable
727041d1964SAndreas Gohr
728b9ac8716Schris    $wordblocks = getWordblocks();
7293e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
7303e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
7313e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
7323e2965d7Sandi        // backreferences are used - the maximum is 99
7333e2965d7Sandi        // this is very bad performancewise and may even be too high still
7343e2965d7Sandi        $chunksize = 40;
7353e2965d7Sandi    } else {
736a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
7373e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
738a51d08efSAndreas Gohr        $chunksize = 200;
7393e2965d7Sandi    }
740b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
741f3f0262cSandi        $re = array();
74249eb6e38SAndreas Gohr        // build regexp from blocks
743f3f0262cSandi        foreach($blocks as $block) {
744f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
745f3f0262cSandi            $block = trim($block);
746f3f0262cSandi            if(empty($block)) continue;
747f3f0262cSandi            $re[] = $block;
748f3f0262cSandi        }
749e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
750e403cc58SMichael Klier            // prepare event data
75159bc3b48SGerrit Uitslag            $data = array();
752e403cc58SMichael Klier            $data['matches']        = $matches;
753585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
754585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
755585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
756e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
757e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
758e403cc58SMichael Klier            }
759bad6fc0dSAndreas Gohr            $callback = function () {
760bad6fc0dSAndreas Gohr                return true;
761bad6fc0dSAndreas Gohr            };
762cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
763b9ac8716Schris        }
764703f6fdeSandi    }
765f3f0262cSandi    return false;
766f3f0262cSandi}
767f3f0262cSandi
768f3f0262cSandi/**
76915fae107Sandi * Return the IP of the client
77015fae107Sandi *
7716d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
77215fae107Sandi *
7736d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7746d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7756d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7766d8affe6SAndreas Gohr * headers
7776d8affe6SAndreas Gohr *
77815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
779140cfbcdSGerrit Uitslag *
7803272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7813272d797SAndreas Gohr * @return string
782f3f0262cSandi */
7836d8affe6SAndreas Gohrfunction clientIP($single = false) {
784585bf44eSChristopher Smith    /* @var Input $INPUT */
785*925105e8SPhy    global $INPUT, $conf;
786585bf44eSChristopher Smith
7876d8affe6SAndreas Gohr    $ip   = array();
788585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
789585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
790585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
791585bf44eSChristopher Smith    }
792585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
793585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
794585bf44eSChristopher Smith    }
7956d8affe6SAndreas Gohr
796dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
797dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
798dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
799dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
800dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
801dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
802dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
803dc14c6d1SGuy Brand    $IPv6Address =
804dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
805dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
806dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
807dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
808dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
809dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
810dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
811dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
812dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
813dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
814dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
815dc14c6d1SGuy Brand
8166d8affe6SAndreas Gohr    // remove any non-IP stuff
8176d8affe6SAndreas Gohr    $cnt   = count($ip);
8184ff28443Schris    $match = array();
8196d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
820dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
8214ff28443Schris            $ip[$i] = $match[0];
8224ff28443Schris        } else {
8234ff28443Schris            $ip[$i] = '';
8244ff28443Schris        }
8256d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
826f3f0262cSandi    }
8276d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
8286d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8296d8affe6SAndreas Gohr
8306d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
8316d8affe6SAndreas Gohr
832*925105e8SPhy    // skip trusted local addresses
8336d8affe6SAndreas Gohr    foreach($ip as $i) {
834*925105e8SPhy        if(!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
8356d8affe6SAndreas Gohr            continue;
8366d8affe6SAndreas Gohr        } else {
8376d8affe6SAndreas Gohr            return $i;
8386d8affe6SAndreas Gohr        }
8396d8affe6SAndreas Gohr    }
840*925105e8SPhy
841*925105e8SPhy    // still here? just use the last address
842*925105e8SPhy    // this case all ips in the list are trusted
843*925105e8SPhy    return $ip[count($ip)-1];
844f3f0262cSandi}
845f3f0262cSandi
846f3f0262cSandi/**
8471c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8481c548ebeSAndreas Gohr *
8491c548ebeSAndreas Gohr * Adapted from the example code at url below
8501c548ebeSAndreas Gohr *
8511c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
852140cfbcdSGerrit Uitslag *
85364159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
854140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8551c548ebeSAndreas Gohr */
8561c548ebeSAndreas Gohrfunction clientismobile() {
857585bf44eSChristopher Smith    /* @var Input $INPUT */
858585bf44eSChristopher Smith    global $INPUT;
8591c548ebeSAndreas Gohr
860585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8611c548ebeSAndreas Gohr
862585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8631c548ebeSAndreas Gohr
864585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8651c548ebeSAndreas Gohr
86664159a61SAndreas Gohr    $uamatches = join(
86764159a61SAndreas Gohr        '|',
86864159a61SAndreas Gohr        [
86964159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
87064159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
87164159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
87264159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
87364159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
87464159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
87564159a61SAndreas Gohr            '\d\d\di', 'moto'
87664159a61SAndreas Gohr        ]
87764159a61SAndreas Gohr    );
8781c548ebeSAndreas Gohr
879585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8801c548ebeSAndreas Gohr
8811c548ebeSAndreas Gohr    return false;
8821c548ebeSAndreas Gohr}
8831c548ebeSAndreas Gohr
8841c548ebeSAndreas Gohr/**
8856efc45a2SDmitry Katsubo * check if a given link is interwiki link
8866efc45a2SDmitry Katsubo *
8876efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8886efc45a2SDmitry Katsubo * @return bool
8896efc45a2SDmitry Katsubo */
8906efc45a2SDmitry Katsubofunction link_isinterwiki($link){
8916efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
8926efc45a2SDmitry Katsubo    return false;
8936efc45a2SDmitry Katsubo}
8946efc45a2SDmitry Katsubo
8956efc45a2SDmitry Katsubo/**
89663211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
89763211f61SGlen Harris *
89822ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
89922ef1e32SAndreas Gohr *
90063211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
901140cfbcdSGerrit Uitslag *
9023272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
9033272d797SAndreas Gohr * @return string a comma separated list of hostnames
90463211f61SGlen Harris */
90563211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
90622ef1e32SAndreas Gohr    global $conf;
90722ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
90822ef1e32SAndreas Gohr
90963211f61SGlen Harris    $hosts = array();
91063211f61SGlen Harris    $ips   = explode(',', $ips);
911551a720fSMichael Klier
912551a720fSMichael Klier    if(is_array($ips)) {
9133886270dSAndreas Gohr        foreach($ips as $ip) {
914551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
91563211f61SGlen Harris        }
916551a720fSMichael Klier        return join(',', $hosts);
917551a720fSMichael Klier    } else {
918551a720fSMichael Klier        return gethostbyaddr(trim($ips));
919551a720fSMichael Klier    }
92063211f61SGlen Harris}
92163211f61SGlen Harris
92263211f61SGlen Harris/**
92315fae107Sandi * Checks if a given page is currently locked.
92415fae107Sandi *
925f3f0262cSandi * removes stale lockfiles
92615fae107Sandi *
92715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
928140cfbcdSGerrit Uitslag *
929140cfbcdSGerrit Uitslag * @param string $id page id
930140cfbcdSGerrit Uitslag * @return bool page is locked?
931f3f0262cSandi */
932f3f0262cSandifunction checklock($id) {
933f3f0262cSandi    global $conf;
934585bf44eSChristopher Smith    /* @var Input $INPUT */
935585bf44eSChristopher Smith    global $INPUT;
936585bf44eSChristopher Smith
937c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
938f3f0262cSandi
939f3f0262cSandi    //no lockfile
94079e79377SAndreas Gohr    if(!file_exists($lock)) return false;
941f3f0262cSandi
942f3f0262cSandi    //lockfile expired
943f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
944d8186216SBen Coburn        @unlink($lock);
945f3f0262cSandi        return false;
946f3f0262cSandi    }
947f3f0262cSandi
948f3f0262cSandi    //my own lock
9496d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
9500712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
951f3f0262cSandi        return false;
952f3f0262cSandi    }
953f3f0262cSandi
954f3f0262cSandi    return $ip;
955f3f0262cSandi}
956f3f0262cSandi
957f3f0262cSandi/**
95815fae107Sandi * Lock a page for editing
95915fae107Sandi *
96015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
961140cfbcdSGerrit Uitslag *
962140cfbcdSGerrit Uitslag * @param string $id page id to lock
963f3f0262cSandi */
964f3f0262cSandifunction lock($id) {
965544ed901SDaniel Calviño Sánchez    global $conf;
966585bf44eSChristopher Smith    /* @var Input $INPUT */
967585bf44eSChristopher Smith    global $INPUT;
968544ed901SDaniel Calviño Sánchez
969544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
970544ed901SDaniel Calviño Sánchez        return;
971544ed901SDaniel Calviño Sánchez    }
972544ed901SDaniel Calviño Sánchez
973c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
974585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
975585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
976f3f0262cSandi    } else {
97785fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
978f3f0262cSandi    }
979f3f0262cSandi}
980f3f0262cSandi
981f3f0262cSandi/**
98215fae107Sandi * Unlock a page if it was locked by the user
983f3f0262cSandi *
98415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
985140cfbcdSGerrit Uitslag *
9863272d797SAndreas Gohr * @param string $id page id to unlock
98715fae107Sandi * @return bool true if a lock was removed
988f3f0262cSandi */
989f3f0262cSandifunction unlock($id) {
990585bf44eSChristopher Smith    /* @var Input $INPUT */
991585bf44eSChristopher Smith    global $INPUT;
992585bf44eSChristopher Smith
993c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
99479e79377SAndreas Gohr    if(file_exists($lock)) {
9956d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
996585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
997f3f0262cSandi            @unlink($lock);
998f3f0262cSandi            return true;
999f3f0262cSandi        }
1000f3f0262cSandi    }
1001f3f0262cSandi    return false;
1002f3f0262cSandi}
1003f3f0262cSandi
1004f3f0262cSandi/**
1005f3f0262cSandi * convert line ending to unix format
1006f3f0262cSandi *
10076db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
10086db7468bSAndreas Gohr *
100915fae107Sandi * @see    formText() for 2crlf conversion
101015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1011140cfbcdSGerrit Uitslag *
1012140cfbcdSGerrit Uitslag * @param string $text
1013140cfbcdSGerrit Uitslag * @return string
1014f3f0262cSandi */
1015f3f0262cSandifunction cleanText($text) {
1016f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
10176db7468bSAndreas Gohr
10186db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
10196db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
10206db7468bSAndreas Gohr    // but might actually fix the problem in many cases
10218cbc5ee8SAndreas Gohr    if(!\dokuwiki\Utf8\Clean::isUtf8($text)) $text = utf8_encode($text);
10226db7468bSAndreas Gohr
1023f3f0262cSandi    return $text;
1024f3f0262cSandi}
1025f3f0262cSandi
1026f3f0262cSandi/**
1027f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
1028f3f0262cSandi * It also converts line endings to Windows format which is
1029f3f0262cSandi * pseudo standard for webforms.
1030f3f0262cSandi *
103115fae107Sandi * @see    cleanText() for 2unix conversion
103215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1033140cfbcdSGerrit Uitslag *
1034140cfbcdSGerrit Uitslag * @param string $text
1035140cfbcdSGerrit Uitslag * @return string
1036f3f0262cSandi */
1037f3f0262cSandifunction formText($text) {
10385b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
1039f3f0262cSandi    return htmlspecialchars($text);
1040f3f0262cSandi}
1041f3f0262cSandi
1042f3f0262cSandi/**
104315fae107Sandi * Returns the specified local text in raw format
104415fae107Sandi *
104515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1046140cfbcdSGerrit Uitslag *
1047140cfbcdSGerrit Uitslag * @param string $id   page id
1048140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1049140cfbcdSGerrit Uitslag * @return string
1050f3f0262cSandi */
10512adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
10522adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1053f3f0262cSandi}
1054f3f0262cSandi
1055f3f0262cSandi/**
1056f3f0262cSandi * Returns the raw WikiText
105715fae107Sandi *
105815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1059140cfbcdSGerrit Uitslag *
1060140cfbcdSGerrit Uitslag * @param string $id   page id
1061e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1062140cfbcdSGerrit Uitslag * @return string
1063f3f0262cSandi */
1064f3f0262cSandifunction rawWiki($id, $rev = '') {
1065cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1066f3f0262cSandi}
1067f3f0262cSandi
1068f3f0262cSandi/**
10697146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10707146cee2SAndreas Gohr *
10717b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10727146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1073140cfbcdSGerrit Uitslag *
1074140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1075140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10767146cee2SAndreas Gohr */
1077fe17917eSAdrian Langfunction pageTemplate($id) {
1078a15ce62dSEsther Brunner    global $conf;
1079e29549feSAndreas Gohr
1080fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1081e29549feSAndreas Gohr
10827b84afa2SAndreas Gohr    // prepare initial event data
10837b84afa2SAndreas Gohr    $data = array(
10847b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10857b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10867b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10877b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10887b84afa2SAndreas Gohr    );
10897b84afa2SAndreas Gohr
1090e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10917b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10927b84afa2SAndreas Gohr        // the before event might have loaded the content already
10937b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10947b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10957b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1096fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
109779e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10987b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1099e29549feSAndreas Gohr                } else {
1100e29549feSAndreas Gohr                    // search upper namespaces for templates
1101e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1102e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
110379e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
11047b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1105e29549feSAndreas Gohr                            break;
1106e29549feSAndreas Gohr                        }
1107e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1108e29549feSAndreas Gohr                    }
1109e29549feSAndreas Gohr                }
11107b84afa2SAndreas Gohr            }
11117b84afa2SAndreas Gohr            // load the content
11123d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
11137b84afa2SAndreas Gohr        }
1114a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
11157b84afa2SAndreas Gohr    }
11167b84afa2SAndreas Gohr    $evt->advise_after();
11177b84afa2SAndreas Gohr    unset($evt);
11187b84afa2SAndreas Gohr
1119fe17917eSAdrian Lang    return $data['tpl'];
11202b1223ecSAdrian Lang}
11212b1223ecSAdrian Lang
11222b1223ecSAdrian Lang/**
11232b1223ecSAdrian Lang * Performs common page template replacements
11247b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
11252b1223ecSAdrian Lang *
11262b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1127140cfbcdSGerrit Uitslag *
1128140cfbcdSGerrit Uitslag * @param array $data array with event data
1129140cfbcdSGerrit Uitslag * @return string
11302b1223ecSAdrian Lang */
1131d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
11323272d797SAndreas Gohr    /**
11333272d797SAndreas Gohr     * @var string $id        the id of the page to be created
11343272d797SAndreas Gohr     * @var string $tpl       the text used as template
11353272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
11363272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
11373272d797SAndreas Gohr     */
1138fe17917eSAdrian Lang    extract($data);
1139fe17917eSAdrian Lang
1140b856f7dfSAdrian Lang    global $USERINFO;
1141bce53b1fSAdrian Lang    global $conf;
1142585bf44eSChristopher Smith    /* @var Input $INPUT */
1143585bf44eSChristopher Smith    global $INPUT;
1144e29549feSAndreas Gohr
1145e29549feSAndreas Gohr    // replace placeholders
114626ece5a7SAndreas Gohr    $file = noNS($id);
114737c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
114826ece5a7SAndreas Gohr
11493272d797SAndreas Gohr    $tpl = str_replace(
11503272d797SAndreas Gohr        array(
115126ece5a7SAndreas Gohr             '@ID@',
115226ece5a7SAndreas Gohr             '@NS@',
11538a7bcf66SShota Miyazaki             '@CURNS@',
1154a3db0ab0SSimon Lees             '@!CURNS@',
1155a3db0ab0SSimon Lees             '@!!CURNS@',
1156a3db0ab0SSimon Lees             '@!CURNS!@',
115726ece5a7SAndreas Gohr             '@FILE@',
115826ece5a7SAndreas Gohr             '@!FILE@',
115926ece5a7SAndreas Gohr             '@!FILE!@',
116026ece5a7SAndreas Gohr             '@PAGE@',
116126ece5a7SAndreas Gohr             '@!PAGE@',
116226ece5a7SAndreas Gohr             '@!!PAGE@',
116326ece5a7SAndreas Gohr             '@!PAGE!@',
116426ece5a7SAndreas Gohr             '@USER@',
116526ece5a7SAndreas Gohr             '@NAME@',
116626ece5a7SAndreas Gohr             '@MAIL@',
116726ece5a7SAndreas Gohr             '@DATE@',
116826ece5a7SAndreas Gohr        ),
116926ece5a7SAndreas Gohr        array(
117026ece5a7SAndreas Gohr             $id,
117126ece5a7SAndreas Gohr             getNS($id),
11728a7bcf66SShota Miyazaki             curNS($id),
1173a3db0ab0SSimon Lees             utf8_ucfirst(curNS($id)),
1174a3db0ab0SSimon Lees             utf8_ucwords(curNS($id)),
1175a3db0ab0SSimon Lees             utf8_strtoupper(curNS($id)),
117626ece5a7SAndreas Gohr             $file,
11778cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst($file),
11788cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper($file),
117926ece5a7SAndreas Gohr             $page,
11808cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst($page),
11818cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucwords($page),
11828cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper($page),
1183585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1184b856f7dfSAdrian Lang             $USERINFO['name'],
1185b856f7dfSAdrian Lang             $USERINFO['mail'],
118626ece5a7SAndreas Gohr             $conf['dformat'],
11873272d797SAndreas Gohr        ), $tpl
11883272d797SAndreas Gohr    );
118926ece5a7SAndreas Gohr
11907d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1191bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1192bad6fc0dSAndreas Gohr        '/%./',
1193bad6fc0dSAndreas Gohr        function ($m) {
1194bad6fc0dSAndreas Gohr            return strftime($m[0]);
1195bad6fc0dSAndreas Gohr        },
1196bad6fc0dSAndreas Gohr        $tpl
1197bad6fc0dSAndreas Gohr    );
1198d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1199a15ce62dSEsther Brunner    return $tpl;
12007146cee2SAndreas Gohr}
12017146cee2SAndreas Gohr
12027146cee2SAndreas Gohr/**
120315fae107Sandi * Returns the raw Wiki Text in three slices.
120415fae107Sandi *
120515fae107Sandi * The range parameter needs to have the form "from-to"
120615cfe303Sandi * and gives the range of the section in bytes - no
120715cfe303Sandi * UTF-8 awareness is needed.
1208f3f0262cSandi * The returned order is prefix, section and suffix.
120915fae107Sandi *
121015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1211140cfbcdSGerrit Uitslag *
1212140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1213140cfbcdSGerrit Uitslag * @param string $id    page id
1214140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
121542ea7f44SGerrit Uitslag * @return string[] with three slices
1216f3f0262cSandi */
1217f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1218cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1219f3f0262cSandi
122080fcb268SAdrian Lang    // Parse range
122180fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
122280fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
122380fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
122480fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
122580fcb268SAdrian Lang
122659bc3b48SGerrit Uitslag    $slices = array();
122780fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
122880fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
122915cfe303Sandi    $slices[2] = substr($text, $to);
1230f3f0262cSandi    return $slices;
1231f3f0262cSandi}
1232f3f0262cSandi
1233f3f0262cSandi/**
123415fae107Sandi * Joins wiki text slices
123515fae107Sandi *
123680fcb268SAdrian Lang * function to join the text slices.
1237f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1238f3f0262cSandi * lines between sections if needed (used on saving).
123915fae107Sandi *
124015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1241140cfbcdSGerrit Uitslag *
1242140cfbcdSGerrit Uitslag * @param string $pre   prefix
1243140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1244140cfbcdSGerrit Uitslag * @param string $suf   suffix
1245140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1246140cfbcdSGerrit Uitslag * @return string
1247f3f0262cSandi */
1248f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1249f3f0262cSandi    if($pretty) {
125080fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
12513272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
12523272d797SAndreas Gohr        ) {
125380fcb268SAdrian Lang            $pre .= "\n";
125480fcb268SAdrian Lang        }
125580fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
12563272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
12573272d797SAndreas Gohr        ) {
125880fcb268SAdrian Lang            $text .= "\n";
125980fcb268SAdrian Lang        }
1260f3f0262cSandi    }
1261f3f0262cSandi
1262f3f0262cSandi    return $pre.$text.$suf;
1263f3f0262cSandi}
1264f3f0262cSandi
1265f3f0262cSandi/**
1266b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1267b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1268b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1269b24d9195SAndreas Gohr *
1270b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1271b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1272b24d9195SAndreas Gohr *
1273b24d9195SAndreas Gohr * @param string $id the page ID
1274b24d9195SAndreas Gohr */
1275b24d9195SAndreas Gohrfunction detectExternalEdit($id) {
1276b24d9195SAndreas Gohr    global $lang;
1277b24d9195SAndreas Gohr
12788c7319beSGerrit Uitslag    $fileLastMod = wikiFN($id);
12798c7319beSGerrit Uitslag    $lastMod     = @filemtime($fileLastMod); // from page
1280b24d9195SAndreas Gohr    $pagelog     = new PageChangeLog($id, 1024);
12818c7319beSGerrit Uitslag    $lastRev     = $pagelog->getRevisions(-1, 1); // from changelog
12828c7319beSGerrit Uitslag    $lastRev     = (int) (empty($lastRev) ? 0 : $lastRev[0]);
1283b24d9195SAndreas Gohr
12848c7319beSGerrit Uitslag    if(!file_exists(wikiFN($id, $lastMod)) && file_exists($fileLastMod) && $lastMod >= $lastRev) {
1285b24d9195SAndreas Gohr        // add old revision to the attic if missing
1286b24d9195SAndreas Gohr        saveOldRevision($id);
1287b24d9195SAndreas Gohr        // add a changelog entry if this edit came from outside dokuwiki
12888c7319beSGerrit Uitslag        if($lastMod > $lastRev) {
12898c7319beSGerrit Uitslag            $fileLastRev = wikiFN($id, $lastRev);
12908c7319beSGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($lastRev);
12913c48b1d0SGerrit Uitslag            if(empty($lastRev) || !file_exists($fileLastRev) || $revinfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
12924b5aebc1SGerrit Uitslag                $filesize_old = 0;
12934b5aebc1SGerrit Uitslag            } else {
12948c7319beSGerrit Uitslag                $filesize_old = io_getSizeFile($fileLastRev);
12954b5aebc1SGerrit Uitslag            }
12968c7319beSGerrit Uitslag            $filesize_new = filesize($fileLastMod);
12972966355bSGerrit Uitslag            $sizechange = $filesize_new - $filesize_old;
12982966355bSGerrit Uitslag
129964159a61SAndreas Gohr            addLogEntry(
130064159a61SAndreas Gohr                $lastMod,
130164159a61SAndreas Gohr                $id,
130264159a61SAndreas Gohr                DOKU_CHANGE_TYPE_EDIT,
130364159a61SAndreas Gohr                $lang['external_edit'],
130464159a61SAndreas Gohr                '',
130564159a61SAndreas Gohr                array('ExternalEdit' => true),
130664159a61SAndreas Gohr                $sizechange
130764159a61SAndreas Gohr            );
1308b24d9195SAndreas Gohr            // remove soon to be stale instructions
13090db5771eSMichael Große            $cache = new CacheInstructions($id, $fileLastMod);
1310b24d9195SAndreas Gohr            $cache->removeCache();
1311b24d9195SAndreas Gohr        }
1312b24d9195SAndreas Gohr    }
1313b24d9195SAndreas Gohr}
1314b24d9195SAndreas Gohr
1315b24d9195SAndreas Gohr/**
1316a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1317a701424fSBen Coburn * Also directs changelog and attic updates.
131815fae107Sandi *
131915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
132071726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1321140cfbcdSGerrit Uitslag *
1322140cfbcdSGerrit Uitslag * @param string $id       page id
1323140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1324140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1325140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1326f3f0262cSandi */
1327b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1328a701424fSBen Coburn    /* Note to developers:
1329a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1330a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1331a701424fSBen Coburn       after any changes. External edits change the wiki page
1332a701424fSBen Coburn       directly without using php or dokuwiki.
1333a701424fSBen Coburn     */
1334f3f0262cSandi    global $conf;
1335f3f0262cSandi    global $lang;
133671726d78SBen Coburn    global $REV;
1337585bf44eSChristopher Smith    /* @var Input $INPUT */
1338585bf44eSChristopher Smith    global $INPUT;
1339585bf44eSChristopher Smith
1340b24d9195SAndreas Gohr    // prepare data for event
1341b24d9195SAndreas Gohr    $svdta = array();
1342b24d9195SAndreas Gohr    $svdta['id']             = $id;
1343b24d9195SAndreas Gohr    $svdta['file']           = wikiFN($id);
1344b24d9195SAndreas Gohr    $svdta['revertFrom']     = $REV;
1345b24d9195SAndreas Gohr    $svdta['oldRevision']    = @filemtime($svdta['file']);
1346b24d9195SAndreas Gohr    $svdta['newRevision']    = 0;
1347b24d9195SAndreas Gohr    $svdta['newContent']     = $text;
1348b24d9195SAndreas Gohr    $svdta['oldContent']     = rawWiki($id);
1349b24d9195SAndreas Gohr    $svdta['summary']        = $summary;
1350b24d9195SAndreas Gohr    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1351b24d9195SAndreas Gohr    $svdta['changeInfo']     = '';
1352b24d9195SAndreas Gohr    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
13532966355bSGerrit Uitslag    $svdta['sizechange']     = null;
1354b24d9195SAndreas Gohr
1355b24d9195SAndreas Gohr    // select changelog line type
1356b24d9195SAndreas Gohr    if($REV) {
1357b24d9195SAndreas Gohr        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1358b24d9195SAndreas Gohr        $svdta['changeInfo'] = $REV;
1359b24d9195SAndreas Gohr    } else if(!file_exists($svdta['file'])) {
1360b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1361b24d9195SAndreas Gohr    } else if(trim($text) == '') {
1362b24d9195SAndreas Gohr        // empty or whitespace only content deletes
1363b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1364b24d9195SAndreas Gohr        // autoset summary on deletion
1365655ddc1dSGerrit Uitslag        if(blank($svdta['summary'])) {
1366655ddc1dSGerrit Uitslag            $svdta['summary'] = $lang['deleted'];
1367655ddc1dSGerrit Uitslag        }
1368b24d9195SAndreas Gohr    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1369b24d9195SAndreas Gohr        //minor edits only for logged in users
1370b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1371f3f0262cSandi    }
1372f3f0262cSandi
1373e1d9dcc8SAndreas Gohr    $event = new Event('COMMON_WIKIPAGE_SAVE', $svdta);
1374b24d9195SAndreas Gohr    if(!$event->advise_before()) return;
1375f3f0262cSandi
1376b24d9195SAndreas Gohr    // if the content has not been changed, no save happens (plugins may override this)
1377b24d9195SAndreas Gohr    if(!$svdta['contentChanged']) return;
1378b24d9195SAndreas Gohr
1379b24d9195SAndreas Gohr    detectExternalEdit($id);
1380f3f0262cSandi
13814b5aebc1SGerrit Uitslag    if(
13824b5aebc1SGerrit Uitslag        $svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE ||
13834b5aebc1SGerrit Uitslag        ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file']))
13844b5aebc1SGerrit Uitslag    ) {
1385ac3ed4afSGerrit Uitslag        $filesize_old = 0;
1386ac3ed4afSGerrit Uitslag    } else {
13872966355bSGerrit Uitslag        $filesize_old = filesize($svdta['file']);
1388ac3ed4afSGerrit Uitslag    }
1389b24d9195SAndreas Gohr    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
139030725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
1391b24d9195SAndreas Gohr        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
1392cbb44eabSAndreas Gohr        Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data);
1393e45b34cdSBen Coburn        // pre-save deleted revision
1394b24d9195SAndreas Gohr        @touch($svdta['file']);
139546844156SBen Coburn        clearstatcache();
13962d69eb44SMichael Hamann        $svdta['newRevision'] = saveOldRevision($id);
1397e1f3d9e1SEsther Brunner        // remove empty file
1398b24d9195SAndreas Gohr        @unlink($svdta['file']);
1399ac3ed4afSGerrit Uitslag        $filesize_new = 0;
140064159a61SAndreas Gohr        // don't remove old meta info as it should be saved, plugins can use
140164159a61SAndreas Gohr        // IO_WIKIPAGE_WRITE for removing their metadata...
1402c5f92742SMichael Hamann        // purge non-persistant meta data
14033d1f9ec3SMichael Klier        p_purge_metadata($id);
140453d6ccfeSandi        // remove empty namespaces
1405cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1406cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1407f3f0262cSandi    } else {
1408cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
140933d979e7SMichael Große        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
141046844156SBen Coburn        // pre-save the revision, to keep the attic in sync
1411b24d9195SAndreas Gohr        $svdta['newRevision'] = saveOldRevision($id);
14122966355bSGerrit Uitslag        $filesize_new = filesize($svdta['file']);
1413f3f0262cSandi    }
14142966355bSGerrit Uitslag    $svdta['sizechange'] = $filesize_new - $filesize_old;
1415f3f0262cSandi
1416b24d9195SAndreas Gohr    $event->advise_after();
141771726d78SBen Coburn
141864159a61SAndreas Gohr    addLogEntry(
141964159a61SAndreas Gohr        $svdta['newRevision'],
142064159a61SAndreas Gohr        $svdta['id'],
142164159a61SAndreas Gohr        $svdta['changeType'],
142264159a61SAndreas Gohr        $svdta['summary'],
142364159a61SAndreas Gohr        $svdta['changeInfo'],
142464159a61SAndreas Gohr        null,
142564159a61SAndreas Gohr        $svdta['sizechange']
142664159a61SAndreas Gohr    );
1427ac3ed4afSGerrit Uitslag
142826a0801fSAndreas Gohr    // send notify mails
1429b24d9195SAndreas Gohr    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
1430b24d9195SAndreas Gohr    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
1431f3f0262cSandi
1432ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
143398407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
14342eccbdaaSGina Haeussge
14352eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1436fe9ec250SChris Smith    if(useHeading('content')) {
143707ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
14382eccbdaaSGina Haeussge        foreach($pages as $page) {
14390db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
14402eccbdaaSGina Haeussge            $cache->removeCache();
14412eccbdaaSGina Haeussge        }
14422eccbdaaSGina Haeussge    }
1443f3f0262cSandi}
1444f3f0262cSandi
1445f3f0262cSandi/**
1446f3f0262cSandi * moves the current version to the attic and returns its
1447f3f0262cSandi * revision date
144815fae107Sandi *
144915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1450140cfbcdSGerrit Uitslag *
1451140cfbcdSGerrit Uitslag * @param string $id page id
1452140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1453f3f0262cSandi */
1454f3f0262cSandifunction saveOldRevision($id) {
1455f3f0262cSandi    $oldf = wikiFN($id);
145679e79377SAndreas Gohr    if(!file_exists($oldf)) return '';
1457f3f0262cSandi    $date = filemtime($oldf);
1458f3f0262cSandi    $newf = wikiFN($id, $date);
1459cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1460f3f0262cSandi    return $date;
1461f3f0262cSandi}
1462f3f0262cSandi
1463f3f0262cSandi/**
1464fde10de4SAdrian Lang * Sends a notify mail on page change or registration
146526a0801fSAndreas Gohr *
146626a0801fSAndreas Gohr * @param string     $id       The changed page
1467fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
14683272d797SAndreas Gohr * @param int|string $rev Old page revision
146926a0801fSAndreas Gohr * @param string     $summary  What changed
147090033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
147142ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
14723272d797SAndreas Gohr * @return bool
1473140cfbcdSGerrit Uitslag *
147415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1475f3f0262cSandi */
147602a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1477f3f0262cSandi    global $conf;
1478585bf44eSChristopher Smith    /* @var Input $INPUT */
1479585bf44eSChristopher Smith    global $INPUT;
1480b158d625SSteven Danz
14816df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
148226a0801fSAndreas Gohr    if($who == 'admin') {
14833272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
14842ed38036SAndreas Gohr        $tpl = 'mailtext';
148526a0801fSAndreas Gohr        $to  = $conf['notify'];
148626a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
148784c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1488585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
14890bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
1490cbb44eabSAndreas Gohr        Event::createAndTrigger(
14913272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1492835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
14933272d797SAndreas Gohr        );
14942ed38036SAndreas Gohr        $to = $data['addresslist'];
14952ed38036SAndreas Gohr        if(empty($to)) return false;
14962ed38036SAndreas Gohr        $tpl = 'subscr_single';
149726a0801fSAndreas Gohr    } else {
14983272d797SAndreas Gohr        return false; //just to be safe
149926a0801fSAndreas Gohr    }
150026a0801fSAndreas Gohr
15016df843eeSAndreas Gohr    // prepare content
1502704a815fSMichael Große    $subscription = new PageSubscriptionSender();
150375d66495SMichael Große    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary);
1504f3f0262cSandi}
15052ed38036SAndreas Gohr
150615fae107Sandi/**
150771f7bde7SAndreas Gohr * extracts the query from a search engine referrer
150815fae107Sandi *
150915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
151071f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1511140cfbcdSGerrit Uitslag *
1512140cfbcdSGerrit Uitslag * @return array|string
1513f3f0262cSandi */
1514f3f0262cSandifunction getGoogleQuery() {
1515585bf44eSChristopher Smith    /* @var Input $INPUT */
1516585bf44eSChristopher Smith    global $INPUT;
1517585bf44eSChristopher Smith
1518585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1519c66972f2SAdrian Lang        return '';
1520c66972f2SAdrian Lang    }
1521585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1522f3f0262cSandi
1523079b3ac1SAndreas Gohr    // only handle common SEs
1524079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1525e4d8a516SKazutaka Miyasaka
1526079b3ac1SAndreas Gohr    $query = array();
1527f3f0262cSandi    parse_str($url['query'], $query);
1528e4d8a516SKazutaka Miyasaka
1529c66972f2SAdrian Lang    $q = '';
1530079b3ac1SAndreas Gohr    if(isset($query['q'])){
1531079b3ac1SAndreas Gohr        $q = $query['q'];
1532079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1533079b3ac1SAndreas Gohr        $q = $query['p'];
1534079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1535079b3ac1SAndreas Gohr        $q = $query['query'];
1536079b3ac1SAndreas Gohr    }
1537079b3ac1SAndreas Gohr    $q = trim($q);
1538f3f0262cSandi
1539079b3ac1SAndreas Gohr    if(!$q) return '';
1540*925105e8SPhy    // ignore if query includes a full URL
1541*925105e8SPhy    if(strpos($q, '//') !== false) return '';
15426531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1543f93b3b50SAndreas Gohr    return $q;
1544f3f0262cSandi}
1545f3f0262cSandi
1546f3f0262cSandi/**
1547f3f0262cSandi * Return the human readable size of a file
1548f3f0262cSandi *
1549f3f0262cSandi * @param int $size A file size
1550f3f0262cSandi * @param int $dec A number of decimal places
155174160ca1SGerrit Uitslag * @return string human readable size
1552140cfbcdSGerrit Uitslag *
1553f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1554f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1555f3f0262cSandi * @version     1.0.0
1556f3f0262cSandi */
1557f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1558f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1559f3f0262cSandi    $count = count($sizes);
1560f3f0262cSandi    $i     = 0;
1561f3f0262cSandi
1562f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1563f3f0262cSandi        $size /= 1024;
1564f3f0262cSandi        $i++;
1565f3f0262cSandi    }
1566f3f0262cSandi
1567ef08383eSAndreas Gohr    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1568f3f0262cSandi}
1569f3f0262cSandi
157015fae107Sandi/**
1571c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1572c57e365eSAndreas Gohr *
1573c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1574140cfbcdSGerrit Uitslag *
1575140cfbcdSGerrit Uitslag * @param int $dt timestamp
1576140cfbcdSGerrit Uitslag * @return string
1577c57e365eSAndreas Gohr */
1578c57e365eSAndreas Gohrfunction datetime_h($dt) {
1579c57e365eSAndreas Gohr    global $lang;
1580c57e365eSAndreas Gohr
1581c57e365eSAndreas Gohr    $ago = time() - $dt;
1582c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1583c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1584c57e365eSAndreas Gohr    }
1585c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1586c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1587c57e365eSAndreas Gohr    }
1588c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1589c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1590c57e365eSAndreas Gohr    }
1591c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1592c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1593c57e365eSAndreas Gohr    }
1594c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1595c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1596c57e365eSAndreas Gohr    }
1597c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1598c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1599c57e365eSAndreas Gohr    }
1600c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1601c57e365eSAndreas Gohr}
1602c57e365eSAndreas Gohr
1603c57e365eSAndreas Gohr/**
1604f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1605f2263577SAndreas Gohr *
1606f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1607f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1608f2263577SAndreas Gohr *
1609f2263577SAndreas Gohr * @see datetime_h
1610f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1611140cfbcdSGerrit Uitslag *
1612140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1613140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1614140cfbcdSGerrit Uitslag * @return string
1615f2263577SAndreas Gohr */
1616f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1617f2263577SAndreas Gohr    global $conf;
1618f2263577SAndreas Gohr
1619f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1620f2263577SAndreas Gohr    $dt = (int) $dt;
1621f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1622f2263577SAndreas Gohr
1623f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1624f2263577SAndreas Gohr    return strftime($format, $dt);
1625f2263577SAndreas Gohr}
1626f2263577SAndreas Gohr
1627f2263577SAndreas Gohr/**
1628c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1629c4f79b71SMichael Hamann *
1630c4f79b71SMichael Hamann * @author <ungu at terong dot com>
163159752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1632140cfbcdSGerrit Uitslag *
16337e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
16343272d797SAndreas Gohr * @return string
1635c4f79b71SMichael Hamann */
1636c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1637c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1638c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1639c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1640c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1641c4f79b71SMichael Hamann    return $date_mod;
1642c4f79b71SMichael Hamann}
1643c4f79b71SMichael Hamann
1644c4f79b71SMichael Hamann/**
164500a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
164600a7b5adSEsther Brunner *
164700a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
164800a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1649140cfbcdSGerrit Uitslag *
1650140cfbcdSGerrit Uitslag * @param string $email email address
1651140cfbcdSGerrit Uitslag * @return string
165200a7b5adSEsther Brunner */
165300a7b5adSEsther Brunnerfunction obfuscate($email) {
165400a7b5adSEsther Brunner    global $conf;
165500a7b5adSEsther Brunner
165600a7b5adSEsther Brunner    switch($conf['mailguard']) {
165700a7b5adSEsther Brunner        case 'visible' :
165800a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
165900a7b5adSEsther Brunner            return strtr($email, $obfuscate);
166000a7b5adSEsther Brunner
166100a7b5adSEsther Brunner        case 'hex' :
1662debc52aaSPhy            return utf8_tohtml($email, true);
166300a7b5adSEsther Brunner
166400a7b5adSEsther Brunner        case 'none' :
166500a7b5adSEsther Brunner        default :
166600a7b5adSEsther Brunner            return $email;
166700a7b5adSEsther Brunner    }
166800a7b5adSEsther Brunner}
166900a7b5adSEsther Brunner
167000a7b5adSEsther Brunner/**
167189541d4bSAndreas Gohr * Removes quoting backslashes
167289541d4bSAndreas Gohr *
167389541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1674140cfbcdSGerrit Uitslag *
1675140cfbcdSGerrit Uitslag * @param string $string
1676140cfbcdSGerrit Uitslag * @param string $char backslashed character
1677140cfbcdSGerrit Uitslag * @return string
167889541d4bSAndreas Gohr */
167989541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
168089541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
168189541d4bSAndreas Gohr}
168289541d4bSAndreas Gohr
168373038c47SAndreas Gohr/**
168473038c47SAndreas Gohr * Convert php.ini shorthands to byte
168573038c47SAndreas Gohr *
1686a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1687140cfbcdSGerrit Uitslag *
1688a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1689a81f3d99SAndreas Gohr *
1690a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1691a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1692a81f3d99SAndreas Gohr * @return int
169373038c47SAndreas Gohr */
1694a81f3d99SAndreas Gohrfunction php_to_byte($value) {
1695f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value,-1))) {
169673038c47SAndreas Gohr        case 'G':
1697a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024;
169873038c47SAndreas Gohr            break;
169973038c47SAndreas Gohr        case 'M':
1700a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024 * 1024;
1701a81f3d99SAndreas Gohr            break;
170273038c47SAndreas Gohr        case 'K':
1703a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024;
170473038c47SAndreas Gohr            break;
17059eeeb775SAndreas Gohr        default:
1706a81f3d99SAndreas Gohr            $ret = intval($value);
170749cbd23eSOtto Vainio            break;
170873038c47SAndreas Gohr    }
170973038c47SAndreas Gohr    return $ret;
171073038c47SAndreas Gohr}
171173038c47SAndreas Gohr
1712546d3a99SAndreas Gohr/**
1713546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1714140cfbcdSGerrit Uitslag *
1715140cfbcdSGerrit Uitslag * @param string $string
1716140cfbcdSGerrit Uitslag * @return string
1717546d3a99SAndreas Gohr */
1718546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1719546d3a99SAndreas Gohr    return preg_quote($string, '/');
1720546d3a99SAndreas Gohr}
172173038c47SAndreas Gohr
1722bd2f6c2fSAndreas Gohr/**
1723bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1724bd2f6c2fSAndreas Gohr *
1725c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1726bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1727bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1728bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1729bd2f6c2fSAndreas Gohr *
1730bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1731bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1732bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1733bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1734bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
17353272d797SAndreas Gohr * @return string
1736bd2f6c2fSAndreas Gohr */
1737a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
17388cbc5ee8SAndreas Gohr    $max = $max - \dokuwiki\Utf8\PhpString::strlen($keep);
1739bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
17408cbc5ee8SAndreas Gohr    $len = \dokuwiki\Utf8\PhpString::strlen($short);
1741bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1742bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
17436ce3e5f8SAndreas Gohr    return $keep .
17446ce3e5f8SAndreas Gohr        \dokuwiki\Utf8\PhpString::substr($short, 0, $half - 1) .
17456ce3e5f8SAndreas Gohr        $char .
17466ce3e5f8SAndreas Gohr        \dokuwiki\Utf8\PhpString::substr($short, $len - $half);
1747bd2f6c2fSAndreas Gohr}
1748bd2f6c2fSAndreas Gohr
1749dc58b6f4SAndy Webber/**
1750dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1751dc58b6f4SAndy Webber * in page footer and recent changes pages
1752dc58b6f4SAndy Webber *
1753b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
175415f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1755c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
175615f3bc49SGerrit Uitslag *
1757dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1758dc58b6f4SAndy Webber */
175915f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1760cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1761dc58b6f4SAndy Webber}
1762dc58b6f4SAndy Webber
176360a396c8SGerrit Uitslag/**
176460a396c8SGerrit Uitslag * Returns users realname w/o link
176560a396c8SGerrit Uitslag *
1766f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
176715f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1768c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
176960a396c8SGerrit Uitslag *
177060a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
177160a396c8SGerrit Uitslag */
1772cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
177360a396c8SGerrit Uitslag    global $conf, $INFO;
1774e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
177560a396c8SGerrit Uitslag    global $auth;
177630f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
177730f6ec4bSGerrit Uitslag    global $INPUT;
177860a396c8SGerrit Uitslag
177960a396c8SGerrit Uitslag    // prepare initial event data
178060a396c8SGerrit Uitslag    $data = array(
178160a396c8SGerrit Uitslag        'username' => $username, // the unique user name
178260a396c8SGerrit Uitslag        'name' => '',
178360a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
178460a396c8SGerrit Uitslag                         'target' => '',
178560a396c8SGerrit Uitslag                         'pre' => '',
178660a396c8SGerrit Uitslag                         'suf' => '',
178760a396c8SGerrit Uitslag                         'style' => '',
178860a396c8SGerrit Uitslag                         'more' => '',
178960a396c8SGerrit Uitslag                         'url' => '',
179060a396c8SGerrit Uitslag                         'title' => '',
179160a396c8SGerrit Uitslag                         'class' => ''
179260a396c8SGerrit Uitslag        ),
17934d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
179415f3bc49SGerrit Uitslag        'textonly' => $textonly
179560a396c8SGerrit Uitslag    );
179662c8004eSGerrit Uitslag    if($username === null) {
179730f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
179815f3bc49SGerrit Uitslag        if($textonly){
179915f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
180015f3bc49SGerrit Uitslag        }else {
180164159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
180264159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
180360a396c8SGerrit Uitslag        }
180415f3bc49SGerrit Uitslag    }
180560a396c8SGerrit Uitslag
1806e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
180760a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
180860a396c8SGerrit Uitslag        if(empty($data['name'])) {
180960a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
181065833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1811dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1812dc58b6f4SAndy Webber                    case 'username':
18137f081821SGerrit Uitslag                    case 'username_link':
181415f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
181560a396c8SGerrit Uitslag                        break;
1816dc58b6f4SAndy Webber                    case 'email':
1817dc58b6f4SAndy Webber                    case 'email_link':
181860a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
181960a396c8SGerrit Uitslag                        break;
1820dc58b6f4SAndy Webber                }
182165833968SGerrit Uitslag            } else {
182265833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
182360a396c8SGerrit Uitslag            }
182460a396c8SGerrit Uitslag        }
18257f081821SGerrit Uitslag
18267f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
18277f081821SGerrit Uitslag        static $xhtml_renderer = null;
18287f081821SGerrit Uitslag
182915f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
18307f081821SGerrit Uitslag
18317f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
183260a396c8SGerrit Uitslag                if(!isset($info)) {
183360a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
183460a396c8SGerrit Uitslag                }
183560a396c8SGerrit Uitslag                if(isset($info) && $info) {
18367f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
183760a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1838dc58b6f4SAndy Webber                    } else {
18397f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
18407f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
18417f081821SGerrit Uitslag                        }
18427f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
18437f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
18447f081821SGerrit Uitslag                        }
18457f081821SGerrit Uitslag                        $shortcut = 'user';
1846533772e1SGerrit Uitslag                        $exists = null;
18476496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
18482a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
18496496c33fSGerrit Uitslag                        if($exists !== null) {
18506496c33fSGerrit Uitslag                            if($exists) {
18516496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
18526496c33fSGerrit Uitslag                            } else {
18536496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
18546496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
18556496c33fSGerrit Uitslag                            }
18566496c33fSGerrit Uitslag                        }
1857dc58b6f4SAndy Webber                    }
1858dc58b6f4SAndy Webber                } else {
185915f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1860dc58b6f4SAndy Webber                }
186160a396c8SGerrit Uitslag
186260a396c8SGerrit Uitslag            } else {
186315f3bc49SGerrit Uitslag                $data['textonly'] = true;
186460a396c8SGerrit Uitslag            }
186560a396c8SGerrit Uitslag        }
186660a396c8SGerrit Uitslag
186715f3bc49SGerrit Uitslag        if($data['textonly']) {
18684d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
186960a396c8SGerrit Uitslag        } else {
187060a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
187160a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
187260a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
187360a396c8SGerrit Uitslag            }
18744d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
187560a396c8SGerrit Uitslag        }
187660a396c8SGerrit Uitslag    }
187760a396c8SGerrit Uitslag    $evt->advise_after();
187860a396c8SGerrit Uitslag    unset($evt);
187960a396c8SGerrit Uitslag
18804d5fc927SGerrit Uitslag    return $data['userlink'];
1881066fee30SAndreas Gohr}
1882066fee30SAndreas Gohr
1883066fee30SAndreas Gohr/**
1884066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1885066fee30SAndreas Gohr * When no image exists, returns an empty string
1886066fee30SAndreas Gohr *
1887066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1888140cfbcdSGerrit Uitslag *
1889066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
18903272d797SAndreas Gohr * @return string
1891066fee30SAndreas Gohr */
1892066fee30SAndreas Gohrfunction license_img($type) {
1893066fee30SAndreas Gohr    global $license;
1894066fee30SAndreas Gohr    global $conf;
1895066fee30SAndreas Gohr    if(!$conf['license']) return '';
1896066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1897066fee30SAndreas Gohr    $try   = array();
1898066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1899066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1900066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1901066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1902066fee30SAndreas Gohr    }
1903066fee30SAndreas Gohr    foreach($try as $src) {
190479e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1905066fee30SAndreas Gohr    }
1906066fee30SAndreas Gohr    return '';
1907dc58b6f4SAndy Webber}
1908dc58b6f4SAndy Webber
190913c08e2fSMichael Klier/**
191013c08e2fSMichael Klier * Checks if the given amount of memory is available
191113c08e2fSMichael Klier *
191213c08e2fSMichael Klier * If the memory_get_usage() function is not available the
191313c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
191413c08e2fSMichael Klier *
191513c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
191613c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
19173272d797SAndreas Gohr *
19183272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1919140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
19203272d797SAndreas Gohr * @return bool
192113c08e2fSMichael Klier */
192213c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
192313c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
192413c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
1925985d6187SElenchus    if($limit == -1) return true; // unlimited
192613c08e2fSMichael Klier
192713c08e2fSMichael Klier    // parse limit to bytes
192813c08e2fSMichael Klier    $limit = php_to_byte($limit);
192913c08e2fSMichael Klier
193013c08e2fSMichael Klier    // get used memory if possible
193113c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
193213c08e2fSMichael Klier        $used = memory_get_usage();
193349eb6e38SAndreas Gohr    } else {
193449eb6e38SAndreas Gohr        $used = $bytes;
193513c08e2fSMichael Klier    }
193613c08e2fSMichael Klier
193713c08e2fSMichael Klier    if($used + $mem > $limit) {
193813c08e2fSMichael Klier        return false;
193913c08e2fSMichael Klier    }
194013c08e2fSMichael Klier
194113c08e2fSMichael Klier    return true;
194213c08e2fSMichael Klier}
194313c08e2fSMichael Klier
1944af2408d5SAndreas Gohr/**
1945af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1946af2408d5SAndreas Gohr *
1947af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1948af2408d5SAndreas Gohr *
1949af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1950af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1951140cfbcdSGerrit Uitslag *
1952140cfbcdSGerrit Uitslag * @param string $url url being directed to
1953af2408d5SAndreas Gohr */
1954af2408d5SAndreas Gohrfunction send_redirect($url) {
195598ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
195698ca30d2SAndreas Gohr
1957585bf44eSChristopher Smith    /* @var Input $INPUT */
1958585bf44eSChristopher Smith    global $INPUT;
1959585bf44eSChristopher Smith
19600181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
19610181f021SAndreas Gohr    global $MSG;
19620181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
19630181f021SAndreas Gohr        //reopen session, store data and close session again
19640181f021SAndreas Gohr        @session_start();
19650181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
19660181f021SAndreas Gohr    }
19670181f021SAndreas Gohr
1968d4869846SAndreas Gohr    // always close the session
1969d4869846SAndreas Gohr    session_write_close();
1970d4869846SAndreas Gohr
1971af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1972585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1973585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1974585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
19753272d797SAndreas Gohr        $matches[1] < 6
19763272d797SAndreas Gohr    ) {
1977af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1978af2408d5SAndreas Gohr    } else {
1979af2408d5SAndreas Gohr        header('Location: '.$url);
1980af2408d5SAndreas Gohr    }
198181781cb6SAndreas Gohr
1982572dc222SLarsDW223    // no exits during unit tests
198327c0c399SAndreas Gohr    if(defined('DOKU_UNITTEST')) {
198427c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
198527c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
198627c0c399SAndreas Gohr        if($testRequest !== null) {
198727c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
198827c0c399SAndreas Gohr        }
1989572dc222SLarsDW223        return;
1990572dc222SLarsDW223    }
199127c0c399SAndreas Gohr
1992af2408d5SAndreas Gohr    exit;
1993af2408d5SAndreas Gohr}
1994af2408d5SAndreas Gohr
19955b75cd1fSAdrian Lang/**
19965b75cd1fSAdrian Lang * Validate a value using a set of valid values
19975b75cd1fSAdrian Lang *
19985b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
19995b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
20005b75cd1fSAdrian Lang * default is specified, throws an exception.
20015b75cd1fSAdrian Lang *
20025b75cd1fSAdrian Lang * @param string $param        The name of the parameter
20035b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
20045b75cd1fSAdrian Lang *                             be marked by the key “default”.
20055b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
20065b75cd1fSAdrian Lang *                             or $_GET)
20075b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
20085b75cd1fSAdrian Lang *
20093272d797SAndreas Gohr * @throws Exception
20103272d797SAndreas Gohr * @return mixed
20115b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
20125b75cd1fSAdrian Lang */
20135b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
20145b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
20155b75cd1fSAdrian Lang        return $array[$param];
20165b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
20175b75cd1fSAdrian Lang        return $valid_values['default'];
20185b75cd1fSAdrian Lang    } else {
20195b75cd1fSAdrian Lang        throw new Exception($exc);
20205b75cd1fSAdrian Lang    }
20215b75cd1fSAdrian Lang}
20225b75cd1fSAdrian Lang
202363703ba5SAndreas Gohr/**
202463703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
2025646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
2026140cfbcdSGerrit Uitslag *
2027140cfbcdSGerrit Uitslag * @param string $pref     preference key
2028b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
2029140cfbcdSGerrit Uitslag * @return string preference value
203063703ba5SAndreas Gohr */
2031554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
2032646a531aSChristopher Smith    $enc_pref = urlencode($pref);
203306c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
2034554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
203563703ba5SAndreas Gohr        $cnt   = count($parts);
20361c3eca7dSPhy
20371c3eca7dSPhy        // due to #2721 there might be duplicate entries,
20381c3eca7dSPhy        // so we read from the end
20391c3eca7dSPhy        for($i = $cnt-2; $i >= 0; $i -= 2) {
2040646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
2041646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
2042554a8c9fSAdrian Lang            }
2043554a8c9fSAdrian Lang        }
2044554a8c9fSAdrian Lang    }
2045554a8c9fSAdrian Lang    return $default;
2046554a8c9fSAdrian Lang}
2047554a8c9fSAdrian Lang
20483c94d07bSAnika Henke/**
20493c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
205036ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
20513a970889SAnika Henke * Remove it by setting $val to false
2052140cfbcdSGerrit Uitslag *
2053140cfbcdSGerrit Uitslag * @param string $pref  preference key
2054140cfbcdSGerrit Uitslag * @param string $val   preference value
20553c94d07bSAnika Henke */
20563c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
20573c94d07bSAnika Henke    global $conf;
20583c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
20593c94d07bSAnika Henke    $cookieVal = '';
20603c94d07bSAnika Henke
20611c3eca7dSPhy    if($orig !== false && ($orig !== $val)) {
20623c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
20633c94d07bSAnika Henke        $cnt   = count($parts);
206436ec377eSChristopher Smith        // urlencode $pref for the comparison
206536ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
20661c3eca7dSPhy        $seen = false;
20673c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
206836ec377eSChristopher Smith            if ($parts[$i] == $enc_pref) {
20691c3eca7dSPhy                if (!$seen){
20703a970889SAnika Henke                    if ($val !== false) {
207136ec377eSChristopher Smith                        $parts[$i + 1] = rawurlencode($val);
20723a970889SAnika Henke                    } else {
20733a970889SAnika Henke                        unset($parts[$i]);
20743a970889SAnika Henke                        unset($parts[$i + 1]);
20753a970889SAnika Henke                    }
20761c3eca7dSPhy                    $seen = true;
20771c3eca7dSPhy                } else {
20781c3eca7dSPhy                    // no break because we want to remove duplicate entries
20791c3eca7dSPhy                    unset($parts[$i]);
20801c3eca7dSPhy                    unset($parts[$i + 1]);
20811c3eca7dSPhy                }
20823c94d07bSAnika Henke            }
20833c94d07bSAnika Henke        }
20843c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
20851c3eca7dSPhy    } else if ($orig === false && $val !== false) {
208664159a61SAndreas Gohr        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
208764159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
20883c94d07bSAnika Henke    }
20893c94d07bSAnika Henke
209075e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
20915833995aSPhy    if(defined('DOKU_UNITTEST')) {
20925833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
20935833995aSPhy    }else{
209475e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
20953c94d07bSAnika Henke    }
20963c94d07bSAnika Henke}
20973c94d07bSAnika Henke
2098f8fb2d18SAndreas Gohr/**
2099f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
2100f8fb2d18SAndreas Gohr *
210142ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
2102f8fb2d18SAndreas Gohr */
2103f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
2104f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2105f8fb2d18SAndreas Gohr}
2106f8fb2d18SAndreas Gohr
21073c27983bSAndreas Gohr/**
210871de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
21093c27983bSAndreas Gohr *
21103c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
21113c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
21123c27983bSAndreas Gohr * files are embedded.
21133c27983bSAndreas Gohr *
211471de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
211571de5572SAndreas Gohr *
21163c27983bSAndreas Gohr * @param string $file full path to the SVG file
21173c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
211871de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
21193c27983bSAndreas Gohr */
21204cd2074fSAndreas Gohrfunction inlineSVG($file, $maxsize = 2048) {
21213c27983bSAndreas Gohr    $file = trim($file);
21223c27983bSAndreas Gohr    if($file === '') return false;
21233c27983bSAndreas Gohr    if(!file_exists($file)) return false;
21243c27983bSAndreas Gohr    if(filesize($file) > $maxsize) return false;
21253c27983bSAndreas Gohr    if(!is_readable($file)) return false;
21263c27983bSAndreas Gohr    $content = file_get_contents($file);
21270849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
21280849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
21290849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
21300849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
21313c27983bSAndreas Gohr    $content = trim($content);
21323c27983bSAndreas Gohr    if(substr($content, 0, 5) !== '<svg ') return false;
213371de5572SAndreas Gohr    return $content;
21343c27983bSAndreas Gohr}
21353c27983bSAndreas Gohr
2136e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2137