xref: /dokuwiki/inc/common.php (revision 5b5713770737b5a36a7cc55b86dd0e6fc0c61b78)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Common DokuWiki functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
815fae107Sandi
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10f3f0262cSandi
11f3f0262cSandi/**
12b6912aeaSAndreas Gohr * These constants are used with the recents function
13b6912aeaSAndreas Gohr */
14b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_DELETED', 2);
15b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_MINORS', 4);
16b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_SUBSPACES', 8);
170b926329SKate Arzamastsevadefine('RECENTS_MEDIA_CHANGES', 16);
180b926329SKate Arzamastsevadefine('RECENTS_MEDIA_PAGES_MIXED', 32);
19b6912aeaSAndreas Gohr
20b6912aeaSAndreas Gohr/**
21d5197206Schris * Wrapper around htmlspecialchars()
22d5197206Schris *
23d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
24d5197206Schris * @see    htmlspecialchars()
25140cfbcdSGerrit Uitslag *
26140cfbcdSGerrit Uitslag * @param string $string the string being converted
27140cfbcdSGerrit Uitslag * @return string converted string
28d5197206Schris */
29d5197206Schrisfunction hsc($string) {
30d5197206Schris    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
31d5197206Schris}
32d5197206Schris
33d5197206Schris/**
34*5b571377SAndreas Gohr * Checks if the given input is blank
35*5b571377SAndreas Gohr *
36*5b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
37*5b571377SAndreas Gohr *
38*5b571377SAndreas Gohr * @param $in
39*5b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
40*5b571377SAndreas Gohr * @return bool
41*5b571377SAndreas Gohr */
42*5b571377SAndreas Gohrfunction blank(&$in, $trim = false) {
43*5b571377SAndreas Gohr    if(!isset($in)) return true;
44*5b571377SAndreas Gohr    if(is_null($in)) return true;
45*5b571377SAndreas Gohr    if(is_array($in)) return empty($in);
46*5b571377SAndreas Gohr    if($in === "\0") return true;
47*5b571377SAndreas Gohr    if($trim && trim($in) === '') return true;
48*5b571377SAndreas Gohr    if(strlen($in) > 0) return false;
49*5b571377SAndreas Gohr    return empty($in);
50*5b571377SAndreas Gohr}
51*5b571377SAndreas Gohr
52*5b571377SAndreas Gohr/**
53d5197206Schris * print a newline terminated string
54d5197206Schris *
55d5197206Schris * You can give an indention as optional parameter
56d5197206Schris *
57d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
58140cfbcdSGerrit Uitslag *
59140cfbcdSGerrit Uitslag * @param string $string  line of text
60140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
61d5197206Schris */
6225ec097bSChris Smithfunction ptln($string, $indent = 0) {
6325ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
6402b0b681SAndreas Gohr}
6502b0b681SAndreas Gohr
6602b0b681SAndreas Gohr/**
6702b0b681SAndreas Gohr * strips control characters (<32) from the given string
6802b0b681SAndreas Gohr *
6902b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
70140cfbcdSGerrit Uitslag *
7142ea7f44SGerrit Uitslag * @param string $string being stripped
72140cfbcdSGerrit Uitslag * @return string
7302b0b681SAndreas Gohr */
7402b0b681SAndreas Gohrfunction stripctl($string) {
7502b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
76d5197206Schris}
77d5197206Schris
78d5197206Schris/**
79634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
80634d7150SAndreas Gohr *
81634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
82634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
83634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
8442ea7f44SGerrit Uitslag *
85634d7150SAndreas Gohr * @return  string
86634d7150SAndreas Gohr */
87634d7150SAndreas Gohrfunction getSecurityToken() {
88585bf44eSChristopher Smith    /** @var Input $INPUT */
89585bf44eSChristopher Smith    global $INPUT;
90585bf44eSChristopher Smith    return PassHash::hmac('md5', session_id().$INPUT->server->str('REMOTE_USER'), auth_cookiesalt());
91634d7150SAndreas Gohr}
92634d7150SAndreas Gohr
93634d7150SAndreas Gohr/**
94634d7150SAndreas Gohr * Check the secret CSRF token
95140cfbcdSGerrit Uitslag *
96140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
97140cfbcdSGerrit Uitslag * @return bool success if the token matched
98634d7150SAndreas Gohr */
99634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
100585bf44eSChristopher Smith    /** @var Input $INPUT */
1017d01a0eaSTom N Harris    global $INPUT;
102585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
103df97eaacSAndreas Gohr
1047d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
105634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
106634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
107634d7150SAndreas Gohr        return false;
108634d7150SAndreas Gohr    }
109634d7150SAndreas Gohr    return true;
110634d7150SAndreas Gohr}
111634d7150SAndreas Gohr
112634d7150SAndreas Gohr/**
113634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
114634d7150SAndreas Gohr *
115634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
116140cfbcdSGerrit Uitslag *
117140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
11842ea7f44SGerrit Uitslag * @return string html of hidden form field
119634d7150SAndreas Gohr */
120634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1212404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1223272d797SAndreas Gohr    if($print) echo $ret;
123634d7150SAndreas Gohr    return $ret;
124634d7150SAndreas Gohr}
125634d7150SAndreas Gohr
126634d7150SAndreas Gohr/**
1271015a57dSChristopher Smith * Determine basic information for a request of $id
12815fae107Sandi *
12915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1307e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
131140cfbcdSGerrit Uitslag *
132140cfbcdSGerrit Uitslag * @param string $id         pageid
133140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
134140cfbcdSGerrit Uitslag * @return array with info for a request of $id
135140cfbcdSGerrit Uitslag *
136f3f0262cSandi */
1371015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
138f3f0262cSandi    global $USERINFO;
139585bf44eSChristopher Smith    /* @var Input $INPUT */
140585bf44eSChristopher Smith    global $INPUT;
1416afe8dcaSchris
142c66972f2SAdrian Lang    // set info about manager/admin status.
14359bc3b48SGerrit Uitslag    $info = array();
144c66972f2SAdrian Lang    $info['isadmin']   = false;
145c66972f2SAdrian Lang    $info['ismanager'] = false;
146585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
147f3f0262cSandi        $info['userinfo']   = $USERINFO;
1481015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
149585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
15017ee7f66SAndreas Gohr
151f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
152f8cc712eSAndreas Gohr            $info['isadmin']   = true;
153f8cc712eSAndreas Gohr            $info['ismanager'] = true;
154f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
155f8cc712eSAndreas Gohr            $info['ismanager'] = true;
156f8cc712eSAndreas Gohr        }
157f8cc712eSAndreas Gohr
15817ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
15917ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
160585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
16117ee7f66SAndreas Gohr        }
162ee4c4a1bSAndreas Gohr
163f3f0262cSandi    } else {
1641015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
165ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
166f3f0262cSandi    }
167f3f0262cSandi
1681015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1691015a57dSChristopher Smith
1701015a57dSChristopher Smith    // mobile detection
1711015a57dSChristopher Smith    if ($htmlClient) {
1721015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1731015a57dSChristopher Smith    }
1741015a57dSChristopher Smith
1751015a57dSChristopher Smith    return $info;
1761015a57dSChristopher Smith }
1771015a57dSChristopher Smith
1781015a57dSChristopher Smith/**
1791015a57dSChristopher Smith * Return info about the current document as associative
1801015a57dSChristopher Smith * array.
1811015a57dSChristopher Smith *
1821015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
183140cfbcdSGerrit Uitslag *
184140cfbcdSGerrit Uitslag * @return array with info about current document
1851015a57dSChristopher Smith */
1861015a57dSChristopher Smithfunction pageinfo() {
1871015a57dSChristopher Smith    global $ID;
1881015a57dSChristopher Smith    global $REV;
1891015a57dSChristopher Smith    global $RANGE;
1901015a57dSChristopher Smith    global $lang;
191585bf44eSChristopher Smith    /* @var Input $INPUT */
192585bf44eSChristopher Smith    global $INPUT;
1931015a57dSChristopher Smith
1941015a57dSChristopher Smith    $info = basicinfo($ID);
1951015a57dSChristopher Smith
1961015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1971015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1981015a57dSChristopher Smith    $info['id']  = $ID;
1991015a57dSChristopher Smith    $info['rev'] = $REV;
2001015a57dSChristopher Smith
201585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
2027e87a794SChristopher Smith        $sub = new Subscription();
2037e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
2047e87a794SChristopher Smith    } else {
2057e87a794SChristopher Smith        $info['subscribed'] = false;
2067e87a794SChristopher Smith    }
2077e87a794SChristopher Smith
208f3f0262cSandi    $info['locked']     = checklock($ID);
20900976812SAndreas Gohr    $info['filepath']   = fullpath(wikiFN($ID));
21079e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
21101c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2122ca9d91cSBen Coburn    if($REV) {
2132ca9d91cSBen Coburn        //check if current revision was meant
21401c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
2152ca9d91cSBen Coburn            $REV = '';
2167b3a6803SAndreas Gohr        } elseif($RANGE) {
2177b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2187b3a6803SAndreas Gohr            $REV   = '';
2197b3a6803SAndreas Gohr            $RANGE = '';
2207b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2212ca9d91cSBen Coburn        } else {
2222ca9d91cSBen Coburn            //really use old revision
22300976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID, $REV));
22479e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
225f3f0262cSandi        }
226f3f0262cSandi    }
227c112d578Sandi    $info['rev'] = $REV;
228f3f0262cSandi    if($info['exists']) {
229f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
230f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
231f3f0262cSandi    } else {
232f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
233f3f0262cSandi    }
23450e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
235f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
236f3f0262cSandi
23771726d78SBen Coburn    //load page meta data
23871726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
23971726d78SBen Coburn
240652610a2Sandi    //who's the editor
241047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
242652610a2Sandi    if($REV) {
243f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
244652610a2Sandi    } else {
2450e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
246aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
247aa27cf05SAndreas Gohr        } else {
248f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
249cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
250cd00a034SBen Coburn            if($revinfo !== false) {
251cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
252cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
253cd00a034SBen Coburn            }
254cd00a034SBen Coburn        }
255cd00a034SBen Coburn    }
256cd00a034SBen Coburn    //and check for an external edit
257cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
258cd00a034SBen Coburn        // cached changelog line no longer valid
259cd00a034SBen Coburn        $revinfo                     = false;
260cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
261cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
262652610a2Sandi    }
263bb4866bdSchris
264652610a2Sandi    $info['ip']   = $revinfo['ip'];
265652610a2Sandi    $info['user'] = $revinfo['user'];
266652610a2Sandi    $info['sum']  = $revinfo['sum'];
26771726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
268ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
26959f257aeSchris
27088f522e9Sandi    if($revinfo['user']) {
27188f522e9Sandi        $info['editor'] = $revinfo['user'];
27288f522e9Sandi    } else {
27388f522e9Sandi        $info['editor'] = $revinfo['ip'];
27488f522e9Sandi    }
275652610a2Sandi
276ee4c4a1bSAndreas Gohr    // draft
277ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
27879e79377SAndreas Gohr    if(file_exists($draft)) {
279ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
280ee4c4a1bSAndreas Gohr            // remove stale draft
281ee4c4a1bSAndreas Gohr            @unlink($draft);
282ee4c4a1bSAndreas Gohr        } else {
283ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
284ee4c4a1bSAndreas Gohr        }
285ee4c4a1bSAndreas Gohr    }
286ee4c4a1bSAndreas Gohr
2871015a57dSChristopher Smith    return $info;
2881015a57dSChristopher Smith}
2891015a57dSChristopher Smith
2901015a57dSChristopher Smith/**
2911015a57dSChristopher Smith * Return information about the current media item as an associative array.
292140cfbcdSGerrit Uitslag *
293140cfbcdSGerrit Uitslag * @return array with info about current media item
2941015a57dSChristopher Smith */
2951015a57dSChristopher Smithfunction mediainfo(){
2961015a57dSChristopher Smith    global $NS;
2971015a57dSChristopher Smith    global $IMG;
2981015a57dSChristopher Smith
2991015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3001015a57dSChristopher Smith    $info['image'] = $IMG;
3011c548ebeSAndreas Gohr
302f3f0262cSandi    return $info;
303f3f0262cSandi}
304f3f0262cSandi
305f3f0262cSandi/**
3062684e50aSAndreas Gohr * Build an string of URL parameters
3072684e50aSAndreas Gohr *
3082684e50aSAndreas Gohr * @author Andreas Gohr
309140cfbcdSGerrit Uitslag *
310140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
311140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
312140cfbcdSGerrit Uitslag * @return string query string
3132684e50aSAndreas Gohr */
314b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3152684e50aSAndreas Gohr    $url = '';
3162684e50aSAndreas Gohr    $amp = false;
3172684e50aSAndreas Gohr    foreach($params as $key => $val) {
318b174aeaeSchris        if($amp) $url .= $sep;
3192684e50aSAndreas Gohr
32085e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3213a50618cSgweissbach        $url .= rawurlencode((string) $val);
3222684e50aSAndreas Gohr        $amp = true;
3232684e50aSAndreas Gohr    }
3242684e50aSAndreas Gohr    return $url;
3252684e50aSAndreas Gohr}
3262684e50aSAndreas Gohr
3272684e50aSAndreas Gohr/**
3282684e50aSAndreas Gohr * Build an string of html tag attributes
3292684e50aSAndreas Gohr *
3307bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3317bff22c0SAndreas Gohr *
3322684e50aSAndreas Gohr * @author Andreas Gohr
333140cfbcdSGerrit Uitslag *
334140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
335140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
336140cfbcdSGerrit Uitslag * @return string
3372684e50aSAndreas Gohr */
3384b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3392684e50aSAndreas Gohr    $url   = '';
3409063ec14SAdrian Lang    $white = false;
3412684e50aSAndreas Gohr    foreach($params as $key => $val) {
3427bff22c0SAndreas Gohr        if($key{0} == '_') continue;
343b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3449063ec14SAdrian Lang        if($white) $url .= ' ';
3457bff22c0SAndreas Gohr
3462684e50aSAndreas Gohr        $url .= $key.'="';
3472684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3482684e50aSAndreas Gohr        $url .= '"';
3499063ec14SAdrian Lang        $white = true;
3502684e50aSAndreas Gohr    }
3512684e50aSAndreas Gohr    return $url;
3522684e50aSAndreas Gohr}
3532684e50aSAndreas Gohr
3542684e50aSAndreas Gohr/**
35515fae107Sandi * This builds the breadcrumb trail and returns it as array
35615fae107Sandi *
35715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
358140cfbcdSGerrit Uitslag *
359e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
360f3f0262cSandi */
361f3f0262cSandifunction breadcrumbs() {
3628746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3638746e727Sandi    static $crumbs = null;
3648746e727Sandi    if($crumbs != null) return $crumbs;
3658746e727Sandi
366f3f0262cSandi    global $ID;
367f3f0262cSandi    global $ACT;
368f3f0262cSandi    global $conf;
369f3f0262cSandi
370f3f0262cSandi    //first visit?
371c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
372f3f0262cSandi    //we only save on show and existing wiki documents
373a77f5846Sjan    $file = wikiFN($ID);
37479e79377SAndreas Gohr    if($ACT != 'show' || !file_exists($file)) {
375e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
376f3f0262cSandi        return $crumbs;
377f3f0262cSandi    }
378a77f5846Sjan
379a77f5846Sjan    // page names
3801a84a0f3SAnika Henke    $name = noNSorNS($ID);
381fe9ec250SChris Smith    if(useHeading('navigation')) {
382a77f5846Sjan        // get page title
38367c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
384a77f5846Sjan        if($title) {
385a77f5846Sjan            $name = $title;
386a77f5846Sjan        }
387a77f5846Sjan    }
388a77f5846Sjan
389f3f0262cSandi    //remove ID from array
390a77f5846Sjan    if(isset($crumbs[$ID])) {
391a77f5846Sjan        unset($crumbs[$ID]);
392f3f0262cSandi    }
393f3f0262cSandi
394f3f0262cSandi    //add to array
395a77f5846Sjan    $crumbs[$ID] = $name;
396f3f0262cSandi    //reduce size
397f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
398f3f0262cSandi        array_shift($crumbs);
399f3f0262cSandi    }
400f3f0262cSandi    //save to session
401e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
402f3f0262cSandi    return $crumbs;
403f3f0262cSandi}
404f3f0262cSandi
405f3f0262cSandi/**
40615fae107Sandi * Filter for page IDs
40715fae107Sandi *
408f3f0262cSandi * This is run on a ID before it is outputted somewhere
409f3f0262cSandi * currently used to replace the colon with something else
410907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
411907f24f7SAndreas Gohr *
412907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
413907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
414907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
41515fae107Sandi *
41649c713a3Sandi * Urlencoding is ommitted when the second parameter is false
41749c713a3Sandi *
41815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
419140cfbcdSGerrit Uitslag *
420140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
421140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
422140cfbcdSGerrit Uitslag * @return string
423f3f0262cSandi */
42449c713a3Sandifunction idfilter($id, $ue = true) {
425f3f0262cSandi    global $conf;
426585bf44eSChristopher Smith    /* @var Input $INPUT */
427585bf44eSChristopher Smith    global $INPUT;
428585bf44eSChristopher Smith
429f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
430f3f0262cSandi        $id = strtr($id, ':', '/');
431f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
43258bedc8aSborekb        $conf['userewrite'] &&
433585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4343272d797SAndreas Gohr    ) {
435f3f0262cSandi        $id = strtr($id, ':', ';');
436f3f0262cSandi    }
43749c713a3Sandi    if($ue) {
438b6c6979fSAndreas Gohr        $id = rawurlencode($id);
439f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
440edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
441f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
44249c713a3Sandi    }
443f3f0262cSandi    return $id;
444f3f0262cSandi}
445f3f0262cSandi
446f3f0262cSandi/**
447ed7b5f09Sandi * This builds a link to a wikipage
44815fae107Sandi *
4494bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4506c7843b5Sandi *
45115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4524bc480e5SAndreas Gohr *
4534bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4544bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4554bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4564bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4574bc480e5SAndreas Gohr * @return string
458f3f0262cSandi */
45916f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
460f3f0262cSandi    global $conf;
46116f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
4624bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
4637b62b42dSlisps        if(isset($urlParameters['at']) && $conf['date_at_format']) $urlParameters['at'] = date($conf['date_at_format'],$urlParameters['at']);
46416f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4656de3759aSAndreas Gohr    } else {
46616f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4676de3759aSAndreas Gohr    }
46816f15a81SDominik Eckelmann    if($id === '') {
46916f15a81SDominik Eckelmann        $id = $conf['start'];
47016f15a81SDominik Eckelmann    }
471f3f0262cSandi    $id = idfilter($id);
47216f15a81SDominik Eckelmann    if($absolute) {
473ed7b5f09Sandi        $xlink = DOKU_URL;
474ed7b5f09Sandi    } else {
475ed7b5f09Sandi        $xlink = DOKU_BASE;
476ed7b5f09Sandi    }
477f3f0262cSandi
4786c7843b5Sandi    if($conf['userewrite'] == 2) {
4796c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
48016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4816c7843b5Sandi    } elseif($conf['userewrite']) {
482f3f0262cSandi        $xlink .= $id;
48316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
484bce3726dSAndreas Gohr    } elseif($id) {
4856c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
48616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
487bce3726dSAndreas Gohr    } else {
488bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
48916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
490f3f0262cSandi    }
491f3f0262cSandi
492f3f0262cSandi    return $xlink;
493f3f0262cSandi}
494f3f0262cSandi
495f3f0262cSandi/**
496f5c2808fSBen Coburn * This builds a link to an alternate page format
497f5c2808fSBen Coburn *
498f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
499f5c2808fSBen Coburn *
500f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5014bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5024bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5034bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5044bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5054bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5064bc480e5SAndreas Gohr * @return string
507f5c2808fSBen Coburn */
5084bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
509f5c2808fSBen Coburn    global $conf;
5104bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5114bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
512f5c2808fSBen Coburn    } else {
5134bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
514f5c2808fSBen Coburn    }
515f5c2808fSBen Coburn
516f5c2808fSBen Coburn    $format = rawurlencode($format);
517f5c2808fSBen Coburn    $id     = idfilter($id);
518f5c2808fSBen Coburn    if($abs) {
519f5c2808fSBen Coburn        $xlink = DOKU_URL;
520f5c2808fSBen Coburn    } else {
521f5c2808fSBen Coburn        $xlink = DOKU_BASE;
522f5c2808fSBen Coburn    }
523f5c2808fSBen Coburn
524f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
525f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5264bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
527f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
528f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5294bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
530f5c2808fSBen Coburn    } else {
531f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5324bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
533f5c2808fSBen Coburn    }
534f5c2808fSBen Coburn
535f5c2808fSBen Coburn    return $xlink;
536f5c2808fSBen Coburn}
537f5c2808fSBen Coburn
538f5c2808fSBen Coburn/**
5396de3759aSAndreas Gohr * Build a link to a media file
5406de3759aSAndreas Gohr *
5416de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5428c08db0aSAndreas Gohr *
5438c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5448c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5458c08db0aSAndreas Gohr *
5463272d797SAndreas Gohr * @param string  $id     the media file id or URL
5473272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5483272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5493272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5503272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5513272d797SAndreas Gohr * @return string
5526de3759aSAndreas Gohr */
55355b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5546de3759aSAndreas Gohr    global $conf;
555b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
556826d2766SKlap-in    if(!$isexternalimage) {
557826d2766SKlap-in        $id = cleanID($id);
558826d2766SKlap-in    }
559826d2766SKlap-in
5606de3759aSAndreas Gohr    if(is_array($more)) {
5610f4e0092SChristopher Smith        // add token for resized images
562443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5630f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5640f4e0092SChristopher Smith        }
5658c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5668c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
567443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
568443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5698c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
57078b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
571b174aeaeSchris        $more = buildURLparams($more, $sep);
5726de3759aSAndreas Gohr    } else {
5735e7db1e2SChristopher Smith        $matches = array();
574cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
5755e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
5765e7db1e2SChristopher Smith            foreach ($matches as $match){
5775e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
5785e7db1e2SChristopher Smith            }
579cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
580cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
5815e7db1e2SChristopher Smith        }
5828c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
5838c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
584b174aeaeSchris        $more = str_replace(',', $sep, $more);
5856de3759aSAndreas Gohr    }
5866de3759aSAndreas Gohr
58755b2b31bSAndreas Gohr    if($abs) {
58855b2b31bSAndreas Gohr        $xlink = DOKU_URL;
58955b2b31bSAndreas Gohr    } else {
5906de3759aSAndreas Gohr        $xlink = DOKU_BASE;
59155b2b31bSAndreas Gohr    }
5926de3759aSAndreas Gohr
5936de3759aSAndreas Gohr    // external URLs are always direct without rewriting
594826d2766SKlap-in    if($isexternalimage) {
5956de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
596cc036f74SKlap-in        $xlink .= '?'.$more;
597b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
5986de3759aSAndreas Gohr        return $xlink;
5996de3759aSAndreas Gohr    }
6006de3759aSAndreas Gohr
6016de3759aSAndreas Gohr    $id = idfilter($id);
6026de3759aSAndreas Gohr
6036de3759aSAndreas Gohr    // decide on scriptname
6046de3759aSAndreas Gohr    if($direct) {
6056de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6066de3759aSAndreas Gohr            $script = '_media';
6076de3759aSAndreas Gohr        } else {
6086de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6096de3759aSAndreas Gohr        }
6106de3759aSAndreas Gohr    } else {
6116de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6126de3759aSAndreas Gohr            $script = '_detail';
6136de3759aSAndreas Gohr        } else {
6146de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
6156de3759aSAndreas Gohr        }
6166de3759aSAndreas Gohr    }
6176de3759aSAndreas Gohr
6186de3759aSAndreas Gohr    // build URL based on rewrite mode
6196de3759aSAndreas Gohr    if($conf['userewrite']) {
6206de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6216de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6226de3759aSAndreas Gohr    } else {
6236de3759aSAndreas Gohr        if($more) {
624a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
625b174aeaeSchris            $xlink .= $sep.'media='.$id;
6266de3759aSAndreas Gohr        } else {
627a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6286de3759aSAndreas Gohr        }
6296de3759aSAndreas Gohr    }
6306de3759aSAndreas Gohr
6316de3759aSAndreas Gohr    return $xlink;
6326de3759aSAndreas Gohr}
6336de3759aSAndreas Gohr
6346de3759aSAndreas Gohr/**
63525ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
63615fae107Sandi *
63725ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
63825ca5b17SAndreas Gohr *
63915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
640140cfbcdSGerrit Uitslag *
641140cfbcdSGerrit Uitslag * @return string
642f3f0262cSandi */
64325ca5b17SAndreas Gohrfunction script() {
644ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
645f3f0262cSandi}
646f3f0262cSandi
647f3f0262cSandi/**
64815fae107Sandi * Spamcheck against wordlist
64915fae107Sandi *
650f3f0262cSandi * Checks the wikitext against a list of blocked expressions
651f3f0262cSandi * returns true if the text contains any bad words
65215fae107Sandi *
653e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
654e403cc58SMichael Klier *
655e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
656e403cc58SMichael Klier *  and gain information about the user who was blocked.
657e403cc58SMichael Klier *
658e403cc58SMichael Klier *  Event data:
659e403cc58SMichael Klier *    data['matches']  - array of matches
660e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
661e403cc58SMichael Klier *      [ip]           - ip address
662e403cc58SMichael Klier *      [user]         - username (if logged in)
663e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
664e403cc58SMichael Klier *      [name]         - real name (if logged in)
665e403cc58SMichael Klier *
66615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6676dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
668140cfbcdSGerrit Uitslag *
6696dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6706dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
671f3f0262cSandi */
6726dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
673f3f0262cSandi    global $TEXT;
6746dffa0e0SAndreas Gohr    global $PRE;
6756dffa0e0SAndreas Gohr    global $SUF;
676e0086ca2SAndreas Gohr    global $SUM;
677f3f0262cSandi    global $conf;
678e403cc58SMichael Klier    global $INFO;
679585bf44eSChristopher Smith    /* @var Input $INPUT */
680585bf44eSChristopher Smith    global $INPUT;
681f3f0262cSandi
682f3f0262cSandi    if(!$conf['usewordblock']) return false;
683f3f0262cSandi
684e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
6856dffa0e0SAndreas Gohr
686041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
6876dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
688041d1964SAndreas Gohr
689b9ac8716Schris    $wordblocks = getWordblocks();
6903e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
6913e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
6923e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
6933e2965d7Sandi        // backreferences are used - the maximum is 99
6943e2965d7Sandi        // this is very bad performancewise and may even be too high still
6953e2965d7Sandi        $chunksize = 40;
6963e2965d7Sandi    } else {
697a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
6983e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
699a51d08efSAndreas Gohr        $chunksize = 200;
7003e2965d7Sandi    }
701b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
702f3f0262cSandi        $re = array();
70349eb6e38SAndreas Gohr        // build regexp from blocks
704f3f0262cSandi        foreach($blocks as $block) {
705f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
706f3f0262cSandi            $block = trim($block);
707f3f0262cSandi            if(empty($block)) continue;
708f3f0262cSandi            $re[] = $block;
709f3f0262cSandi        }
710e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
711e403cc58SMichael Klier            // prepare event data
71259bc3b48SGerrit Uitslag            $data = array();
713e403cc58SMichael Klier            $data['matches']        = $matches;
714585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
715585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
716585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
717e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
718e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
719e403cc58SMichael Klier            }
720e403cc58SMichael Klier            $callback = create_function('', 'return true;');
721e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
722b9ac8716Schris        }
723703f6fdeSandi    }
724f3f0262cSandi    return false;
725f3f0262cSandi}
726f3f0262cSandi
727f3f0262cSandi/**
72815fae107Sandi * Return the IP of the client
72915fae107Sandi *
7306d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
73115fae107Sandi *
7326d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7336d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7346d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7356d8affe6SAndreas Gohr * headers
7366d8affe6SAndreas Gohr *
73715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
738140cfbcdSGerrit Uitslag *
7393272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7403272d797SAndreas Gohr * @return string
741f3f0262cSandi */
7426d8affe6SAndreas Gohrfunction clientIP($single = false) {
743585bf44eSChristopher Smith    /* @var Input $INPUT */
744585bf44eSChristopher Smith    global $INPUT;
745585bf44eSChristopher Smith
7466d8affe6SAndreas Gohr    $ip   = array();
747585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
748585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
749585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
750585bf44eSChristopher Smith    }
751585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
752585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
753585bf44eSChristopher Smith    }
7546d8affe6SAndreas Gohr
755dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
756dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
757dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
758dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
759dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
760dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
761dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
762dc14c6d1SGuy Brand    $IPv6Address =
763dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
764dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
765dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
766dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
767dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
768dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
769dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
770dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
771dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
772dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
773dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
774dc14c6d1SGuy Brand
7756d8affe6SAndreas Gohr    // remove any non-IP stuff
7766d8affe6SAndreas Gohr    $cnt   = count($ip);
7774ff28443Schris    $match = array();
7786d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
779dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
7804ff28443Schris            $ip[$i] = $match[0];
7814ff28443Schris        } else {
7824ff28443Schris            $ip[$i] = '';
7834ff28443Schris        }
7846d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
785f3f0262cSandi    }
7866d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
7876d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
7886d8affe6SAndreas Gohr
7896d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
7906d8affe6SAndreas Gohr
7916d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
7926d8affe6SAndreas Gohr    $ip = array_reverse($ip);
7936d8affe6SAndreas Gohr    foreach($ip as $i) {
7942343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
7956d8affe6SAndreas Gohr            continue;
7966d8affe6SAndreas Gohr        } else {
7976d8affe6SAndreas Gohr            return $i;
7986d8affe6SAndreas Gohr        }
7996d8affe6SAndreas Gohr    }
8006d8affe6SAndreas Gohr    // still here? just use the first (last) address
8016d8affe6SAndreas Gohr    return $ip[0];
802f3f0262cSandi}
803f3f0262cSandi
804f3f0262cSandi/**
8051c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8061c548ebeSAndreas Gohr *
8071c548ebeSAndreas Gohr * Adapted from the example code at url below
8081c548ebeSAndreas Gohr *
8091c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
810140cfbcdSGerrit Uitslag *
811140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8121c548ebeSAndreas Gohr */
8131c548ebeSAndreas Gohrfunction clientismobile() {
814585bf44eSChristopher Smith    /* @var Input $INPUT */
815585bf44eSChristopher Smith    global $INPUT;
8161c548ebeSAndreas Gohr
817585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8181c548ebeSAndreas Gohr
819585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8201c548ebeSAndreas Gohr
821585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8221c548ebeSAndreas Gohr
8231c548ebeSAndreas Gohr    $uamatches = 'midp|j2me|avantg|docomo|novarra|palmos|palmsource|240x320|opwv|chtml|pda|windows ce|mmp\/|blackberry|mib\/|symbian|wireless|nokia|hand|mobi|phone|cdm|up\.b|audio|SIE\-|SEC\-|samsung|HTC|mot\-|mitsu|sagem|sony|alcatel|lg|erics|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch|rover|pocket|benq|java|pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|\d\d\di|moto';
8241c548ebeSAndreas Gohr
825585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8261c548ebeSAndreas Gohr
8271c548ebeSAndreas Gohr    return false;
8281c548ebeSAndreas Gohr}
8291c548ebeSAndreas Gohr
8301c548ebeSAndreas Gohr/**
83163211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
83263211f61SGlen Harris *
83322ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
83422ef1e32SAndreas Gohr *
83563211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
836140cfbcdSGerrit Uitslag *
8373272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8383272d797SAndreas Gohr * @return string a comma separated list of hostnames
83963211f61SGlen Harris */
84063211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
84122ef1e32SAndreas Gohr    global $conf;
84222ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
84322ef1e32SAndreas Gohr
84463211f61SGlen Harris    $hosts = array();
84563211f61SGlen Harris    $ips   = explode(',', $ips);
846551a720fSMichael Klier
847551a720fSMichael Klier    if(is_array($ips)) {
8483886270dSAndreas Gohr        foreach($ips as $ip) {
849551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
85063211f61SGlen Harris        }
851551a720fSMichael Klier        return join(',', $hosts);
852551a720fSMichael Klier    } else {
853551a720fSMichael Klier        return gethostbyaddr(trim($ips));
854551a720fSMichael Klier    }
85563211f61SGlen Harris}
85663211f61SGlen Harris
85763211f61SGlen Harris/**
85815fae107Sandi * Checks if a given page is currently locked.
85915fae107Sandi *
860f3f0262cSandi * removes stale lockfiles
86115fae107Sandi *
86215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
863140cfbcdSGerrit Uitslag *
864140cfbcdSGerrit Uitslag * @param string $id page id
865140cfbcdSGerrit Uitslag * @return bool page is locked?
866f3f0262cSandi */
867f3f0262cSandifunction checklock($id) {
868f3f0262cSandi    global $conf;
869585bf44eSChristopher Smith    /* @var Input $INPUT */
870585bf44eSChristopher Smith    global $INPUT;
871585bf44eSChristopher Smith
872c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
873f3f0262cSandi
874f3f0262cSandi    //no lockfile
87579e79377SAndreas Gohr    if(!file_exists($lock)) return false;
876f3f0262cSandi
877f3f0262cSandi    //lockfile expired
878f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
879d8186216SBen Coburn        @unlink($lock);
880f3f0262cSandi        return false;
881f3f0262cSandi    }
882f3f0262cSandi
883f3f0262cSandi    //my own lock
8846d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
8850712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
886f3f0262cSandi        return false;
887f3f0262cSandi    }
888f3f0262cSandi
889f3f0262cSandi    return $ip;
890f3f0262cSandi}
891f3f0262cSandi
892f3f0262cSandi/**
89315fae107Sandi * Lock a page for editing
89415fae107Sandi *
89515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
896140cfbcdSGerrit Uitslag *
897140cfbcdSGerrit Uitslag * @param string $id page id to lock
898f3f0262cSandi */
899f3f0262cSandifunction lock($id) {
900544ed901SDaniel Calviño Sánchez    global $conf;
901585bf44eSChristopher Smith    /* @var Input $INPUT */
902585bf44eSChristopher Smith    global $INPUT;
903544ed901SDaniel Calviño Sánchez
904544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
905544ed901SDaniel Calviño Sánchez        return;
906544ed901SDaniel Calviño Sánchez    }
907544ed901SDaniel Calviño Sánchez
908c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
909585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
910585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
911f3f0262cSandi    } else {
91285fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
913f3f0262cSandi    }
914f3f0262cSandi}
915f3f0262cSandi
916f3f0262cSandi/**
91715fae107Sandi * Unlock a page if it was locked by the user
918f3f0262cSandi *
91915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
920140cfbcdSGerrit Uitslag *
9213272d797SAndreas Gohr * @param string $id page id to unlock
92215fae107Sandi * @return bool true if a lock was removed
923f3f0262cSandi */
924f3f0262cSandifunction unlock($id) {
925585bf44eSChristopher Smith    /* @var Input $INPUT */
926585bf44eSChristopher Smith    global $INPUT;
927585bf44eSChristopher Smith
928c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
92979e79377SAndreas Gohr    if(file_exists($lock)) {
9306d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
931585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
932f3f0262cSandi            @unlink($lock);
933f3f0262cSandi            return true;
934f3f0262cSandi        }
935f3f0262cSandi    }
936f3f0262cSandi    return false;
937f3f0262cSandi}
938f3f0262cSandi
939f3f0262cSandi/**
940f3f0262cSandi * convert line ending to unix format
941f3f0262cSandi *
9426db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9436db7468bSAndreas Gohr *
94415fae107Sandi * @see    formText() for 2crlf conversion
94515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
946140cfbcdSGerrit Uitslag *
947140cfbcdSGerrit Uitslag * @param string $text
948140cfbcdSGerrit Uitslag * @return string
949f3f0262cSandi */
950f3f0262cSandifunction cleanText($text) {
951f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9526db7468bSAndreas Gohr
9536db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9546db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9556db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9566db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
9576db7468bSAndreas Gohr
958f3f0262cSandi    return $text;
959f3f0262cSandi}
960f3f0262cSandi
961f3f0262cSandi/**
962f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
963f3f0262cSandi * It also converts line endings to Windows format which is
964f3f0262cSandi * pseudo standard for webforms.
965f3f0262cSandi *
96615fae107Sandi * @see    cleanText() for 2unix conversion
96715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
968140cfbcdSGerrit Uitslag *
969140cfbcdSGerrit Uitslag * @param string $text
970140cfbcdSGerrit Uitslag * @return string
971f3f0262cSandi */
972f3f0262cSandifunction formText($text) {
9735b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
974f3f0262cSandi    return htmlspecialchars($text);
975f3f0262cSandi}
976f3f0262cSandi
977f3f0262cSandi/**
97815fae107Sandi * Returns the specified local text in raw format
97915fae107Sandi *
98015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
981140cfbcdSGerrit Uitslag *
982140cfbcdSGerrit Uitslag * @param string $id   page id
983140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
984140cfbcdSGerrit Uitslag * @return string
985f3f0262cSandi */
9862adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
9872adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
988f3f0262cSandi}
989f3f0262cSandi
990f3f0262cSandi/**
991f3f0262cSandi * Returns the raw WikiText
99215fae107Sandi *
99315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
994140cfbcdSGerrit Uitslag *
995140cfbcdSGerrit Uitslag * @param string $id   page id
996e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
997140cfbcdSGerrit Uitslag * @return string
998f3f0262cSandi */
999f3f0262cSandifunction rawWiki($id, $rev = '') {
1000cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1001f3f0262cSandi}
1002f3f0262cSandi
1003f3f0262cSandi/**
10047146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10057146cee2SAndreas Gohr *
10067b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10077146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1008140cfbcdSGerrit Uitslag *
1009140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1010140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10117146cee2SAndreas Gohr */
1012fe17917eSAdrian Langfunction pageTemplate($id) {
1013a15ce62dSEsther Brunner    global $conf;
1014e29549feSAndreas Gohr
1015fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1016e29549feSAndreas Gohr
10177b84afa2SAndreas Gohr    // prepare initial event data
10187b84afa2SAndreas Gohr    $data = array(
10197b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10207b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10217b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10227b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10237b84afa2SAndreas Gohr    );
10247b84afa2SAndreas Gohr
10257b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10267b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10277b84afa2SAndreas Gohr        // the before event might have loaded the content already
10287b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10297b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10307b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1031fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
103279e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10337b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1034e29549feSAndreas Gohr                } else {
1035e29549feSAndreas Gohr                    // search upper namespaces for templates
1036e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1037e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
103879e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10397b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1040e29549feSAndreas Gohr                            break;
1041e29549feSAndreas Gohr                        }
1042e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1043e29549feSAndreas Gohr                    }
1044e29549feSAndreas Gohr                }
10457b84afa2SAndreas Gohr            }
10467b84afa2SAndreas Gohr            // load the content
10473d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10487b84afa2SAndreas Gohr        }
1049a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10507b84afa2SAndreas Gohr    }
10517b84afa2SAndreas Gohr    $evt->advise_after();
10527b84afa2SAndreas Gohr    unset($evt);
10537b84afa2SAndreas Gohr
1054fe17917eSAdrian Lang    return $data['tpl'];
10552b1223ecSAdrian Lang}
10562b1223ecSAdrian Lang
10572b1223ecSAdrian Lang/**
10582b1223ecSAdrian Lang * Performs common page template replacements
10597b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10602b1223ecSAdrian Lang *
10612b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1062140cfbcdSGerrit Uitslag *
1063140cfbcdSGerrit Uitslag * @param array $data array with event data
1064140cfbcdSGerrit Uitslag * @return string
10652b1223ecSAdrian Lang */
1066d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
10673272d797SAndreas Gohr    /**
10683272d797SAndreas Gohr     * @var string $id        the id of the page to be created
10693272d797SAndreas Gohr     * @var string $tpl       the text used as template
10703272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
10713272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
10723272d797SAndreas Gohr     */
1073fe17917eSAdrian Lang    extract($data);
1074fe17917eSAdrian Lang
1075b856f7dfSAdrian Lang    global $USERINFO;
1076bce53b1fSAdrian Lang    global $conf;
1077585bf44eSChristopher Smith    /* @var Input $INPUT */
1078585bf44eSChristopher Smith    global $INPUT;
1079e29549feSAndreas Gohr
1080e29549feSAndreas Gohr    // replace placeholders
108126ece5a7SAndreas Gohr    $file = noNS($id);
108237c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
108326ece5a7SAndreas Gohr
10843272d797SAndreas Gohr    $tpl = str_replace(
10853272d797SAndreas Gohr        array(
108626ece5a7SAndreas Gohr             '@ID@',
108726ece5a7SAndreas Gohr             '@NS@',
108826ece5a7SAndreas Gohr             '@FILE@',
108926ece5a7SAndreas Gohr             '@!FILE@',
109026ece5a7SAndreas Gohr             '@!FILE!@',
109126ece5a7SAndreas Gohr             '@PAGE@',
109226ece5a7SAndreas Gohr             '@!PAGE@',
109326ece5a7SAndreas Gohr             '@!!PAGE@',
109426ece5a7SAndreas Gohr             '@!PAGE!@',
109526ece5a7SAndreas Gohr             '@USER@',
109626ece5a7SAndreas Gohr             '@NAME@',
109726ece5a7SAndreas Gohr             '@MAIL@',
109826ece5a7SAndreas Gohr             '@DATE@',
109926ece5a7SAndreas Gohr        ),
110026ece5a7SAndreas Gohr        array(
110126ece5a7SAndreas Gohr             $id,
110226ece5a7SAndreas Gohr             getNS($id),
110326ece5a7SAndreas Gohr             $file,
110426ece5a7SAndreas Gohr             utf8_ucfirst($file),
110526ece5a7SAndreas Gohr             utf8_strtoupper($file),
110626ece5a7SAndreas Gohr             $page,
110726ece5a7SAndreas Gohr             utf8_ucfirst($page),
110826ece5a7SAndreas Gohr             utf8_ucwords($page),
110926ece5a7SAndreas Gohr             utf8_strtoupper($page),
1110585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1111b856f7dfSAdrian Lang             $USERINFO['name'],
1112b856f7dfSAdrian Lang             $USERINFO['mail'],
111326ece5a7SAndreas Gohr             $conf['dformat'],
11143272d797SAndreas Gohr        ), $tpl
11153272d797SAndreas Gohr    );
111626ece5a7SAndreas Gohr
11177d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
11187d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
1119d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1120a15ce62dSEsther Brunner    return $tpl;
11217146cee2SAndreas Gohr}
11227146cee2SAndreas Gohr
11237146cee2SAndreas Gohr/**
112415fae107Sandi * Returns the raw Wiki Text in three slices.
112515fae107Sandi *
112615fae107Sandi * The range parameter needs to have the form "from-to"
112715cfe303Sandi * and gives the range of the section in bytes - no
112815cfe303Sandi * UTF-8 awareness is needed.
1129f3f0262cSandi * The returned order is prefix, section and suffix.
113015fae107Sandi *
113115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1132140cfbcdSGerrit Uitslag *
1133140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1134140cfbcdSGerrit Uitslag * @param string $id    page id
1135140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
113642ea7f44SGerrit Uitslag * @return string[] with three slices
1137f3f0262cSandi */
1138f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1139cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1140f3f0262cSandi
114180fcb268SAdrian Lang    // Parse range
114280fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
114380fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
114480fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
114580fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
114680fcb268SAdrian Lang
114759bc3b48SGerrit Uitslag    $slices = array();
114880fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
114980fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
115015cfe303Sandi    $slices[2] = substr($text, $to);
1151f3f0262cSandi    return $slices;
1152f3f0262cSandi}
1153f3f0262cSandi
1154f3f0262cSandi/**
115515fae107Sandi * Joins wiki text slices
115615fae107Sandi *
115780fcb268SAdrian Lang * function to join the text slices.
1158f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1159f3f0262cSandi * lines between sections if needed (used on saving).
116015fae107Sandi *
116115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1162140cfbcdSGerrit Uitslag *
1163140cfbcdSGerrit Uitslag * @param string $pre   prefix
1164140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1165140cfbcdSGerrit Uitslag * @param string $suf   suffix
1166140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1167140cfbcdSGerrit Uitslag * @return string
1168f3f0262cSandi */
1169f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1170f3f0262cSandi    if($pretty) {
117180fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
11723272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
11733272d797SAndreas Gohr        ) {
117480fcb268SAdrian Lang            $pre .= "\n";
117580fcb268SAdrian Lang        }
117680fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
11773272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
11783272d797SAndreas Gohr        ) {
117980fcb268SAdrian Lang            $text .= "\n";
118080fcb268SAdrian Lang        }
1181f3f0262cSandi    }
1182f3f0262cSandi
1183f3f0262cSandi    return $pre.$text.$suf;
1184f3f0262cSandi}
1185f3f0262cSandi
1186f3f0262cSandi/**
1187a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1188a701424fSBen Coburn * Also directs changelog and attic updates.
118915fae107Sandi *
119015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
119171726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1192140cfbcdSGerrit Uitslag *
1193140cfbcdSGerrit Uitslag * @param string $id       page id
1194140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1195140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1196140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1197f3f0262cSandi */
1198b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1199a701424fSBen Coburn    /* Note to developers:
1200a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1201a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1202a701424fSBen Coburn       after any changes. External edits change the wiki page
1203a701424fSBen Coburn       directly without using php or dokuwiki.
1204a701424fSBen Coburn     */
1205f3f0262cSandi    global $conf;
1206f3f0262cSandi    global $lang;
120771726d78SBen Coburn    global $REV;
1208585bf44eSChristopher Smith    /* @var Input $INPUT */
1209585bf44eSChristopher Smith    global $INPUT;
1210585bf44eSChristopher Smith
1211f3f0262cSandi    // ignore if no changes were made
1212f3f0262cSandi    if($text == rawWiki($id, '')) {
1213f3f0262cSandi        return;
1214f3f0262cSandi    }
1215f3f0262cSandi
1216f3f0262cSandi    $file        = wikiFN($id);
1217a701424fSBen Coburn    $old         = @filemtime($file); // from page
1218407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
121979e79377SAndreas Gohr    $wasCreated  = !file_exists($file);
122071726d78SBen Coburn    $wasReverted = ($REV == true);
1221047bad06SGerrit Uitslag    $pagelog     = new PageChangeLog($id, 1024);
1222e45b34cdSBen Coburn    $newRev      = false;
1223f523c971SGerrit Uitslag    $oldRev      = $pagelog->getRevisions(-1, 1); // from changelog
1224a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
122579e79377SAndreas Gohr    if(!file_exists(wikiFN($id, $old)) && file_exists($file) && $old >= $oldRev) {
122646844156SBen Coburn        // add old revision to the attic if missing
122746844156SBen Coburn        saveOldRevision($id);
122846844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1229a701424fSBen Coburn        if($old > $oldRev) {
1230ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
123146844156SBen Coburn            // remove soon to be stale instructions
123246844156SBen Coburn            $cache = new cache_instructions($id, $file);
123346844156SBen Coburn            $cache->removeCache();
123446844156SBen Coburn        }
123546844156SBen Coburn    }
1236f3f0262cSandi
123771726d78SBen Coburn    if($wasRemoved) {
123830725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
123930725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
124030725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1241e45b34cdSBen Coburn        // pre-save deleted revision
1242e45b34cdSBen Coburn        @touch($file);
124346844156SBen Coburn        clearstatcache();
1244e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1245e1f3d9e1SEsther Brunner        // remove empty file
1246f3f0262cSandi        @unlink($file);
1247c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1248c5f92742SMichael Hamann        // purge non-persistant meta data
12493d1f9ec3SMichael Klier        p_purge_metadata($id);
1250f3f0262cSandi        $del = true;
12513ce054b3Sandi        // autoset summary on deletion
12523ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
125353d6ccfeSandi        // remove empty namespaces
1254cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1255cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1256f3f0262cSandi    } else {
1257cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1258cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
125946844156SBen Coburn        // pre-save the revision, to keep the attic in sync
126046844156SBen Coburn        $newRev = saveOldRevision($id);
1261f3f0262cSandi        $del    = false;
1262f3f0262cSandi    }
1263f3f0262cSandi
126471726d78SBen Coburn    // select changelog line type
126571726d78SBen Coburn    $extra = '';
1266ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
126771726d78SBen Coburn    if($wasReverted) {
1268ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
126971726d78SBen Coburn        $extra = $REV;
12703272d797SAndreas Gohr    } else if($wasCreated) {
12713272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
12723272d797SAndreas Gohr    } else if($wasRemoved) {
12733272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
1274585bf44eSChristopher Smith    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
12753272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
12763272d797SAndreas Gohr    } //minor edits only for logged in users
127771726d78SBen Coburn
1278e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
127926a0801fSAndreas Gohr    // send notify mails
128090033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
128190033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1282f3f0262cSandi
1283ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
128498407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
12852eccbdaaSGina Haeussge
12862eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1287fe9ec250SChris Smith    if(useHeading('content')) {
128807ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12892eccbdaaSGina Haeussge        foreach($pages as $page) {
12902eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
12912eccbdaaSGina Haeussge            $cache->removeCache();
12922eccbdaaSGina Haeussge        }
12932eccbdaaSGina Haeussge    }
1294f3f0262cSandi}
1295f3f0262cSandi
1296f3f0262cSandi/**
1297f3f0262cSandi * moves the current version to the attic and returns its
1298f3f0262cSandi * revision date
129915fae107Sandi *
130015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1301140cfbcdSGerrit Uitslag *
1302140cfbcdSGerrit Uitslag * @param string $id page id
1303140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1304f3f0262cSandi */
1305f3f0262cSandifunction saveOldRevision($id) {
1306f3f0262cSandi    $oldf = wikiFN($id);
130779e79377SAndreas Gohr    if(!file_exists($oldf)) return '';
1308f3f0262cSandi    $date = filemtime($oldf);
1309f3f0262cSandi    $newf = wikiFN($id, $date);
1310cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1311f3f0262cSandi    return $date;
1312f3f0262cSandi}
1313f3f0262cSandi
1314f3f0262cSandi/**
1315fde10de4SAdrian Lang * Sends a notify mail on page change or registration
131626a0801fSAndreas Gohr *
131726a0801fSAndreas Gohr * @param string     $id       The changed page
1318fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
13193272d797SAndreas Gohr * @param int|string $rev Old page revision
132026a0801fSAndreas Gohr * @param string     $summary  What changed
132190033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
132242ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
13233272d797SAndreas Gohr * @return bool
1324140cfbcdSGerrit Uitslag *
132515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1326f3f0262cSandi */
132702a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1328f3f0262cSandi    global $conf;
1329585bf44eSChristopher Smith    /* @var Input $INPUT */
1330585bf44eSChristopher Smith    global $INPUT;
1331b158d625SSteven Danz
13326df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
133326a0801fSAndreas Gohr    if($who == 'admin') {
13343272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
13352ed38036SAndreas Gohr        $tpl = 'mailtext';
133626a0801fSAndreas Gohr        $to  = $conf['notify'];
133726a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
133884c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1339585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
13400bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
13413272d797SAndreas Gohr        trigger_event(
13423272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1343835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
13443272d797SAndreas Gohr        );
13452ed38036SAndreas Gohr        $to = $data['addresslist'];
13462ed38036SAndreas Gohr        if(empty($to)) return false;
13472ed38036SAndreas Gohr        $tpl = 'subscr_single';
134826a0801fSAndreas Gohr    } else {
13493272d797SAndreas Gohr        return false; //just to be safe
135026a0801fSAndreas Gohr    }
135126a0801fSAndreas Gohr
13526df843eeSAndreas Gohr    // prepare content
13532ed38036SAndreas Gohr    $subscription = new Subscription();
13542ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1355f3f0262cSandi}
13562ed38036SAndreas Gohr
135715fae107Sandi/**
135871f7bde7SAndreas Gohr * extracts the query from a search engine referrer
135915fae107Sandi *
136015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
136171f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1362140cfbcdSGerrit Uitslag *
1363140cfbcdSGerrit Uitslag * @return array|string
1364f3f0262cSandi */
1365f3f0262cSandifunction getGoogleQuery() {
1366585bf44eSChristopher Smith    /* @var Input $INPUT */
1367585bf44eSChristopher Smith    global $INPUT;
1368585bf44eSChristopher Smith
1369585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1370c66972f2SAdrian Lang        return '';
1371c66972f2SAdrian Lang    }
1372585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1373f3f0262cSandi
1374079b3ac1SAndreas Gohr    // only handle common SEs
1375079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1376e4d8a516SKazutaka Miyasaka
1377079b3ac1SAndreas Gohr    $query = array();
1378e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1379e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1380e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1381f3f0262cSandi    parse_str($url['query'], $query);
1382e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1383e4d8a516SKazutaka Miyasaka
1384c66972f2SAdrian Lang    $q = '';
1385079b3ac1SAndreas Gohr    if(isset($query['q'])){
1386079b3ac1SAndreas Gohr        $q = $query['q'];
1387079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1388079b3ac1SAndreas Gohr        $q = $query['p'];
1389079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1390079b3ac1SAndreas Gohr        $q = $query['query'];
1391079b3ac1SAndreas Gohr    }
1392079b3ac1SAndreas Gohr    $q = trim($q);
1393f3f0262cSandi
1394079b3ac1SAndreas Gohr    if(!$q) return '';
13956531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1396f93b3b50SAndreas Gohr    return $q;
1397f3f0262cSandi}
1398f3f0262cSandi
1399f3f0262cSandi/**
1400f3f0262cSandi * Return the human readable size of a file
1401f3f0262cSandi *
1402f3f0262cSandi * @param int $size A file size
1403f3f0262cSandi * @param int $dec A number of decimal places
140474160ca1SGerrit Uitslag * @return string human readable size
1405140cfbcdSGerrit Uitslag *
1406f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1407f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1408f3f0262cSandi * @version     1.0.0
1409f3f0262cSandi */
1410f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1411f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1412f3f0262cSandi    $count = count($sizes);
1413f3f0262cSandi    $i     = 0;
1414f3f0262cSandi
1415f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1416f3f0262cSandi        $size /= 1024;
1417f3f0262cSandi        $i++;
1418f3f0262cSandi    }
1419f3f0262cSandi
1420f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1421f3f0262cSandi}
1422f3f0262cSandi
142315fae107Sandi/**
1424c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1425c57e365eSAndreas Gohr *
1426c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1427140cfbcdSGerrit Uitslag *
1428140cfbcdSGerrit Uitslag * @param int $dt timestamp
1429140cfbcdSGerrit Uitslag * @return string
1430c57e365eSAndreas Gohr */
1431c57e365eSAndreas Gohrfunction datetime_h($dt) {
1432c57e365eSAndreas Gohr    global $lang;
1433c57e365eSAndreas Gohr
1434c57e365eSAndreas Gohr    $ago = time() - $dt;
1435c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1436c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1437c57e365eSAndreas Gohr    }
1438c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1439c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1440c57e365eSAndreas Gohr    }
1441c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1442c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1443c57e365eSAndreas Gohr    }
1444c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1445c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1446c57e365eSAndreas Gohr    }
1447c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1448c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1449c57e365eSAndreas Gohr    }
1450c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1451c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1452c57e365eSAndreas Gohr    }
1453c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1454c57e365eSAndreas Gohr}
1455c57e365eSAndreas Gohr
1456c57e365eSAndreas Gohr/**
1457f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1458f2263577SAndreas Gohr *
1459f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1460f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1461f2263577SAndreas Gohr *
1462f2263577SAndreas Gohr * @see datetime_h
1463f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1464140cfbcdSGerrit Uitslag *
1465140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1466140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1467140cfbcdSGerrit Uitslag * @return string
1468f2263577SAndreas Gohr */
1469f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1470f2263577SAndreas Gohr    global $conf;
1471f2263577SAndreas Gohr
1472f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1473f2263577SAndreas Gohr    $dt = (int) $dt;
1474f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1475f2263577SAndreas Gohr
1476f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1477f2263577SAndreas Gohr    return strftime($format, $dt);
1478f2263577SAndreas Gohr}
1479f2263577SAndreas Gohr
1480f2263577SAndreas Gohr/**
1481c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1482c4f79b71SMichael Hamann *
1483c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1484c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
1485140cfbcdSGerrit Uitslag *
14867e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
14873272d797SAndreas Gohr * @return string
1488c4f79b71SMichael Hamann */
1489c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1490c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1491c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1492c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1493c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1494c4f79b71SMichael Hamann    return $date_mod;
1495c4f79b71SMichael Hamann}
1496c4f79b71SMichael Hamann
1497c4f79b71SMichael Hamann/**
149800a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
149900a7b5adSEsther Brunner *
150000a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
150100a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1502140cfbcdSGerrit Uitslag *
1503140cfbcdSGerrit Uitslag * @param string $email email address
1504140cfbcdSGerrit Uitslag * @return string
150500a7b5adSEsther Brunner */
150600a7b5adSEsther Brunnerfunction obfuscate($email) {
150700a7b5adSEsther Brunner    global $conf;
150800a7b5adSEsther Brunner
150900a7b5adSEsther Brunner    switch($conf['mailguard']) {
151000a7b5adSEsther Brunner        case 'visible' :
151100a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
151200a7b5adSEsther Brunner            return strtr($email, $obfuscate);
151300a7b5adSEsther Brunner
151400a7b5adSEsther Brunner        case 'hex' :
151500a7b5adSEsther Brunner            $encode = '';
151649eb6e38SAndreas Gohr            $len    = strlen($email);
151749eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
151849eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
151949eb6e38SAndreas Gohr            }
152000a7b5adSEsther Brunner            return $encode;
152100a7b5adSEsther Brunner
152200a7b5adSEsther Brunner        case 'none' :
152300a7b5adSEsther Brunner        default :
152400a7b5adSEsther Brunner            return $email;
152500a7b5adSEsther Brunner    }
152600a7b5adSEsther Brunner}
152700a7b5adSEsther Brunner
152800a7b5adSEsther Brunner/**
152989541d4bSAndreas Gohr * Removes quoting backslashes
153089541d4bSAndreas Gohr *
153189541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1532140cfbcdSGerrit Uitslag *
1533140cfbcdSGerrit Uitslag * @param string $string
1534140cfbcdSGerrit Uitslag * @param string $char backslashed character
1535140cfbcdSGerrit Uitslag * @return string
153689541d4bSAndreas Gohr */
153789541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
153889541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
153989541d4bSAndreas Gohr}
154089541d4bSAndreas Gohr
154173038c47SAndreas Gohr/**
154273038c47SAndreas Gohr * Convert php.ini shorthands to byte
154373038c47SAndreas Gohr *
154473038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
154573038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
1546140cfbcdSGerrit Uitslag *
1547140cfbcdSGerrit Uitslag * @param string $v shorthands
1548140cfbcdSGerrit Uitslag * @return int|string
154973038c47SAndreas Gohr */
155073038c47SAndreas Gohrfunction php_to_byte($v) {
155173038c47SAndreas Gohr    $l   = substr($v, -1);
155273038c47SAndreas Gohr    $ret = substr($v, 0, -1);
155373038c47SAndreas Gohr    switch(strtoupper($l)) {
155474160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
155573038c47SAndreas Gohr        case 'P':
155673038c47SAndreas Gohr            $ret *= 1024;
155774160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
155873038c47SAndreas Gohr        case 'T':
155973038c47SAndreas Gohr            $ret *= 1024;
156074160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
156173038c47SAndreas Gohr        case 'G':
156273038c47SAndreas Gohr            $ret *= 1024;
156374160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
156473038c47SAndreas Gohr        case 'M':
156573038c47SAndreas Gohr            $ret *= 1024;
1566f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
156773038c47SAndreas Gohr        case 'K':
156873038c47SAndreas Gohr            $ret *= 1024;
156973038c47SAndreas Gohr            break;
157049cbd23eSOtto Vainio        default;
157149cbd23eSOtto Vainio            $ret *= 10;
157249cbd23eSOtto Vainio            break;
157373038c47SAndreas Gohr    }
157473038c47SAndreas Gohr    return $ret;
157573038c47SAndreas Gohr}
157673038c47SAndreas Gohr
1577546d3a99SAndreas Gohr/**
1578546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1579140cfbcdSGerrit Uitslag *
1580140cfbcdSGerrit Uitslag * @param string $string
1581140cfbcdSGerrit Uitslag * @return string
1582546d3a99SAndreas Gohr */
1583546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1584546d3a99SAndreas Gohr    return preg_quote($string, '/');
1585546d3a99SAndreas Gohr}
158673038c47SAndreas Gohr
1587bd2f6c2fSAndreas Gohr/**
1588bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1589bd2f6c2fSAndreas Gohr *
1590c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1591bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1592bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1593bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1594bd2f6c2fSAndreas Gohr *
1595bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1596bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1597bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1598bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1599bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
16003272d797SAndreas Gohr * @return string
1601bd2f6c2fSAndreas Gohr */
1602a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1603bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1604bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1605bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1606bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1607bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1608bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1609bd2f6c2fSAndreas Gohr}
1610bd2f6c2fSAndreas Gohr
1611dc58b6f4SAndy Webber/**
1612dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1613dc58b6f4SAndy Webber * in page footer and recent changes pages
1614dc58b6f4SAndy Webber *
1615b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
161615f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1617c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
161815f3bc49SGerrit Uitslag *
1619dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1620dc58b6f4SAndy Webber */
162115f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1622cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1623dc58b6f4SAndy Webber}
1624dc58b6f4SAndy Webber
162560a396c8SGerrit Uitslag/**
162660a396c8SGerrit Uitslag * Returns users realname w/o link
162760a396c8SGerrit Uitslag *
1628f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
162915f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1630c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
163160a396c8SGerrit Uitslag *
163260a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
163360a396c8SGerrit Uitslag */
1634cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
163560a396c8SGerrit Uitslag    global $conf, $INFO;
163660a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
163760a396c8SGerrit Uitslag    global $auth;
163830f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
163930f6ec4bSGerrit Uitslag    global $INPUT;
164060a396c8SGerrit Uitslag
164160a396c8SGerrit Uitslag    // prepare initial event data
164260a396c8SGerrit Uitslag    $data = array(
164360a396c8SGerrit Uitslag        'username' => $username, // the unique user name
164460a396c8SGerrit Uitslag        'name' => '',
164560a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
164660a396c8SGerrit Uitslag                         'target' => '',
164760a396c8SGerrit Uitslag                         'pre' => '',
164860a396c8SGerrit Uitslag                         'suf' => '',
164960a396c8SGerrit Uitslag                         'style' => '',
165060a396c8SGerrit Uitslag                         'more' => '',
165160a396c8SGerrit Uitslag                         'url' => '',
165260a396c8SGerrit Uitslag                         'title' => '',
165360a396c8SGerrit Uitslag                         'class' => ''
165460a396c8SGerrit Uitslag        ),
16554d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
165615f3bc49SGerrit Uitslag        'textonly' => $textonly
165760a396c8SGerrit Uitslag    );
165862c8004eSGerrit Uitslag    if($username === null) {
165930f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
166015f3bc49SGerrit Uitslag        if($textonly){
166115f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
166215f3bc49SGerrit Uitslag        }else {
166330f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
166460a396c8SGerrit Uitslag        }
166515f3bc49SGerrit Uitslag    }
166660a396c8SGerrit Uitslag
166760a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
166860a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
166960a396c8SGerrit Uitslag        if(empty($data['name'])) {
167060a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
167165833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1672dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1673dc58b6f4SAndy Webber                    case 'username':
16747f081821SGerrit Uitslag                    case 'username_link':
167515f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
167660a396c8SGerrit Uitslag                        break;
1677dc58b6f4SAndy Webber                    case 'email':
1678dc58b6f4SAndy Webber                    case 'email_link':
167960a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
168060a396c8SGerrit Uitslag                        break;
1681dc58b6f4SAndy Webber                }
168265833968SGerrit Uitslag            } else {
168365833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
168460a396c8SGerrit Uitslag            }
168560a396c8SGerrit Uitslag        }
16867f081821SGerrit Uitslag
16877f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16887f081821SGerrit Uitslag        static $xhtml_renderer = null;
16897f081821SGerrit Uitslag
169015f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
16917f081821SGerrit Uitslag
16927f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
169360a396c8SGerrit Uitslag                if(!isset($info)) {
169460a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
169560a396c8SGerrit Uitslag                }
169660a396c8SGerrit Uitslag                if(isset($info) && $info) {
16977f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
169860a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1699dc58b6f4SAndy Webber                    } else {
17007f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
17017f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
17027f081821SGerrit Uitslag                        }
17037f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
17047f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
17057f081821SGerrit Uitslag                        }
17067f081821SGerrit Uitslag                        $shortcut = 'user';
1707533772e1SGerrit Uitslag                        $exists = null;
17086496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
17092a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
17106496c33fSGerrit Uitslag                        if($exists !== null) {
17116496c33fSGerrit Uitslag                            if($exists) {
17126496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17136496c33fSGerrit Uitslag                            } else {
17146496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17156496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17166496c33fSGerrit Uitslag                            }
17176496c33fSGerrit Uitslag                        }
1718dc58b6f4SAndy Webber                    }
1719dc58b6f4SAndy Webber                } else {
172015f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1721dc58b6f4SAndy Webber                }
172260a396c8SGerrit Uitslag
172360a396c8SGerrit Uitslag            } else {
172415f3bc49SGerrit Uitslag                $data['textonly'] = true;
172560a396c8SGerrit Uitslag            }
172660a396c8SGerrit Uitslag        }
172760a396c8SGerrit Uitslag
172815f3bc49SGerrit Uitslag        if($data['textonly']) {
17294d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
173060a396c8SGerrit Uitslag        } else {
173160a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
173260a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
173360a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
173460a396c8SGerrit Uitslag            }
17354d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
173660a396c8SGerrit Uitslag        }
173760a396c8SGerrit Uitslag    }
173860a396c8SGerrit Uitslag    $evt->advise_after();
173960a396c8SGerrit Uitslag    unset($evt);
174060a396c8SGerrit Uitslag
17414d5fc927SGerrit Uitslag    return $data['userlink'];
1742066fee30SAndreas Gohr}
1743066fee30SAndreas Gohr
1744066fee30SAndreas Gohr/**
1745066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1746066fee30SAndreas Gohr * When no image exists, returns an empty string
1747066fee30SAndreas Gohr *
1748066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1749140cfbcdSGerrit Uitslag *
1750066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17513272d797SAndreas Gohr * @return string
1752066fee30SAndreas Gohr */
1753066fee30SAndreas Gohrfunction license_img($type) {
1754066fee30SAndreas Gohr    global $license;
1755066fee30SAndreas Gohr    global $conf;
1756066fee30SAndreas Gohr    if(!$conf['license']) return '';
1757066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1758066fee30SAndreas Gohr    $try   = array();
1759066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1760066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1761066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1762066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1763066fee30SAndreas Gohr    }
1764066fee30SAndreas Gohr    foreach($try as $src) {
176579e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1766066fee30SAndreas Gohr    }
1767066fee30SAndreas Gohr    return '';
1768dc58b6f4SAndy Webber}
1769dc58b6f4SAndy Webber
177013c08e2fSMichael Klier/**
177113c08e2fSMichael Klier * Checks if the given amount of memory is available
177213c08e2fSMichael Klier *
177313c08e2fSMichael Klier * If the memory_get_usage() function is not available the
177413c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
177513c08e2fSMichael Klier *
177613c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
177713c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
17783272d797SAndreas Gohr *
17793272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1780140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
17813272d797SAndreas Gohr * @return bool
178213c08e2fSMichael Klier */
178313c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
178413c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
178513c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
178613c08e2fSMichael Klier
178713c08e2fSMichael Klier    // parse limit to bytes
178813c08e2fSMichael Klier    $limit = php_to_byte($limit);
178913c08e2fSMichael Klier
179013c08e2fSMichael Klier    // get used memory if possible
179113c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
179213c08e2fSMichael Klier        $used = memory_get_usage();
179349eb6e38SAndreas Gohr    } else {
179449eb6e38SAndreas Gohr        $used = $bytes;
179513c08e2fSMichael Klier    }
179613c08e2fSMichael Klier
179713c08e2fSMichael Klier    if($used + $mem > $limit) {
179813c08e2fSMichael Klier        return false;
179913c08e2fSMichael Klier    }
180013c08e2fSMichael Klier
180113c08e2fSMichael Klier    return true;
180213c08e2fSMichael Klier}
180313c08e2fSMichael Klier
1804af2408d5SAndreas Gohr/**
1805af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1806af2408d5SAndreas Gohr *
1807af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1808af2408d5SAndreas Gohr *
1809af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1810af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1811140cfbcdSGerrit Uitslag *
1812140cfbcdSGerrit Uitslag * @param string $url url being directed to
1813af2408d5SAndreas Gohr */
1814af2408d5SAndreas Gohrfunction send_redirect($url) {
1815585bf44eSChristopher Smith    /* @var Input $INPUT */
1816585bf44eSChristopher Smith    global $INPUT;
1817585bf44eSChristopher Smith
18180181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18190181f021SAndreas Gohr    global $MSG;
18200181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18210181f021SAndreas Gohr        //reopen session, store data and close session again
18220181f021SAndreas Gohr        @session_start();
18230181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18240181f021SAndreas Gohr    }
18250181f021SAndreas Gohr
1826d4869846SAndreas Gohr    // always close the session
1827d4869846SAndreas Gohr    session_write_close();
1828d4869846SAndreas Gohr
1829af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1830585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1831585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1832585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18333272d797SAndreas Gohr        $matches[1] < 6
18343272d797SAndreas Gohr    ) {
1835af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1836af2408d5SAndreas Gohr    } else {
1837af2408d5SAndreas Gohr        header('Location: '.$url);
1838af2408d5SAndreas Gohr    }
183981781cb6SAndreas Gohr
184081781cb6SAndreas Gohr    if(defined('DOKU_UNITTEST')) return; // no exits during unit tests
1841af2408d5SAndreas Gohr    exit;
1842af2408d5SAndreas Gohr}
1843af2408d5SAndreas Gohr
18445b75cd1fSAdrian Lang/**
18455b75cd1fSAdrian Lang * Validate a value using a set of valid values
18465b75cd1fSAdrian Lang *
18475b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18485b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18495b75cd1fSAdrian Lang * default is specified, throws an exception.
18505b75cd1fSAdrian Lang *
18515b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18525b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18535b75cd1fSAdrian Lang *                             be marked by the key “default”.
18545b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18555b75cd1fSAdrian Lang *                             or $_GET)
18565b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
18575b75cd1fSAdrian Lang *
18583272d797SAndreas Gohr * @throws Exception
18593272d797SAndreas Gohr * @return mixed
18605b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18615b75cd1fSAdrian Lang */
18625b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
18635b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
18645b75cd1fSAdrian Lang        return $array[$param];
18655b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
18665b75cd1fSAdrian Lang        return $valid_values['default'];
18675b75cd1fSAdrian Lang    } else {
18685b75cd1fSAdrian Lang        throw new Exception($exc);
18695b75cd1fSAdrian Lang    }
18705b75cd1fSAdrian Lang}
18715b75cd1fSAdrian Lang
187263703ba5SAndreas Gohr/**
187363703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1874646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1875140cfbcdSGerrit Uitslag *
1876140cfbcdSGerrit Uitslag * @param string $pref     preference key
1877b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1878140cfbcdSGerrit Uitslag * @return string preference value
187963703ba5SAndreas Gohr */
1880554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1881646a531aSChristopher Smith    $enc_pref = urlencode($pref);
188206c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1883554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
188463703ba5SAndreas Gohr        $cnt   = count($parts);
188563703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1886646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1887646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1888554a8c9fSAdrian Lang            }
1889554a8c9fSAdrian Lang        }
1890554a8c9fSAdrian Lang    }
1891554a8c9fSAdrian Lang    return $default;
1892554a8c9fSAdrian Lang}
1893554a8c9fSAdrian Lang
18943c94d07bSAnika Henke/**
18953c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
189636ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
18973a970889SAnika Henke * Remove it by setting $val to false
1898140cfbcdSGerrit Uitslag *
1899140cfbcdSGerrit Uitslag * @param string $pref  preference key
1900140cfbcdSGerrit Uitslag * @param string $val   preference value
19013c94d07bSAnika Henke */
19023c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
19033c94d07bSAnika Henke    global $conf;
19043c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19053c94d07bSAnika Henke    $cookieVal = '';
19063c94d07bSAnika Henke
19073c94d07bSAnika Henke    if($orig && ($orig != $val)) {
19083c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19093c94d07bSAnika Henke        $cnt   = count($parts);
191036ec377eSChristopher Smith        // urlencode $pref for the comparison
191136ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
19123c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
191336ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
19143a970889SAnika Henke                if ($val !== false) {
191536ec377eSChristopher Smith                    $parts[$i + 1] = rawurlencode($val);
19163a970889SAnika Henke                } else {
19173a970889SAnika Henke                    unset($parts[$i]);
19183a970889SAnika Henke                    unset($parts[$i + 1]);
19193a970889SAnika Henke                }
192050f261f7SMichael Hamann                break;
19213c94d07bSAnika Henke            }
19223c94d07bSAnika Henke        }
19233c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19243a970889SAnika Henke    } else if (!$orig && $val !== false) {
192536ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
19263c94d07bSAnika Henke    }
19273c94d07bSAnika Henke
19283c94d07bSAnika Henke    if (!empty($cookieVal)) {
192975e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
193075e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
19313c94d07bSAnika Henke    }
19323c94d07bSAnika Henke}
19333c94d07bSAnika Henke
1934f8fb2d18SAndreas Gohr/**
1935f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1936f8fb2d18SAndreas Gohr *
193742ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1938f8fb2d18SAndreas Gohr */
1939f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
1940f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1941f8fb2d18SAndreas Gohr}
1942f8fb2d18SAndreas Gohr
1943e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1944