xref: /dokuwiki/inc/common.php (revision 7e87a794494ea987ebc31decd939a25d44a5c00d)
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()
25d5197206Schris */
26d5197206Schrisfunction hsc($string) {
27d5197206Schris    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
28d5197206Schris}
29d5197206Schris
30d5197206Schris/**
31d5197206Schris * print a newline terminated string
32d5197206Schris *
33d5197206Schris * You can give an indention as optional parameter
34d5197206Schris *
35d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
36d5197206Schris */
3725ec097bSChris Smithfunction ptln($string, $indent = 0) {
3825ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
3902b0b681SAndreas Gohr}
4002b0b681SAndreas Gohr
4102b0b681SAndreas Gohr/**
4202b0b681SAndreas Gohr * strips control characters (<32) from the given string
4302b0b681SAndreas Gohr *
4402b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4502b0b681SAndreas Gohr */
4602b0b681SAndreas Gohrfunction stripctl($string) {
4702b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
48d5197206Schris}
49d5197206Schris
50d5197206Schris/**
51634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
52634d7150SAndreas Gohr *
53634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
54634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
55634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
56634d7150SAndreas Gohr * @return  string
57634d7150SAndreas Gohr */
58634d7150SAndreas Gohrfunction getSecurityToken() {
598071beaaSAndreas Gohr    return md5(auth_cookiesalt().session_id().$_SERVER['REMOTE_USER']);
60634d7150SAndreas Gohr}
61634d7150SAndreas Gohr
62634d7150SAndreas Gohr/**
63634d7150SAndreas Gohr * Check the secret CSRF token
64634d7150SAndreas Gohr */
65634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
667d01a0eaSTom N Harris    global $INPUT;
67df97eaacSAndreas Gohr    if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
68df97eaacSAndreas Gohr
697d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
70634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
71634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
72634d7150SAndreas Gohr        return false;
73634d7150SAndreas Gohr    }
74634d7150SAndreas Gohr    return true;
75634d7150SAndreas Gohr}
76634d7150SAndreas Gohr
77634d7150SAndreas Gohr/**
78634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
79634d7150SAndreas Gohr *
80634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
81634d7150SAndreas Gohr */
82634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
832404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
843272d797SAndreas Gohr    if($print) echo $ret;
85634d7150SAndreas Gohr    return $ret;
86634d7150SAndreas Gohr}
87634d7150SAndreas Gohr
88634d7150SAndreas Gohr/**
891015a57dSChristopher Smith * Determine basic information for a request of $id
9015fae107Sandi *
91*7e87a794SChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
92*7e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
93f3f0262cSandi */
941015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
95f3f0262cSandi    global $USERINFO;
966afe8dcaSchris
97c66972f2SAdrian Lang    // set info about manager/admin status.
98c66972f2SAdrian Lang    $info['isadmin']   = false;
99c66972f2SAdrian Lang    $info['ismanager'] = false;
100c66972f2SAdrian Lang    if(isset($_SERVER['REMOTE_USER'])) {
101f3f0262cSandi        $info['userinfo']   = $USERINFO;
1021015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
103ee4c4a1bSAndreas Gohr        $info['client']     = $_SERVER['REMOTE_USER'];
10417ee7f66SAndreas Gohr
105f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
106f8cc712eSAndreas Gohr            $info['isadmin']   = true;
107f8cc712eSAndreas Gohr            $info['ismanager'] = true;
108f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
109f8cc712eSAndreas Gohr            $info['ismanager'] = true;
110f8cc712eSAndreas Gohr        }
111f8cc712eSAndreas Gohr
11217ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
11317ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
11417ee7f66SAndreas Gohr            $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
11517ee7f66SAndreas Gohr        }
116ee4c4a1bSAndreas Gohr
117f3f0262cSandi    } else {
1181015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
119ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
120f3f0262cSandi    }
121f3f0262cSandi
1221015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1231015a57dSChristopher Smith
1241015a57dSChristopher Smith    // mobile detection
1251015a57dSChristopher Smith    if ($htmlClient) {
1261015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1271015a57dSChristopher Smith    }
1281015a57dSChristopher Smith
1291015a57dSChristopher Smith    return $info;
1301015a57dSChristopher Smith }
1311015a57dSChristopher Smith
1321015a57dSChristopher Smith/**
1331015a57dSChristopher Smith * Return info about the current document as associative
1341015a57dSChristopher Smith * array.
1351015a57dSChristopher Smith *
1361015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
1371015a57dSChristopher Smith */
1381015a57dSChristopher Smithfunction pageinfo() {
1391015a57dSChristopher Smith    global $ID;
1401015a57dSChristopher Smith    global $REV;
1411015a57dSChristopher Smith    global $RANGE;
1421015a57dSChristopher Smith    global $lang;
1431015a57dSChristopher Smith
1441015a57dSChristopher Smith    $info = basicinfo($ID);
1451015a57dSChristopher Smith
1461015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1471015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1481015a57dSChristopher Smith    $info['id']  = $ID;
1491015a57dSChristopher Smith    $info['rev'] = $REV;
1501015a57dSChristopher Smith
151*7e87a794SChristopher Smith    if(isset($_SERVER['REMOTE_USER'])) {
152*7e87a794SChristopher Smith        $sub = new Subscription();
153*7e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
154*7e87a794SChristopher Smith    } else {
155*7e87a794SChristopher Smith        $info['subscribed'] = false;
156*7e87a794SChristopher Smith    }
157*7e87a794SChristopher Smith
158f3f0262cSandi    $info['locked']    = checklock($ID);
15900976812SAndreas Gohr    $info['filepath']  = fullpath(wikiFN($ID));
1602ca9d91cSBen Coburn    $info['exists']    = @file_exists($info['filepath']);
1612ca9d91cSBen Coburn    if($REV) {
1622ca9d91cSBen Coburn        //check if current revision was meant
1632ca9d91cSBen Coburn        if($info['exists'] && (@filemtime($info['filepath']) == $REV)) {
1642ca9d91cSBen Coburn            $REV = '';
1657b3a6803SAndreas Gohr        } elseif($RANGE) {
1667b3a6803SAndreas Gohr            //section editing does not work with old revisions!
1677b3a6803SAndreas Gohr            $REV   = '';
1687b3a6803SAndreas Gohr            $RANGE = '';
1697b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
1702ca9d91cSBen Coburn        } else {
1712ca9d91cSBen Coburn            //really use old revision
17200976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID, $REV));
173f3f0262cSandi            $info['exists']   = @file_exists($info['filepath']);
174f3f0262cSandi        }
175f3f0262cSandi    }
176c112d578Sandi    $info['rev'] = $REV;
177f3f0262cSandi    if($info['exists']) {
178f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
179f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
180f3f0262cSandi    } else {
181f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
182f3f0262cSandi    }
18350e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
184f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
185f3f0262cSandi
18671726d78SBen Coburn    //load page meta data
18771726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
18871726d78SBen Coburn
189652610a2Sandi    //who's the editor
190652610a2Sandi    if($REV) {
19171726d78SBen Coburn        $revinfo = getRevisionInfo($ID, $REV, 1024);
192652610a2Sandi    } else {
193aa27cf05SAndreas Gohr        if(is_array($info['meta']['last_change'])) {
194aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
195aa27cf05SAndreas Gohr        } else {
196cd00a034SBen Coburn            $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
197cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
198cd00a034SBen Coburn            if($revinfo !== false) {
199cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
200cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
201cd00a034SBen Coburn            }
202cd00a034SBen Coburn        }
203cd00a034SBen Coburn    }
204cd00a034SBen Coburn    //and check for an external edit
205cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
206cd00a034SBen Coburn        // cached changelog line no longer valid
207cd00a034SBen Coburn        $revinfo                     = false;
208cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
209cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
210652610a2Sandi    }
211bb4866bdSchris
212652610a2Sandi    $info['ip']   = $revinfo['ip'];
213652610a2Sandi    $info['user'] = $revinfo['user'];
214652610a2Sandi    $info['sum']  = $revinfo['sum'];
21571726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
216ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
21759f257aeSchris
21888f522e9Sandi    if($revinfo['user']) {
21988f522e9Sandi        $info['editor'] = $revinfo['user'];
22088f522e9Sandi    } else {
22188f522e9Sandi        $info['editor'] = $revinfo['ip'];
22288f522e9Sandi    }
223652610a2Sandi
224ee4c4a1bSAndreas Gohr    // draft
225ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
226ee4c4a1bSAndreas Gohr    if(@file_exists($draft)) {
227ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
228ee4c4a1bSAndreas Gohr            // remove stale draft
229ee4c4a1bSAndreas Gohr            @unlink($draft);
230ee4c4a1bSAndreas Gohr        } else {
231ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
232ee4c4a1bSAndreas Gohr        }
233ee4c4a1bSAndreas Gohr    }
234ee4c4a1bSAndreas Gohr
2351015a57dSChristopher Smith    return $info;
2361015a57dSChristopher Smith}
2371015a57dSChristopher Smith
2381015a57dSChristopher Smith/**
2391015a57dSChristopher Smith * Return information about the current media item as an associative array.
2401015a57dSChristopher Smith */
2411015a57dSChristopher Smithfunction mediainfo(){
2421015a57dSChristopher Smith    global $NS;
2431015a57dSChristopher Smith    global $IMG;
2441015a57dSChristopher Smith
2451015a57dSChristopher Smith    $info = basicinfo("$NS:*");
2461015a57dSChristopher Smith    $info['image'] = $IMG;
2471c548ebeSAndreas Gohr
248f3f0262cSandi    return $info;
249f3f0262cSandi}
250f3f0262cSandi
251f3f0262cSandi/**
2522684e50aSAndreas Gohr * Build an string of URL parameters
2532684e50aSAndreas Gohr *
2542684e50aSAndreas Gohr * @author Andreas Gohr
2552684e50aSAndreas Gohr */
256b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
2572684e50aSAndreas Gohr    $url = '';
2582684e50aSAndreas Gohr    $amp = false;
2592684e50aSAndreas Gohr    foreach($params as $key => $val) {
260b174aeaeSchris        if($amp) $url .= $sep;
2612684e50aSAndreas Gohr
26285e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
2633a50618cSgweissbach        $url .= rawurlencode((string) $val);
2642684e50aSAndreas Gohr        $amp = true;
2652684e50aSAndreas Gohr    }
2662684e50aSAndreas Gohr    return $url;
2672684e50aSAndreas Gohr}
2682684e50aSAndreas Gohr
2692684e50aSAndreas Gohr/**
2702684e50aSAndreas Gohr * Build an string of html tag attributes
2712684e50aSAndreas Gohr *
2727bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2737bff22c0SAndreas Gohr *
2742684e50aSAndreas Gohr * @author Andreas Gohr
2752684e50aSAndreas Gohr */
2764b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
2772684e50aSAndreas Gohr    $url   = '';
2789063ec14SAdrian Lang    $white = false;
2792684e50aSAndreas Gohr    foreach($params as $key => $val) {
2807bff22c0SAndreas Gohr        if($key{0} == '_') continue;
281b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
2829063ec14SAdrian Lang        if($white) $url .= ' ';
2837bff22c0SAndreas Gohr
2842684e50aSAndreas Gohr        $url .= $key.'="';
2852684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
2862684e50aSAndreas Gohr        $url .= '"';
2879063ec14SAdrian Lang        $white = true;
2882684e50aSAndreas Gohr    }
2892684e50aSAndreas Gohr    return $url;
2902684e50aSAndreas Gohr}
2912684e50aSAndreas Gohr
2922684e50aSAndreas Gohr/**
29315fae107Sandi * This builds the breadcrumb trail and returns it as array
29415fae107Sandi *
29515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
296f3f0262cSandi */
297f3f0262cSandifunction breadcrumbs() {
2988746e727Sandi    // we prepare the breadcrumbs early for quick session closing
2998746e727Sandi    static $crumbs = null;
3008746e727Sandi    if($crumbs != null) return $crumbs;
3018746e727Sandi
302f3f0262cSandi    global $ID;
303f3f0262cSandi    global $ACT;
304f3f0262cSandi    global $conf;
305f3f0262cSandi
306f3f0262cSandi    //first visit?
307c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
308f3f0262cSandi    //we only save on show and existing wiki documents
309a77f5846Sjan    $file = wikiFN($ID);
310a77f5846Sjan    if($ACT != 'show' || !@file_exists($file)) {
311e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
312f3f0262cSandi        return $crumbs;
313f3f0262cSandi    }
314a77f5846Sjan
315a77f5846Sjan    // page names
3161a84a0f3SAnika Henke    $name = noNSorNS($ID);
317fe9ec250SChris Smith    if(useHeading('navigation')) {
318a77f5846Sjan        // get page title
31967c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
320a77f5846Sjan        if($title) {
321a77f5846Sjan            $name = $title;
322a77f5846Sjan        }
323a77f5846Sjan    }
324a77f5846Sjan
325f3f0262cSandi    //remove ID from array
326a77f5846Sjan    if(isset($crumbs[$ID])) {
327a77f5846Sjan        unset($crumbs[$ID]);
328f3f0262cSandi    }
329f3f0262cSandi
330f3f0262cSandi    //add to array
331a77f5846Sjan    $crumbs[$ID] = $name;
332f3f0262cSandi    //reduce size
333f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
334f3f0262cSandi        array_shift($crumbs);
335f3f0262cSandi    }
336f3f0262cSandi    //save to session
337e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
338f3f0262cSandi    return $crumbs;
339f3f0262cSandi}
340f3f0262cSandi
341f3f0262cSandi/**
34215fae107Sandi * Filter for page IDs
34315fae107Sandi *
344f3f0262cSandi * This is run on a ID before it is outputted somewhere
345f3f0262cSandi * currently used to replace the colon with something else
346907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
347907f24f7SAndreas Gohr *
348907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
349907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
350907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
35115fae107Sandi *
35249c713a3Sandi * Urlencoding is ommitted when the second parameter is false
35349c713a3Sandi *
35415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
355f3f0262cSandi */
35649c713a3Sandifunction idfilter($id, $ue = true) {
357f3f0262cSandi    global $conf;
358f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
359f3f0262cSandi        $id = strtr($id, ':', '/');
360f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
36158bedc8aSborekb        $conf['userewrite'] &&
36258bedc8aSborekb        strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') === false
3633272d797SAndreas Gohr    ) {
364f3f0262cSandi        $id = strtr($id, ':', ';');
365f3f0262cSandi    }
36649c713a3Sandi    if($ue) {
367b6c6979fSAndreas Gohr        $id = rawurlencode($id);
368f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
369f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
37049c713a3Sandi    }
371f3f0262cSandi    return $id;
372f3f0262cSandi}
373f3f0262cSandi
374f3f0262cSandi/**
375ed7b5f09Sandi * This builds a link to a wikipage
37615fae107Sandi *
3776c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3786c7843b5Sandi * given in $more
3796c7843b5Sandi *
38015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
381f3f0262cSandi */
38216f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
383f3f0262cSandi    global $conf;
38416f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
38516f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
3866de3759aSAndreas Gohr    } else {
38716f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
3886de3759aSAndreas Gohr    }
38916f15a81SDominik Eckelmann    if($id === '') {
39016f15a81SDominik Eckelmann        $id = $conf['start'];
39116f15a81SDominik Eckelmann    }
392f3f0262cSandi    $id = idfilter($id);
39316f15a81SDominik Eckelmann    if($absolute) {
394ed7b5f09Sandi        $xlink = DOKU_URL;
395ed7b5f09Sandi    } else {
396ed7b5f09Sandi        $xlink = DOKU_BASE;
397ed7b5f09Sandi    }
398f3f0262cSandi
3996c7843b5Sandi    if($conf['userewrite'] == 2) {
4006c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
40116f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4026c7843b5Sandi    } elseif($conf['userewrite']) {
403f3f0262cSandi        $xlink .= $id;
40416f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
405bce3726dSAndreas Gohr    } elseif($id) {
4066c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
40716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
408bce3726dSAndreas Gohr    } else {
409bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
41016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
411f3f0262cSandi    }
412f3f0262cSandi
413f3f0262cSandi    return $xlink;
414f3f0262cSandi}
415f3f0262cSandi
416f3f0262cSandi/**
417f5c2808fSBen Coburn * This builds a link to an alternate page format
418f5c2808fSBen Coburn *
419f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
420f5c2808fSBen Coburn *
421f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
422f5c2808fSBen Coburn */
423f5c2808fSBen Coburnfunction exportlink($id = '', $format = 'raw', $more = '', $abs = false, $sep = '&amp;') {
424f5c2808fSBen Coburn    global $conf;
425f5c2808fSBen Coburn    if(is_array($more)) {
426f5c2808fSBen Coburn        $more = buildURLparams($more, $sep);
427f5c2808fSBen Coburn    } else {
428f5c2808fSBen Coburn        $more = str_replace(',', $sep, $more);
429f5c2808fSBen Coburn    }
430f5c2808fSBen Coburn
431f5c2808fSBen Coburn    $format = rawurlencode($format);
432f5c2808fSBen Coburn    $id     = idfilter($id);
433f5c2808fSBen Coburn    if($abs) {
434f5c2808fSBen Coburn        $xlink = DOKU_URL;
435f5c2808fSBen Coburn    } else {
436f5c2808fSBen Coburn        $xlink = DOKU_BASE;
437f5c2808fSBen Coburn    }
438f5c2808fSBen Coburn
439f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
440f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
441f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
442f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
443f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
444f5c2808fSBen Coburn        if($more) $xlink .= '?'.$more;
445f5c2808fSBen Coburn    } else {
446f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
447f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
448f5c2808fSBen Coburn    }
449f5c2808fSBen Coburn
450f5c2808fSBen Coburn    return $xlink;
451f5c2808fSBen Coburn}
452f5c2808fSBen Coburn
453f5c2808fSBen Coburn/**
4546de3759aSAndreas Gohr * Build a link to a media file
4556de3759aSAndreas Gohr *
4566de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4578c08db0aSAndreas Gohr *
4588c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4598c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4608c08db0aSAndreas Gohr *
4613272d797SAndreas Gohr * @param string  $id     the media file id or URL
4623272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
4633272d797SAndreas Gohr * @param bool    $direct link to detail page if false
4643272d797SAndreas Gohr * @param string  $sep    URL parameter separator
4653272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
4663272d797SAndreas Gohr * @return string
4676de3759aSAndreas Gohr */
46855b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
4696de3759aSAndreas Gohr    global $conf;
4706de3759aSAndreas Gohr    if(is_array($more)) {
4718c08db0aSAndreas Gohr        // strip defaults for shorter URLs
4728c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
4738c08db0aSAndreas Gohr        if(!$more['w']) unset($more['w']);
4748c08db0aSAndreas Gohr        if(!$more['h']) unset($more['h']);
4758c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
476b174aeaeSchris        $more = buildURLparams($more, $sep);
4776de3759aSAndreas Gohr    } else {
4788c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
4798c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
480b174aeaeSchris        $more = str_replace(',', $sep, $more);
4816de3759aSAndreas Gohr    }
4826de3759aSAndreas Gohr
48355b2b31bSAndreas Gohr    if($abs) {
48455b2b31bSAndreas Gohr        $xlink = DOKU_URL;
48555b2b31bSAndreas Gohr    } else {
4866de3759aSAndreas Gohr        $xlink = DOKU_BASE;
48755b2b31bSAndreas Gohr    }
4886de3759aSAndreas Gohr
4896de3759aSAndreas Gohr    // external URLs are always direct without rewriting
4906de3759aSAndreas Gohr    if(preg_match('#^(https?|ftp)://#i', $id)) {
4916de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
49269d17d94SAndreas Gohr        // add hash:
49369d17d94SAndreas Gohr        $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id), 0, 6);
4946de3759aSAndreas Gohr        if($more) {
49569d17d94SAndreas Gohr            $xlink .= $sep.$more;
496b174aeaeSchris            $xlink .= $sep.'media='.rawurlencode($id);
4976de3759aSAndreas Gohr        } else {
49869d17d94SAndreas Gohr            $xlink .= $sep.'media='.rawurlencode($id);
4996de3759aSAndreas Gohr        }
5006de3759aSAndreas Gohr        return $xlink;
5016de3759aSAndreas Gohr    }
5026de3759aSAndreas Gohr
5036de3759aSAndreas Gohr    $id = idfilter($id);
5046de3759aSAndreas Gohr
5056de3759aSAndreas Gohr    // decide on scriptname
5066de3759aSAndreas Gohr    if($direct) {
5076de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5086de3759aSAndreas Gohr            $script = '_media';
5096de3759aSAndreas Gohr        } else {
5106de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
5116de3759aSAndreas Gohr        }
5126de3759aSAndreas Gohr    } else {
5136de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5146de3759aSAndreas Gohr            $script = '_detail';
5156de3759aSAndreas Gohr        } else {
5166de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
5176de3759aSAndreas Gohr        }
5186de3759aSAndreas Gohr    }
5196de3759aSAndreas Gohr
5206de3759aSAndreas Gohr    // build URL based on rewrite mode
5216de3759aSAndreas Gohr    if($conf['userewrite']) {
5226de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
5236de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
5246de3759aSAndreas Gohr    } else {
5256de3759aSAndreas Gohr        if($more) {
526a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
527b174aeaeSchris            $xlink .= $sep.'media='.$id;
5286de3759aSAndreas Gohr        } else {
529a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
5306de3759aSAndreas Gohr        }
5316de3759aSAndreas Gohr    }
5326de3759aSAndreas Gohr
5336de3759aSAndreas Gohr    return $xlink;
5346de3759aSAndreas Gohr}
5356de3759aSAndreas Gohr
5366de3759aSAndreas Gohr/**
53725ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
53815fae107Sandi *
53925ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
54025ca5b17SAndreas Gohr *
54115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
542f3f0262cSandi */
54325ca5b17SAndreas Gohrfunction script() {
544ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
545f3f0262cSandi}
546f3f0262cSandi
547f3f0262cSandi/**
54815fae107Sandi * Spamcheck against wordlist
54915fae107Sandi *
550f3f0262cSandi * Checks the wikitext against a list of blocked expressions
551f3f0262cSandi * returns true if the text contains any bad words
55215fae107Sandi *
553e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
554e403cc58SMichael Klier *
555e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
556e403cc58SMichael Klier *  and gain information about the user who was blocked.
557e403cc58SMichael Klier *
558e403cc58SMichael Klier *  Event data:
559e403cc58SMichael Klier *    data['matches']  - array of matches
560e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
561e403cc58SMichael Klier *      [ip]           - ip address
562e403cc58SMichael Klier *      [user]         - username (if logged in)
563e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
564e403cc58SMichael Klier *      [name]         - real name (if logged in)
565e403cc58SMichael Klier *
56615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5676dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
5686dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
5696dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
570f3f0262cSandi */
5716dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
572f3f0262cSandi    global $TEXT;
5736dffa0e0SAndreas Gohr    global $PRE;
5746dffa0e0SAndreas Gohr    global $SUF;
575f3f0262cSandi    global $conf;
576e403cc58SMichael Klier    global $INFO;
577f3f0262cSandi
578f3f0262cSandi    if(!$conf['usewordblock']) return false;
579f3f0262cSandi
5806dffa0e0SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF";
5816dffa0e0SAndreas Gohr
582041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
5836dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
584041d1964SAndreas Gohr
585b9ac8716Schris    $wordblocks = getWordblocks();
5863e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
5873e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
5883e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
5893e2965d7Sandi        // backreferences are used - the maximum is 99
5903e2965d7Sandi        // this is very bad performancewise and may even be too high still
5913e2965d7Sandi        $chunksize = 40;
5923e2965d7Sandi    } else {
593a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
5943e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
595a51d08efSAndreas Gohr        $chunksize = 200;
5963e2965d7Sandi    }
597b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
598f3f0262cSandi        $re = array();
59949eb6e38SAndreas Gohr        // build regexp from blocks
600f3f0262cSandi        foreach($blocks as $block) {
601f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
602f3f0262cSandi            $block = trim($block);
603f3f0262cSandi            if(empty($block)) continue;
604f3f0262cSandi            $re[] = $block;
605f3f0262cSandi        }
606e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
607e403cc58SMichael Klier            // prepare event data
608e403cc58SMichael Klier            $data['matches']        = $matches;
609e403cc58SMichael Klier            $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
610e403cc58SMichael Klier            if($_SERVER['REMOTE_USER']) {
611e403cc58SMichael Klier                $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
612e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
613e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
614e403cc58SMichael Klier            }
615e403cc58SMichael Klier            $callback = create_function('', 'return true;');
616e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
617b9ac8716Schris        }
618703f6fdeSandi    }
619f3f0262cSandi    return false;
620f3f0262cSandi}
621f3f0262cSandi
622f3f0262cSandi/**
62315fae107Sandi * Return the IP of the client
62415fae107Sandi *
6256d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
62615fae107Sandi *
6276d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
6286d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
6296d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
6306d8affe6SAndreas Gohr * headers
6316d8affe6SAndreas Gohr *
63215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6333272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
6343272d797SAndreas Gohr * @return string
635f3f0262cSandi */
6366d8affe6SAndreas Gohrfunction clientIP($single = false) {
6376d8affe6SAndreas Gohr    $ip   = array();
6386d8affe6SAndreas Gohr    $ip[] = $_SERVER['REMOTE_ADDR'];
639bb4866bdSchris    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
6405cbeffbfSMarcel Pennewiß        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_FORWARDED_FOR'])));
641bb4866bdSchris    if(!empty($_SERVER['HTTP_X_REAL_IP']))
6425cbeffbfSMarcel Pennewiß        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_REAL_IP'])));
6436d8affe6SAndreas Gohr
644dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
645dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
646dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
647dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
648dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
649dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
650dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
651dc14c6d1SGuy Brand    $IPv6Address =
652dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
653dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
654dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
655dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
656dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
657dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
658dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
659dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
660dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
661dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
662dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
663dc14c6d1SGuy Brand
6646d8affe6SAndreas Gohr    // remove any non-IP stuff
6656d8affe6SAndreas Gohr    $cnt   = count($ip);
6664ff28443Schris    $match = array();
6676d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
668dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
6694ff28443Schris            $ip[$i] = $match[0];
6704ff28443Schris        } else {
6714ff28443Schris            $ip[$i] = '';
6724ff28443Schris        }
6736d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
674f3f0262cSandi    }
6756d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
6766d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6776d8affe6SAndreas Gohr
6786d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
6796d8affe6SAndreas Gohr
6806d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
6816d8affe6SAndreas Gohr    $ip = array_reverse($ip);
6826d8affe6SAndreas Gohr    foreach($ip as $i) {
6832343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
6846d8affe6SAndreas Gohr            continue;
6856d8affe6SAndreas Gohr        } else {
6866d8affe6SAndreas Gohr            return $i;
6876d8affe6SAndreas Gohr        }
6886d8affe6SAndreas Gohr    }
6896d8affe6SAndreas Gohr    // still here? just use the first (last) address
6906d8affe6SAndreas Gohr    return $ip[0];
691f3f0262cSandi}
692f3f0262cSandi
693f3f0262cSandi/**
6941c548ebeSAndreas Gohr * Check if the browser is on a mobile device
6951c548ebeSAndreas Gohr *
6961c548ebeSAndreas Gohr * Adapted from the example code at url below
6971c548ebeSAndreas Gohr *
6981c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
6991c548ebeSAndreas Gohr */
7001c548ebeSAndreas Gohrfunction clientismobile() {
7011c548ebeSAndreas Gohr
7021c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
7031c548ebeSAndreas Gohr
7041c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i', $_SERVER['HTTP_ACCEPT'])) return true;
7051c548ebeSAndreas Gohr
7061c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
7071c548ebeSAndreas Gohr
7081c548ebeSAndreas 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';
7091c548ebeSAndreas Gohr
7101c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i", $_SERVER['HTTP_USER_AGENT'])) return true;
7111c548ebeSAndreas Gohr
7121c548ebeSAndreas Gohr    return false;
7131c548ebeSAndreas Gohr}
7141c548ebeSAndreas Gohr
7151c548ebeSAndreas Gohr/**
71663211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
71763211f61SGlen Harris *
71822ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
71922ef1e32SAndreas Gohr *
72063211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
7213272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
7223272d797SAndreas Gohr * @return string a comma separated list of hostnames
72363211f61SGlen Harris */
72463211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
72522ef1e32SAndreas Gohr    global $conf;
72622ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
72722ef1e32SAndreas Gohr
72863211f61SGlen Harris    $hosts = array();
72963211f61SGlen Harris    $ips   = explode(',', $ips);
730551a720fSMichael Klier
731551a720fSMichael Klier    if(is_array($ips)) {
7323886270dSAndreas Gohr        foreach($ips as $ip) {
733551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
73463211f61SGlen Harris        }
735551a720fSMichael Klier        return join(',', $hosts);
736551a720fSMichael Klier    } else {
737551a720fSMichael Klier        return gethostbyaddr(trim($ips));
738551a720fSMichael Klier    }
73963211f61SGlen Harris}
74063211f61SGlen Harris
74163211f61SGlen Harris/**
74215fae107Sandi * Checks if a given page is currently locked.
74315fae107Sandi *
744f3f0262cSandi * removes stale lockfiles
74515fae107Sandi *
74615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
747f3f0262cSandi */
748f3f0262cSandifunction checklock($id) {
749f3f0262cSandi    global $conf;
750c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
751f3f0262cSandi
752f3f0262cSandi    //no lockfile
753f3f0262cSandi    if(!@file_exists($lock)) return false;
754f3f0262cSandi
755f3f0262cSandi    //lockfile expired
756f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
757d8186216SBen Coburn        @unlink($lock);
758f3f0262cSandi        return false;
759f3f0262cSandi    }
760f3f0262cSandi
761f3f0262cSandi    //my own lock
76285fef7e2SAndreas Gohr    list($ip, $session) = explode("\n", io_readFile($lock));
76385fef7e2SAndreas Gohr    if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
764f3f0262cSandi        return false;
765f3f0262cSandi    }
766f3f0262cSandi
767f3f0262cSandi    return $ip;
768f3f0262cSandi}
769f3f0262cSandi
770f3f0262cSandi/**
77115fae107Sandi * Lock a page for editing
77215fae107Sandi *
77315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
774f3f0262cSandi */
775f3f0262cSandifunction lock($id) {
776544ed901SDaniel Calviño Sánchez    global $conf;
777544ed901SDaniel Calviño Sánchez
778544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
779544ed901SDaniel Calviño Sánchez        return;
780544ed901SDaniel Calviño Sánchez    }
781544ed901SDaniel Calviño Sánchez
782c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
783f3f0262cSandi    if($_SERVER['REMOTE_USER']) {
784f3f0262cSandi        io_saveFile($lock, $_SERVER['REMOTE_USER']);
785f3f0262cSandi    } else {
78685fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
787f3f0262cSandi    }
788f3f0262cSandi}
789f3f0262cSandi
790f3f0262cSandi/**
79115fae107Sandi * Unlock a page if it was locked by the user
792f3f0262cSandi *
79315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7943272d797SAndreas Gohr * @param string $id page id to unlock
79515fae107Sandi * @return bool true if a lock was removed
796f3f0262cSandi */
797f3f0262cSandifunction unlock($id) {
798c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
799f3f0262cSandi    if(@file_exists($lock)) {
80085fef7e2SAndreas Gohr        list($ip, $session) = explode("\n", io_readFile($lock));
80185fef7e2SAndreas Gohr        if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
802f3f0262cSandi            @unlink($lock);
803f3f0262cSandi            return true;
804f3f0262cSandi        }
805f3f0262cSandi    }
806f3f0262cSandi    return false;
807f3f0262cSandi}
808f3f0262cSandi
809f3f0262cSandi/**
810f3f0262cSandi * convert line ending to unix format
811f3f0262cSandi *
81215fae107Sandi * @see    formText() for 2crlf conversion
81315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
814f3f0262cSandi */
815f3f0262cSandifunction cleanText($text) {
816f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
817f3f0262cSandi    return $text;
818f3f0262cSandi}
819f3f0262cSandi
820f3f0262cSandi/**
821f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
822f3f0262cSandi * It also converts line endings to Windows format which is
823f3f0262cSandi * pseudo standard for webforms.
824f3f0262cSandi *
82515fae107Sandi * @see    cleanText() for 2unix conversion
82615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
827f3f0262cSandi */
828f3f0262cSandifunction formText($text) {
8295b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
830f3f0262cSandi    return htmlspecialchars($text);
831f3f0262cSandi}
832f3f0262cSandi
833f3f0262cSandi/**
83415fae107Sandi * Returns the specified local text in raw format
83515fae107Sandi *
83615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
837f3f0262cSandi */
8382adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
8392adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
840f3f0262cSandi}
841f3f0262cSandi
842f3f0262cSandi/**
843f3f0262cSandi * Returns the raw WikiText
84415fae107Sandi *
84515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
846f3f0262cSandi */
847f3f0262cSandifunction rawWiki($id, $rev = '') {
848cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
849f3f0262cSandi}
850f3f0262cSandi
851f3f0262cSandi/**
8527146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
8537146cee2SAndreas Gohr *
8547b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
8557146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8567146cee2SAndreas Gohr */
857fe17917eSAdrian Langfunction pageTemplate($id) {
858a15ce62dSEsther Brunner    global $conf;
859e29549feSAndreas Gohr
860fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
861e29549feSAndreas Gohr
8627b84afa2SAndreas Gohr    // prepare initial event data
8637b84afa2SAndreas Gohr    $data = array(
8647b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
8657b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
8667b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
8677b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
8687b84afa2SAndreas Gohr    );
8697b84afa2SAndreas Gohr
8707b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
8717b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
8727b84afa2SAndreas Gohr        // the before event might have loaded the content already
8737b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
8747b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
8757b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
876fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
877e29549feSAndreas Gohr                if(@file_exists($path.'/_template.txt')) {
8787b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
879e29549feSAndreas Gohr                } else {
880e29549feSAndreas Gohr                    // search upper namespaces for templates
881e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
882e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
883e29549feSAndreas Gohr                        if(@file_exists($path.'/__template.txt')) {
8847b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
885e29549feSAndreas Gohr                            break;
886e29549feSAndreas Gohr                        }
887e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
888e29549feSAndreas Gohr                    }
889e29549feSAndreas Gohr                }
8907b84afa2SAndreas Gohr            }
8917b84afa2SAndreas Gohr            // load the content
8923d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
8937b84afa2SAndreas Gohr        }
894a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
8957b84afa2SAndreas Gohr    }
8967b84afa2SAndreas Gohr    $evt->advise_after();
8977b84afa2SAndreas Gohr    unset($evt);
8987b84afa2SAndreas Gohr
899fe17917eSAdrian Lang    return $data['tpl'];
9002b1223ecSAdrian Lang}
9012b1223ecSAdrian Lang
9022b1223ecSAdrian Lang/**
9032b1223ecSAdrian Lang * Performs common page template replacements
9047b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
9052b1223ecSAdrian Lang *
9062b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
9072b1223ecSAdrian Lang */
908d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
9093272d797SAndreas Gohr    /**
9103272d797SAndreas Gohr     * @var string $id        the id of the page to be created
9113272d797SAndreas Gohr     * @var string $tpl       the text used as template
9123272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
9133272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
9143272d797SAndreas Gohr     */
915fe17917eSAdrian Lang    extract($data);
916fe17917eSAdrian Lang
917b856f7dfSAdrian Lang    global $USERINFO;
918bce53b1fSAdrian Lang    global $conf;
919e29549feSAndreas Gohr
920e29549feSAndreas Gohr    // replace placeholders
92126ece5a7SAndreas Gohr    $file = noNS($id);
92237c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
92326ece5a7SAndreas Gohr
9243272d797SAndreas Gohr    $tpl = str_replace(
9253272d797SAndreas Gohr        array(
92626ece5a7SAndreas Gohr             '@ID@',
92726ece5a7SAndreas Gohr             '@NS@',
92826ece5a7SAndreas Gohr             '@FILE@',
92926ece5a7SAndreas Gohr             '@!FILE@',
93026ece5a7SAndreas Gohr             '@!FILE!@',
93126ece5a7SAndreas Gohr             '@PAGE@',
93226ece5a7SAndreas Gohr             '@!PAGE@',
93326ece5a7SAndreas Gohr             '@!!PAGE@',
93426ece5a7SAndreas Gohr             '@!PAGE!@',
93526ece5a7SAndreas Gohr             '@USER@',
93626ece5a7SAndreas Gohr             '@NAME@',
93726ece5a7SAndreas Gohr             '@MAIL@',
93826ece5a7SAndreas Gohr             '@DATE@',
93926ece5a7SAndreas Gohr        ),
94026ece5a7SAndreas Gohr        array(
94126ece5a7SAndreas Gohr             $id,
94226ece5a7SAndreas Gohr             getNS($id),
94326ece5a7SAndreas Gohr             $file,
94426ece5a7SAndreas Gohr             utf8_ucfirst($file),
94526ece5a7SAndreas Gohr             utf8_strtoupper($file),
94626ece5a7SAndreas Gohr             $page,
94726ece5a7SAndreas Gohr             utf8_ucfirst($page),
94826ece5a7SAndreas Gohr             utf8_ucwords($page),
94926ece5a7SAndreas Gohr             utf8_strtoupper($page),
95026ece5a7SAndreas Gohr             $_SERVER['REMOTE_USER'],
951b856f7dfSAdrian Lang             $USERINFO['name'],
952b856f7dfSAdrian Lang             $USERINFO['mail'],
95326ece5a7SAndreas Gohr             $conf['dformat'],
9543272d797SAndreas Gohr        ), $tpl
9553272d797SAndreas Gohr    );
95626ece5a7SAndreas Gohr
9577d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
9587d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
959d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
960a15ce62dSEsther Brunner    return $tpl;
9617146cee2SAndreas Gohr}
9627146cee2SAndreas Gohr
9637146cee2SAndreas Gohr/**
96415fae107Sandi * Returns the raw Wiki Text in three slices.
96515fae107Sandi *
96615fae107Sandi * The range parameter needs to have the form "from-to"
96715cfe303Sandi * and gives the range of the section in bytes - no
96815cfe303Sandi * UTF-8 awareness is needed.
969f3f0262cSandi * The returned order is prefix, section and suffix.
97015fae107Sandi *
97115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
972f3f0262cSandi */
973f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
974cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
975f3f0262cSandi
97680fcb268SAdrian Lang    // Parse range
97780fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
97880fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
97980fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
98080fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
98180fcb268SAdrian Lang
98280fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
98380fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
98415cfe303Sandi    $slices[2] = substr($text, $to);
985f3f0262cSandi    return $slices;
986f3f0262cSandi}
987f3f0262cSandi
988f3f0262cSandi/**
98915fae107Sandi * Joins wiki text slices
99015fae107Sandi *
99180fcb268SAdrian Lang * function to join the text slices.
992f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
993f3f0262cSandi * lines between sections if needed (used on saving).
99415fae107Sandi *
99515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
996f3f0262cSandi */
997f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
998f3f0262cSandi    if($pretty) {
99980fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
10003272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
10013272d797SAndreas Gohr        ) {
100280fcb268SAdrian Lang            $pre .= "\n";
100380fcb268SAdrian Lang        }
100480fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
10053272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
10063272d797SAndreas Gohr        ) {
100780fcb268SAdrian Lang            $text .= "\n";
100880fcb268SAdrian Lang        }
1009f3f0262cSandi    }
1010f3f0262cSandi
1011f3f0262cSandi    return $pre.$text.$suf;
1012f3f0262cSandi}
1013f3f0262cSandi
1014f3f0262cSandi/**
1015a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1016a701424fSBen Coburn * Also directs changelog and attic updates.
101715fae107Sandi *
101815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
101971726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1020f3f0262cSandi */
1021b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1022a701424fSBen Coburn    /* Note to developers:
1023a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1024a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1025a701424fSBen Coburn       after any changes. External edits change the wiki page
1026a701424fSBen Coburn       directly without using php or dokuwiki.
1027a701424fSBen Coburn     */
1028f3f0262cSandi    global $conf;
1029f3f0262cSandi    global $lang;
103071726d78SBen Coburn    global $REV;
1031f3f0262cSandi    // ignore if no changes were made
1032f3f0262cSandi    if($text == rawWiki($id, '')) {
1033f3f0262cSandi        return;
1034f3f0262cSandi    }
1035f3f0262cSandi
1036f3f0262cSandi    $file        = wikiFN($id);
1037a701424fSBen Coburn    $old         = @filemtime($file); // from page
1038407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
1039d8186216SBen Coburn    $wasCreated  = !@file_exists($file);
104071726d78SBen Coburn    $wasReverted = ($REV == true);
1041e45b34cdSBen Coburn    $newRev      = false;
1042a701424fSBen Coburn    $oldRev      = getRevisions($id, -1, 1, 1024); // from changelog
1043a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1044a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
104546844156SBen Coburn        // add old revision to the attic if missing
104646844156SBen Coburn        saveOldRevision($id);
104746844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1048a701424fSBen Coburn        if($old > $oldRev) {
1049ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
105046844156SBen Coburn            // remove soon to be stale instructions
105146844156SBen Coburn            $cache = new cache_instructions($id, $file);
105246844156SBen Coburn            $cache->removeCache();
105346844156SBen Coburn        }
105446844156SBen Coburn    }
1055f3f0262cSandi
105671726d78SBen Coburn    if($wasRemoved) {
105730725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
105830725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
105930725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1060e45b34cdSBen Coburn        // pre-save deleted revision
1061e45b34cdSBen Coburn        @touch($file);
106246844156SBen Coburn        clearstatcache();
1063e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1064e1f3d9e1SEsther Brunner        // remove empty file
1065f3f0262cSandi        @unlink($file);
1066c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1067c5f92742SMichael Hamann        // purge non-persistant meta data
10683d1f9ec3SMichael Klier        p_purge_metadata($id);
1069f3f0262cSandi        $del = true;
10703ce054b3Sandi        // autoset summary on deletion
10713ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
107253d6ccfeSandi        // remove empty namespaces
1073cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1074cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1075f3f0262cSandi    } else {
1076cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1077cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
107846844156SBen Coburn        // pre-save the revision, to keep the attic in sync
107946844156SBen Coburn        $newRev = saveOldRevision($id);
1080f3f0262cSandi        $del    = false;
1081f3f0262cSandi    }
1082f3f0262cSandi
108371726d78SBen Coburn    // select changelog line type
108471726d78SBen Coburn    $extra = '';
1085ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
108671726d78SBen Coburn    if($wasReverted) {
1087ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
108871726d78SBen Coburn        $extra = $REV;
10893272d797SAndreas Gohr    } else if($wasCreated) {
10903272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
10913272d797SAndreas Gohr    } else if($wasRemoved) {
10923272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
10933272d797SAndreas Gohr    } else if($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) {
10943272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
10953272d797SAndreas Gohr    } //minor edits only for logged in users
109671726d78SBen Coburn
1097e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
109826a0801fSAndreas Gohr    // send notify mails
109990033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
110090033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1101f3f0262cSandi
1102ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
110398407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
11042eccbdaaSGina Haeussge
11052eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1106fe9ec250SChris Smith    if(useHeading('content')) {
11072eccbdaaSGina Haeussge        $pages = ft_backlinks($id);
11082eccbdaaSGina Haeussge        foreach($pages as $page) {
11092eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
11102eccbdaaSGina Haeussge            $cache->removeCache();
11112eccbdaaSGina Haeussge        }
11122eccbdaaSGina Haeussge    }
1113f3f0262cSandi}
1114f3f0262cSandi
1115f3f0262cSandi/**
1116f3f0262cSandi * moves the current version to the attic and returns its
1117f3f0262cSandi * revision date
111815fae107Sandi *
111915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1120f3f0262cSandi */
1121f3f0262cSandifunction saveOldRevision($id) {
1122f3f0262cSandi    global $conf;
1123f3f0262cSandi    $oldf = wikiFN($id);
1124f3f0262cSandi    if(!@file_exists($oldf)) return '';
1125f3f0262cSandi    $date = filemtime($oldf);
1126f3f0262cSandi    $newf = wikiFN($id, $date);
1127cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1128f3f0262cSandi    return $date;
1129f3f0262cSandi}
1130f3f0262cSandi
1131f3f0262cSandi/**
1132fde10de4SAdrian Lang * Sends a notify mail on page change or registration
113326a0801fSAndreas Gohr *
113426a0801fSAndreas Gohr * @param string     $id       The changed page
1135fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
11363272d797SAndreas Gohr * @param int|string $rev Old page revision
113726a0801fSAndreas Gohr * @param string     $summary  What changed
113890033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
113902a498e7Schris * @param array      $replace  Additional string substitutions, @KEY@ to be replaced by value
114015fae107Sandi *
11413272d797SAndreas Gohr * @return bool
114215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1143f3f0262cSandi */
114402a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1145f3f0262cSandi    global $conf;
1146b158d625SSteven Danz
11476df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
114826a0801fSAndreas Gohr    if($who == 'admin') {
11493272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
11502ed38036SAndreas Gohr        $tpl = 'mailtext';
115126a0801fSAndreas Gohr        $to  = $conf['notify'];
115226a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
115384c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
11543272d797SAndreas Gohr        if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return false; //skip minors
11558881fcc9SAdrian Lang        $data = array('id' => $id, 'addresslist' => '', 'self' => false);
11563272d797SAndreas Gohr        trigger_event(
11573272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1158835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
11593272d797SAndreas Gohr        );
11602ed38036SAndreas Gohr        $to = $data['addresslist'];
11612ed38036SAndreas Gohr        if(empty($to)) return false;
11622ed38036SAndreas Gohr        $tpl = 'subscr_single';
116326a0801fSAndreas Gohr    } else {
11643272d797SAndreas Gohr        return false; //just to be safe
116526a0801fSAndreas Gohr    }
116626a0801fSAndreas Gohr
11676df843eeSAndreas Gohr    // prepare content
11682ed38036SAndreas Gohr    $subscription = new Subscription();
11692ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1170f3f0262cSandi}
11712ed38036SAndreas Gohr
117215fae107Sandi/**
117371f7bde7SAndreas Gohr * extracts the query from a search engine referrer
117415fae107Sandi *
117515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
117671f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1177f3f0262cSandi */
1178f3f0262cSandifunction getGoogleQuery() {
1179c66972f2SAdrian Lang    if(!isset($_SERVER['HTTP_REFERER'])) {
1180c66972f2SAdrian Lang        return '';
1181c66972f2SAdrian Lang    }
1182f3f0262cSandi    $url = parse_url($_SERVER['HTTP_REFERER']);
1183f3f0262cSandi
1184079b3ac1SAndreas Gohr    // only handle common SEs
1185079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1186e4d8a516SKazutaka Miyasaka
1187079b3ac1SAndreas Gohr    $query = array();
1188e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1189e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1190e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1191f3f0262cSandi    parse_str($url['query'], $query);
1192e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1193e4d8a516SKazutaka Miyasaka
1194c66972f2SAdrian Lang    $q = '';
1195079b3ac1SAndreas Gohr    if(isset($query['q'])){
1196079b3ac1SAndreas Gohr        $q = $query['q'];
1197079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1198079b3ac1SAndreas Gohr        $q = $query['p'];
1199079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1200079b3ac1SAndreas Gohr        $q = $query['query'];
1201079b3ac1SAndreas Gohr    }
1202079b3ac1SAndreas Gohr    $q = trim($q);
1203f3f0262cSandi
1204079b3ac1SAndreas Gohr    if(!$q) return '';
12056531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1206f93b3b50SAndreas Gohr    return $q;
1207f3f0262cSandi}
1208f3f0262cSandi
1209f3f0262cSandi/**
121015fae107Sandi * Try to set correct locale
121115fae107Sandi *
1212095bfd5cSandi * @deprecated No longer used
121315fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1214f3f0262cSandi */
1215f3f0262cSandifunction setCorrectLocale() {
1216f3f0262cSandi    global $conf;
1217f3f0262cSandi    global $lang;
1218f3f0262cSandi
1219f3f0262cSandi    $enc = strtoupper($lang['encoding']);
1220f3f0262cSandi    foreach($lang['locales'] as $loc) {
1221f3f0262cSandi        //try locale
1222f3f0262cSandi        if(@setlocale(LC_ALL, $loc)) return;
1223f3f0262cSandi        //try loceale with encoding
1224f3f0262cSandi        if(@setlocale(LC_ALL, "$loc.$enc")) return;
1225f3f0262cSandi    }
1226f3f0262cSandi    //still here? try to set from environment
1227f3f0262cSandi    @setlocale(LC_ALL, "");
1228f3f0262cSandi}
1229f3f0262cSandi
1230f3f0262cSandi/**
1231f3f0262cSandi * Return the human readable size of a file
1232f3f0262cSandi *
1233f3f0262cSandi * @param       int    $size   A file size
1234f3f0262cSandi * @param       int    $dec    A number of decimal places
1235f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1236f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1237f3f0262cSandi * @version     1.0.0
1238f3f0262cSandi */
1239f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1240f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1241f3f0262cSandi    $count = count($sizes);
1242f3f0262cSandi    $i     = 0;
1243f3f0262cSandi
1244f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1245f3f0262cSandi        $size /= 1024;
1246f3f0262cSandi        $i++;
1247f3f0262cSandi    }
1248f3f0262cSandi
1249f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1250f3f0262cSandi}
1251f3f0262cSandi
125215fae107Sandi/**
1253c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1254c57e365eSAndreas Gohr *
1255c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1256c57e365eSAndreas Gohr */
1257c57e365eSAndreas Gohrfunction datetime_h($dt) {
1258c57e365eSAndreas Gohr    global $lang;
1259c57e365eSAndreas Gohr
1260c57e365eSAndreas Gohr    $ago = time() - $dt;
1261c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1262c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1263c57e365eSAndreas Gohr    }
1264c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1265c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1266c57e365eSAndreas Gohr    }
1267c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1268c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1269c57e365eSAndreas Gohr    }
1270c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1271c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1272c57e365eSAndreas Gohr    }
1273c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1274c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1275c57e365eSAndreas Gohr    }
1276c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1277c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1278c57e365eSAndreas Gohr    }
1279c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1280c57e365eSAndreas Gohr}
1281c57e365eSAndreas Gohr
1282c57e365eSAndreas Gohr/**
1283f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1284f2263577SAndreas Gohr *
1285f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1286f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1287f2263577SAndreas Gohr *
1288f2263577SAndreas Gohr * @see datetime_h
1289f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1290f2263577SAndreas Gohr */
1291f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1292f2263577SAndreas Gohr    global $conf;
1293f2263577SAndreas Gohr
1294f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1295f2263577SAndreas Gohr    $dt = (int) $dt;
1296f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1297f2263577SAndreas Gohr
1298f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1299f2263577SAndreas Gohr    return strftime($format, $dt);
1300f2263577SAndreas Gohr}
1301f2263577SAndreas Gohr
1302f2263577SAndreas Gohr/**
1303c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1304c4f79b71SMichael Hamann *
1305c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1306c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
130763703ba5SAndreas Gohr * @param int $int_date: current date in UNIX timestamp
13083272d797SAndreas Gohr * @return string
1309c4f79b71SMichael Hamann */
1310c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1311c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1312c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1313c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1314c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1315c4f79b71SMichael Hamann    return $date_mod;
1316c4f79b71SMichael Hamann}
1317c4f79b71SMichael Hamann
1318c4f79b71SMichael Hamann/**
131900a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
132000a7b5adSEsther Brunner *
132100a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
132200a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
132300a7b5adSEsther Brunner */
132400a7b5adSEsther Brunnerfunction obfuscate($email) {
132500a7b5adSEsther Brunner    global $conf;
132600a7b5adSEsther Brunner
132700a7b5adSEsther Brunner    switch($conf['mailguard']) {
132800a7b5adSEsther Brunner        case 'visible' :
132900a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
133000a7b5adSEsther Brunner            return strtr($email, $obfuscate);
133100a7b5adSEsther Brunner
133200a7b5adSEsther Brunner        case 'hex' :
133300a7b5adSEsther Brunner            $encode = '';
133449eb6e38SAndreas Gohr            $len    = strlen($email);
133549eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
133649eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
133749eb6e38SAndreas Gohr            }
133800a7b5adSEsther Brunner            return $encode;
133900a7b5adSEsther Brunner
134000a7b5adSEsther Brunner        case 'none' :
134100a7b5adSEsther Brunner        default :
134200a7b5adSEsther Brunner            return $email;
134300a7b5adSEsther Brunner    }
134400a7b5adSEsther Brunner}
134500a7b5adSEsther Brunner
134600a7b5adSEsther Brunner/**
134789541d4bSAndreas Gohr * Removes quoting backslashes
134889541d4bSAndreas Gohr *
134989541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
135089541d4bSAndreas Gohr */
135189541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
135289541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
135389541d4bSAndreas Gohr}
135489541d4bSAndreas Gohr
135573038c47SAndreas Gohr/**
135673038c47SAndreas Gohr * Convert php.ini shorthands to byte
135773038c47SAndreas Gohr *
135873038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
135973038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
136073038c47SAndreas Gohr */
136173038c47SAndreas Gohrfunction php_to_byte($v) {
136273038c47SAndreas Gohr    $l   = substr($v, -1);
136373038c47SAndreas Gohr    $ret = substr($v, 0, -1);
136473038c47SAndreas Gohr    switch(strtoupper($l)) {
136573038c47SAndreas Gohr        case 'P':
136673038c47SAndreas Gohr            $ret *= 1024;
136773038c47SAndreas Gohr        case 'T':
136873038c47SAndreas Gohr            $ret *= 1024;
136973038c47SAndreas Gohr        case 'G':
137073038c47SAndreas Gohr            $ret *= 1024;
137173038c47SAndreas Gohr        case 'M':
137273038c47SAndreas Gohr            $ret *= 1024;
137373038c47SAndreas Gohr        case 'K':
137473038c47SAndreas Gohr            $ret *= 1024;
137573038c47SAndreas Gohr            break;
137649cbd23eSOtto Vainio        default;
137749cbd23eSOtto Vainio            $ret *= 10;
137849cbd23eSOtto Vainio            break;
137973038c47SAndreas Gohr    }
138073038c47SAndreas Gohr    return $ret;
138173038c47SAndreas Gohr}
138273038c47SAndreas Gohr
1383546d3a99SAndreas Gohr/**
1384546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1385546d3a99SAndreas Gohr */
1386546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1387546d3a99SAndreas Gohr    return preg_quote($string, '/');
1388546d3a99SAndreas Gohr}
138973038c47SAndreas Gohr
1390bd2f6c2fSAndreas Gohr/**
1391bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1392bd2f6c2fSAndreas Gohr *
1393c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1394bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1395bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1396bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1397bd2f6c2fSAndreas Gohr *
1398bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1399bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1400bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1401bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1402bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
14033272d797SAndreas Gohr * @return string
1404bd2f6c2fSAndreas Gohr */
1405a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1406bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1407bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1408bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1409bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1410bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1411bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1412bd2f6c2fSAndreas Gohr}
1413bd2f6c2fSAndreas Gohr
1414dc58b6f4SAndy Webber/**
1415dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1416dc58b6f4SAndy Webber * in page footer and recent changes pages
1417dc58b6f4SAndy Webber *
1418dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1419dc58b6f4SAndy Webber */
1420dc58b6f4SAndy Webberfunction editorinfo($username) {
1421dc58b6f4SAndy Webber    global $conf;
1422dc58b6f4SAndy Webber    global $auth;
1423dc58b6f4SAndy Webber
1424dc58b6f4SAndy Webber    switch($conf['showuseras']) {
1425dc58b6f4SAndy Webber        case 'username':
1426dc58b6f4SAndy Webber        case 'email':
1427dc58b6f4SAndy Webber        case 'email_link':
1428173d78c4SAndreas Gohr            if($auth) $info = $auth->getUserData($username);
1429dc58b6f4SAndy Webber            break;
1430dc58b6f4SAndy Webber        default:
1431dc58b6f4SAndy Webber            return hsc($username);
1432dc58b6f4SAndy Webber    }
1433dc58b6f4SAndy Webber
1434dc58b6f4SAndy Webber    if(isset($info) && $info) {
1435dc58b6f4SAndy Webber        switch($conf['showuseras']) {
1436dc58b6f4SAndy Webber            case 'username':
1437dc58b6f4SAndy Webber                return hsc($info['name']);
1438dc58b6f4SAndy Webber            case 'email':
1439dc58b6f4SAndy Webber                return obfuscate($info['mail']);
1440dc58b6f4SAndy Webber            case 'email_link':
1441dc58b6f4SAndy Webber                $mail = obfuscate($info['mail']);
1442dc58b6f4SAndy Webber                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1443dc58b6f4SAndy Webber            default:
1444dc58b6f4SAndy Webber                return hsc($username);
1445dc58b6f4SAndy Webber        }
1446dc58b6f4SAndy Webber    } else {
1447dc58b6f4SAndy Webber        return hsc($username);
1448dc58b6f4SAndy Webber    }
1449066fee30SAndreas Gohr}
1450066fee30SAndreas Gohr
1451066fee30SAndreas Gohr/**
1452066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1453066fee30SAndreas Gohr * When no image exists, returns an empty string
1454066fee30SAndreas Gohr *
1455066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1456066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
14573272d797SAndreas Gohr * @return string
1458066fee30SAndreas Gohr */
1459066fee30SAndreas Gohrfunction license_img($type) {
1460066fee30SAndreas Gohr    global $license;
1461066fee30SAndreas Gohr    global $conf;
1462066fee30SAndreas Gohr    if(!$conf['license']) return '';
1463066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1464066fee30SAndreas Gohr    $lic   = $license[$conf['license']];
1465066fee30SAndreas Gohr    $try   = array();
1466066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1467066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1468066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1469066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1470066fee30SAndreas Gohr    }
1471066fee30SAndreas Gohr    foreach($try as $src) {
1472066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1473066fee30SAndreas Gohr    }
1474066fee30SAndreas Gohr    return '';
1475dc58b6f4SAndy Webber}
1476dc58b6f4SAndy Webber
147713c08e2fSMichael Klier/**
147813c08e2fSMichael Klier * Checks if the given amount of memory is available
147913c08e2fSMichael Klier *
148013c08e2fSMichael Klier * If the memory_get_usage() function is not available the
148113c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
148213c08e2fSMichael Klier *
148313c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
148413c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
14853272d797SAndreas Gohr *
14863272d797SAndreas Gohr * @param  int $mem  Size of memory you want to allocate in bytes
14873272d797SAndreas Gohr * @param int  $bytes
14883272d797SAndreas Gohr * @internal param int $used already allocated memory (see above)
14893272d797SAndreas Gohr * @return bool
149013c08e2fSMichael Klier */
149113c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
149213c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
149313c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
149413c08e2fSMichael Klier
149513c08e2fSMichael Klier    // parse limit to bytes
149613c08e2fSMichael Klier    $limit = php_to_byte($limit);
149713c08e2fSMichael Klier
149813c08e2fSMichael Klier    // get used memory if possible
149913c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
150013c08e2fSMichael Klier        $used = memory_get_usage();
150149eb6e38SAndreas Gohr    } else {
150249eb6e38SAndreas Gohr        $used = $bytes;
150313c08e2fSMichael Klier    }
150413c08e2fSMichael Klier
150513c08e2fSMichael Klier    if($used + $mem > $limit) {
150613c08e2fSMichael Klier        return false;
150713c08e2fSMichael Klier    }
150813c08e2fSMichael Klier
150913c08e2fSMichael Klier    return true;
151013c08e2fSMichael Klier}
151113c08e2fSMichael Klier
1512af2408d5SAndreas Gohr/**
1513af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1514af2408d5SAndreas Gohr *
1515af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1516af2408d5SAndreas Gohr *
1517af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1518af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1519af2408d5SAndreas Gohr */
1520af2408d5SAndreas Gohrfunction send_redirect($url) {
15210181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
15220181f021SAndreas Gohr    global $MSG;
15230181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
15240181f021SAndreas Gohr        //reopen session, store data and close session again
15250181f021SAndreas Gohr        @session_start();
15260181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
15270181f021SAndreas Gohr    }
15280181f021SAndreas Gohr
1529d4869846SAndreas Gohr    // always close the session
1530d4869846SAndreas Gohr    session_write_close();
1531d4869846SAndreas Gohr
1532c10dcb7dSAndreas Gohr    // work around IE bug
1533c10dcb7dSAndreas Gohr    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
1534c10dcb7dSAndreas Gohr    list($url, $hash) = explode('#', $url);
1535c10dcb7dSAndreas Gohr    if($hash) {
1536c10dcb7dSAndreas Gohr        if(strpos($url, '?')) {
1537c10dcb7dSAndreas Gohr            $url = $url.'&#'.$hash;
1538c10dcb7dSAndreas Gohr        } else {
1539c10dcb7dSAndreas Gohr            $url = $url.'?&#'.$hash;
1540c10dcb7dSAndreas Gohr        }
1541c10dcb7dSAndreas Gohr    }
1542c10dcb7dSAndreas Gohr
1543af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1544af2408d5SAndreas Gohr    if(isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1545af2408d5SAndreas Gohr        (strpos($_SERVER['GATEWAY_INTERFACE'], 'CGI') !== false) &&
1546af2408d5SAndreas Gohr        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
15473272d797SAndreas Gohr        $matches[1] < 6
15483272d797SAndreas Gohr    ) {
1549af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1550af2408d5SAndreas Gohr    } else {
1551af2408d5SAndreas Gohr        header('Location: '.$url);
1552af2408d5SAndreas Gohr    }
1553af2408d5SAndreas Gohr    exit;
1554af2408d5SAndreas Gohr}
1555af2408d5SAndreas Gohr
15565b75cd1fSAdrian Lang/**
15575b75cd1fSAdrian Lang * Validate a value using a set of valid values
15585b75cd1fSAdrian Lang *
15595b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
15605b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
15615b75cd1fSAdrian Lang * default is specified, throws an exception.
15625b75cd1fSAdrian Lang *
15635b75cd1fSAdrian Lang * @param string $param        The name of the parameter
15645b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
15655b75cd1fSAdrian Lang *                             be marked by the key “default”.
15665b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
15675b75cd1fSAdrian Lang *                             or $_GET)
15685b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
15695b75cd1fSAdrian Lang *
15703272d797SAndreas Gohr * @throws Exception
15713272d797SAndreas Gohr * @return mixed
15725b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
15735b75cd1fSAdrian Lang */
15745b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
15755b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
15765b75cd1fSAdrian Lang        return $array[$param];
15775b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
15785b75cd1fSAdrian Lang        return $valid_values['default'];
15795b75cd1fSAdrian Lang    } else {
15805b75cd1fSAdrian Lang        throw new Exception($exc);
15815b75cd1fSAdrian Lang    }
15825b75cd1fSAdrian Lang}
15835b75cd1fSAdrian Lang
158463703ba5SAndreas Gohr/**
158563703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1586646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
158763703ba5SAndreas Gohr */
1588554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1589646a531aSChristopher Smith    $enc_pref = urlencode($pref);
1590646a531aSChristopher Smith    if(strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1591554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
159263703ba5SAndreas Gohr        $cnt   = count($parts);
159363703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1594646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1595646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1596554a8c9fSAdrian Lang            }
1597554a8c9fSAdrian Lang        }
1598554a8c9fSAdrian Lang    }
1599554a8c9fSAdrian Lang    return $default;
1600554a8c9fSAdrian Lang}
1601554a8c9fSAdrian Lang
16023c94d07bSAnika Henke/**
16033c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
160436ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
16053c94d07bSAnika Henke */
16063c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
16073c94d07bSAnika Henke    global $conf;
16083c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
16093c94d07bSAnika Henke    $cookieVal = '';
16103c94d07bSAnika Henke
16113c94d07bSAnika Henke    if($orig && ($orig != $val)) {
16123c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
16133c94d07bSAnika Henke        $cnt   = count($parts);
161436ec377eSChristopher Smith        // urlencode $pref for the comparison
161536ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
16163c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
161736ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
161836ec377eSChristopher Smith                $parts[$i + 1] = rawurlencode($val);
161950f261f7SMichael Hamann                break;
16203c94d07bSAnika Henke            }
16213c94d07bSAnika Henke        }
16223c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
16233c94d07bSAnika Henke    } else if (!$orig) {
162436ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
16253c94d07bSAnika Henke    }
16263c94d07bSAnika Henke
16273c94d07bSAnika Henke    if (!empty($cookieVal)) {
162850f261f7SMichael Hamann        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, DOKU_BASE, '', ($conf['securecookie'] && is_ssl()));
16293c94d07bSAnika Henke    }
16303c94d07bSAnika Henke}
16313c94d07bSAnika Henke
1632e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1633