xref: /dokuwiki/inc/common.php (revision 4bde2196a1e3572cead3f4d4e4b6a5a752bd62b3)
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() {
59a132f948SAndreas Gohr    return PassHash::hmac('md5', session_id().$_SERVER['REMOTE_USER'], auth_cookiesalt());
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;
67443e135dSChristopher Smith    if(empty($_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 *
9115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
927e87a794SChristopher 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
1517e87a794SChristopher Smith    if(isset($_SERVER['REMOTE_USER'])) {
1527e87a794SChristopher Smith        $sub = new Subscription();
1537e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
1547e87a794SChristopher Smith    } else {
1557e87a794SChristopher Smith        $info['subscribed'] = false;
1567e87a794SChristopher Smith    }
1577e87a794SChristopher 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)) {
1645c2eed9aSlisps            //$REV = ''; //if we enter a rev we want to see that revision (inc media files)
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
190f523c971SGerrit Uitslag    $pagelog = new PageRevisionLog($ID, 1024);
191652610a2Sandi    if($REV) {
192f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
193652610a2Sandi    } else {
194aa27cf05SAndreas Gohr        if(is_array($info['meta']['last_change'])) {
195aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
196aa27cf05SAndreas Gohr        } else {
197f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
198cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
199cd00a034SBen Coburn            if($revinfo !== false) {
200cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
201cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
202cd00a034SBen Coburn            }
203cd00a034SBen Coburn        }
204cd00a034SBen Coburn    }
205cd00a034SBen Coburn    //and check for an external edit
206cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
207cd00a034SBen Coburn        // cached changelog line no longer valid
208cd00a034SBen Coburn        $revinfo                     = false;
209cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
210cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
211652610a2Sandi    }
212bb4866bdSchris
213652610a2Sandi    $info['ip']   = $revinfo['ip'];
214652610a2Sandi    $info['user'] = $revinfo['user'];
215652610a2Sandi    $info['sum']  = $revinfo['sum'];
21671726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
217ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
21859f257aeSchris
21988f522e9Sandi    if($revinfo['user']) {
22088f522e9Sandi        $info['editor'] = $revinfo['user'];
22188f522e9Sandi    } else {
22288f522e9Sandi        $info['editor'] = $revinfo['ip'];
22388f522e9Sandi    }
224652610a2Sandi
225ee4c4a1bSAndreas Gohr    // draft
226ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
227ee4c4a1bSAndreas Gohr    if(@file_exists($draft)) {
228ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
229ee4c4a1bSAndreas Gohr            // remove stale draft
230ee4c4a1bSAndreas Gohr            @unlink($draft);
231ee4c4a1bSAndreas Gohr        } else {
232ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
233ee4c4a1bSAndreas Gohr        }
234ee4c4a1bSAndreas Gohr    }
235ee4c4a1bSAndreas Gohr
2361015a57dSChristopher Smith    return $info;
2371015a57dSChristopher Smith}
2381015a57dSChristopher Smith
2391015a57dSChristopher Smith/**
2401015a57dSChristopher Smith * Return information about the current media item as an associative array.
2411015a57dSChristopher Smith */
2421015a57dSChristopher Smithfunction mediainfo(){
2431015a57dSChristopher Smith    global $NS;
2441015a57dSChristopher Smith    global $IMG;
2451015a57dSChristopher Smith
2461015a57dSChristopher Smith    $info = basicinfo("$NS:*");
2471015a57dSChristopher Smith    $info['image'] = $IMG;
2481c548ebeSAndreas Gohr
249f3f0262cSandi    return $info;
250f3f0262cSandi}
251f3f0262cSandi
252f3f0262cSandi/**
2532684e50aSAndreas Gohr * Build an string of URL parameters
2542684e50aSAndreas Gohr *
2552684e50aSAndreas Gohr * @author Andreas Gohr
2562684e50aSAndreas Gohr */
257b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
2582684e50aSAndreas Gohr    $url = '';
2592684e50aSAndreas Gohr    $amp = false;
2602684e50aSAndreas Gohr    foreach($params as $key => $val) {
261b174aeaeSchris        if($amp) $url .= $sep;
2622684e50aSAndreas Gohr
26385e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
2643a50618cSgweissbach        $url .= rawurlencode((string) $val);
2652684e50aSAndreas Gohr        $amp = true;
2662684e50aSAndreas Gohr    }
2672684e50aSAndreas Gohr    return $url;
2682684e50aSAndreas Gohr}
2692684e50aSAndreas Gohr
2702684e50aSAndreas Gohr/**
2712684e50aSAndreas Gohr * Build an string of html tag attributes
2722684e50aSAndreas Gohr *
2737bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2747bff22c0SAndreas Gohr *
2752684e50aSAndreas Gohr * @author Andreas Gohr
2762684e50aSAndreas Gohr */
2774b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
2782684e50aSAndreas Gohr    $url   = '';
2799063ec14SAdrian Lang    $white = false;
2802684e50aSAndreas Gohr    foreach($params as $key => $val) {
2817bff22c0SAndreas Gohr        if($key{0} == '_') continue;
282b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
2839063ec14SAdrian Lang        if($white) $url .= ' ';
2847bff22c0SAndreas Gohr
2852684e50aSAndreas Gohr        $url .= $key.'="';
2862684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
2872684e50aSAndreas Gohr        $url .= '"';
2889063ec14SAdrian Lang        $white = true;
2892684e50aSAndreas Gohr    }
2902684e50aSAndreas Gohr    return $url;
2912684e50aSAndreas Gohr}
2922684e50aSAndreas Gohr
2932684e50aSAndreas Gohr/**
29415fae107Sandi * This builds the breadcrumb trail and returns it as array
29515fae107Sandi *
29615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
297f3f0262cSandi */
298f3f0262cSandifunction breadcrumbs() {
2998746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3008746e727Sandi    static $crumbs = null;
3018746e727Sandi    if($crumbs != null) return $crumbs;
3028746e727Sandi
303f3f0262cSandi    global $ID;
304f3f0262cSandi    global $ACT;
305f3f0262cSandi    global $conf;
306f3f0262cSandi
307f3f0262cSandi    //first visit?
308c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
309f3f0262cSandi    //we only save on show and existing wiki documents
310a77f5846Sjan    $file = wikiFN($ID);
311a77f5846Sjan    if($ACT != 'show' || !@file_exists($file)) {
312e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
313f3f0262cSandi        return $crumbs;
314f3f0262cSandi    }
315a77f5846Sjan
316a77f5846Sjan    // page names
3171a84a0f3SAnika Henke    $name = noNSorNS($ID);
318fe9ec250SChris Smith    if(useHeading('navigation')) {
319a77f5846Sjan        // get page title
32067c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
321a77f5846Sjan        if($title) {
322a77f5846Sjan            $name = $title;
323a77f5846Sjan        }
324a77f5846Sjan    }
325a77f5846Sjan
326f3f0262cSandi    //remove ID from array
327a77f5846Sjan    if(isset($crumbs[$ID])) {
328a77f5846Sjan        unset($crumbs[$ID]);
329f3f0262cSandi    }
330f3f0262cSandi
331f3f0262cSandi    //add to array
332a77f5846Sjan    $crumbs[$ID] = $name;
333f3f0262cSandi    //reduce size
334f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
335f3f0262cSandi        array_shift($crumbs);
336f3f0262cSandi    }
337f3f0262cSandi    //save to session
338e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
339f3f0262cSandi    return $crumbs;
340f3f0262cSandi}
341f3f0262cSandi
342f3f0262cSandi/**
34315fae107Sandi * Filter for page IDs
34415fae107Sandi *
345f3f0262cSandi * This is run on a ID before it is outputted somewhere
346f3f0262cSandi * currently used to replace the colon with something else
347907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
348907f24f7SAndreas Gohr *
349907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
350907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
351907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
35215fae107Sandi *
35349c713a3Sandi * Urlencoding is ommitted when the second parameter is false
35449c713a3Sandi *
35515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
356f3f0262cSandi */
35749c713a3Sandifunction idfilter($id, $ue = true) {
358f3f0262cSandi    global $conf;
359f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
360f3f0262cSandi        $id = strtr($id, ':', '/');
361f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
36258bedc8aSborekb        $conf['userewrite'] &&
36358bedc8aSborekb        strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') === false
3643272d797SAndreas Gohr    ) {
365f3f0262cSandi        $id = strtr($id, ':', ';');
366f3f0262cSandi    }
36749c713a3Sandi    if($ue) {
368b6c6979fSAndreas Gohr        $id = rawurlencode($id);
369f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
370f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
37149c713a3Sandi    }
372f3f0262cSandi    return $id;
373f3f0262cSandi}
374f3f0262cSandi
375f3f0262cSandi/**
376ed7b5f09Sandi * This builds a link to a wikipage
37715fae107Sandi *
3786c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3796c7843b5Sandi * given in $more
3806c7843b5Sandi *
38115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
382f3f0262cSandi */
38316f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
384f3f0262cSandi    global $conf;
38516f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
386*4bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
38716f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
3886de3759aSAndreas Gohr    } else {
38916f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
3906de3759aSAndreas Gohr    }
39116f15a81SDominik Eckelmann    if($id === '') {
39216f15a81SDominik Eckelmann        $id = $conf['start'];
39316f15a81SDominik Eckelmann    }
394f3f0262cSandi    $id = idfilter($id);
39516f15a81SDominik Eckelmann    if($absolute) {
396ed7b5f09Sandi        $xlink = DOKU_URL;
397ed7b5f09Sandi    } else {
398ed7b5f09Sandi        $xlink = DOKU_BASE;
399ed7b5f09Sandi    }
400f3f0262cSandi
4016c7843b5Sandi    if($conf['userewrite'] == 2) {
4026c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
40316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4046c7843b5Sandi    } elseif($conf['userewrite']) {
405f3f0262cSandi        $xlink .= $id;
40616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
407bce3726dSAndreas Gohr    } elseif($id) {
4086c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
40916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
410bce3726dSAndreas Gohr    } else {
411bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
41216f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
413f3f0262cSandi    }
414f3f0262cSandi
415f3f0262cSandi    return $xlink;
416f3f0262cSandi}
417f3f0262cSandi
418f3f0262cSandi/**
419f5c2808fSBen Coburn * This builds a link to an alternate page format
420f5c2808fSBen Coburn *
421f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
422f5c2808fSBen Coburn *
423f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
424f5c2808fSBen Coburn */
425f5c2808fSBen Coburnfunction exportlink($id = '', $format = 'raw', $more = '', $abs = false, $sep = '&amp;') {
426f5c2808fSBen Coburn    global $conf;
427f5c2808fSBen Coburn    if(is_array($more)) {
428f5c2808fSBen Coburn        $more = buildURLparams($more, $sep);
429f5c2808fSBen Coburn    } else {
430f5c2808fSBen Coburn        $more = str_replace(',', $sep, $more);
431f5c2808fSBen Coburn    }
432f5c2808fSBen Coburn
433f5c2808fSBen Coburn    $format = rawurlencode($format);
434f5c2808fSBen Coburn    $id     = idfilter($id);
435f5c2808fSBen Coburn    if($abs) {
436f5c2808fSBen Coburn        $xlink = DOKU_URL;
437f5c2808fSBen Coburn    } else {
438f5c2808fSBen Coburn        $xlink = DOKU_BASE;
439f5c2808fSBen Coburn    }
440f5c2808fSBen Coburn
441f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
442f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
443f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
444f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
445f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
446f5c2808fSBen Coburn        if($more) $xlink .= '?'.$more;
447f5c2808fSBen Coburn    } else {
448f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
449f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
450f5c2808fSBen Coburn    }
451f5c2808fSBen Coburn
452f5c2808fSBen Coburn    return $xlink;
453f5c2808fSBen Coburn}
454f5c2808fSBen Coburn
455f5c2808fSBen Coburn/**
4566de3759aSAndreas Gohr * Build a link to a media file
4576de3759aSAndreas Gohr *
4586de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4598c08db0aSAndreas Gohr *
4608c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4618c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4628c08db0aSAndreas Gohr *
4633272d797SAndreas Gohr * @param string  $id     the media file id or URL
4643272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
4653272d797SAndreas Gohr * @param bool    $direct link to detail page if false
4663272d797SAndreas Gohr * @param string  $sep    URL parameter separator
4673272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
4683272d797SAndreas Gohr * @return string
4696de3759aSAndreas Gohr */
47055b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
4716de3759aSAndreas Gohr    global $conf;
472b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
473826d2766SKlap-in    if(!$isexternalimage) {
474826d2766SKlap-in        $id = cleanID($id);
475826d2766SKlap-in    }
476826d2766SKlap-in
4776de3759aSAndreas Gohr    if(is_array($more)) {
4780f4e0092SChristopher Smith        // add token for resized images
479443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
4800f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
4810f4e0092SChristopher Smith        }
4828c08db0aSAndreas Gohr        // strip defaults for shorter URLs
4838c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
484443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
485443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
4868c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
487b174aeaeSchris        $more = buildURLparams($more, $sep);
4886de3759aSAndreas Gohr    } else {
4895e7db1e2SChristopher Smith        $matches = array();
490cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
4915e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
4925e7db1e2SChristopher Smith            foreach ($matches as $match){
4935e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
4945e7db1e2SChristopher Smith            }
495cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
496cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
4975e7db1e2SChristopher Smith        }
4988c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
4998c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
500b174aeaeSchris        $more = str_replace(',', $sep, $more);
5016de3759aSAndreas Gohr    }
5026de3759aSAndreas Gohr
50355b2b31bSAndreas Gohr    if($abs) {
50455b2b31bSAndreas Gohr        $xlink = DOKU_URL;
50555b2b31bSAndreas Gohr    } else {
5066de3759aSAndreas Gohr        $xlink = DOKU_BASE;
50755b2b31bSAndreas Gohr    }
5086de3759aSAndreas Gohr
5096de3759aSAndreas Gohr    // external URLs are always direct without rewriting
510826d2766SKlap-in    if($isexternalimage) {
5116de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
512cc036f74SKlap-in        $xlink .= '?'.$more;
513b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
5146de3759aSAndreas Gohr        return $xlink;
5156de3759aSAndreas Gohr    }
5166de3759aSAndreas Gohr
5176de3759aSAndreas Gohr    $id = idfilter($id);
5186de3759aSAndreas Gohr
5196de3759aSAndreas Gohr    // decide on scriptname
5206de3759aSAndreas Gohr    if($direct) {
5216de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5226de3759aSAndreas Gohr            $script = '_media';
5236de3759aSAndreas Gohr        } else {
5246de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
5256de3759aSAndreas Gohr        }
5266de3759aSAndreas Gohr    } else {
5276de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5286de3759aSAndreas Gohr            $script = '_detail';
5296de3759aSAndreas Gohr        } else {
5306de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
5316de3759aSAndreas Gohr        }
5326de3759aSAndreas Gohr    }
5336de3759aSAndreas Gohr
5346de3759aSAndreas Gohr    // build URL based on rewrite mode
5356de3759aSAndreas Gohr    if($conf['userewrite']) {
5366de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
5376de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
5386de3759aSAndreas Gohr    } else {
5396de3759aSAndreas Gohr        if($more) {
540a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
541b174aeaeSchris            $xlink .= $sep.'media='.$id;
5426de3759aSAndreas Gohr        } else {
543a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
5446de3759aSAndreas Gohr        }
5456de3759aSAndreas Gohr    }
5466de3759aSAndreas Gohr
5476de3759aSAndreas Gohr    return $xlink;
5486de3759aSAndreas Gohr}
5496de3759aSAndreas Gohr
5506de3759aSAndreas Gohr/**
55125ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
55215fae107Sandi *
55325ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
55425ca5b17SAndreas Gohr *
55515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
556f3f0262cSandi */
55725ca5b17SAndreas Gohrfunction script() {
558ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
559f3f0262cSandi}
560f3f0262cSandi
561f3f0262cSandi/**
56215fae107Sandi * Spamcheck against wordlist
56315fae107Sandi *
564f3f0262cSandi * Checks the wikitext against a list of blocked expressions
565f3f0262cSandi * returns true if the text contains any bad words
56615fae107Sandi *
567e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
568e403cc58SMichael Klier *
569e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
570e403cc58SMichael Klier *  and gain information about the user who was blocked.
571e403cc58SMichael Klier *
572e403cc58SMichael Klier *  Event data:
573e403cc58SMichael Klier *    data['matches']  - array of matches
574e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
575e403cc58SMichael Klier *      [ip]           - ip address
576e403cc58SMichael Klier *      [user]         - username (if logged in)
577e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
578e403cc58SMichael Klier *      [name]         - real name (if logged in)
579e403cc58SMichael Klier *
58015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5816dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
5826dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
5836dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
584f3f0262cSandi */
5856dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
586f3f0262cSandi    global $TEXT;
5876dffa0e0SAndreas Gohr    global $PRE;
5886dffa0e0SAndreas Gohr    global $SUF;
589e0086ca2SAndreas Gohr    global $SUM;
590f3f0262cSandi    global $conf;
591e403cc58SMichael Klier    global $INFO;
592f3f0262cSandi
593f3f0262cSandi    if(!$conf['usewordblock']) return false;
594f3f0262cSandi
595e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
5966dffa0e0SAndreas Gohr
597041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
5986dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
599041d1964SAndreas Gohr
600b9ac8716Schris    $wordblocks = getWordblocks();
6013e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
6023e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
6033e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
6043e2965d7Sandi        // backreferences are used - the maximum is 99
6053e2965d7Sandi        // this is very bad performancewise and may even be too high still
6063e2965d7Sandi        $chunksize = 40;
6073e2965d7Sandi    } else {
608a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
6093e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
610a51d08efSAndreas Gohr        $chunksize = 200;
6113e2965d7Sandi    }
612b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
613f3f0262cSandi        $re = array();
61449eb6e38SAndreas Gohr        // build regexp from blocks
615f3f0262cSandi        foreach($blocks as $block) {
616f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
617f3f0262cSandi            $block = trim($block);
618f3f0262cSandi            if(empty($block)) continue;
619f3f0262cSandi            $re[] = $block;
620f3f0262cSandi        }
621e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
622e403cc58SMichael Klier            // prepare event data
623e403cc58SMichael Klier            $data['matches']        = $matches;
624e403cc58SMichael Klier            $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
625e403cc58SMichael Klier            if($_SERVER['REMOTE_USER']) {
626e403cc58SMichael Klier                $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
627e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
628e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
629e403cc58SMichael Klier            }
630e403cc58SMichael Klier            $callback = create_function('', 'return true;');
631e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
632b9ac8716Schris        }
633703f6fdeSandi    }
634f3f0262cSandi    return false;
635f3f0262cSandi}
636f3f0262cSandi
637f3f0262cSandi/**
63815fae107Sandi * Return the IP of the client
63915fae107Sandi *
6406d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
64115fae107Sandi *
6426d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
6436d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
6446d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
6456d8affe6SAndreas Gohr * headers
6466d8affe6SAndreas Gohr *
64715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6483272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
6493272d797SAndreas Gohr * @return string
650f3f0262cSandi */
6516d8affe6SAndreas Gohrfunction clientIP($single = false) {
6526d8affe6SAndreas Gohr    $ip   = array();
6536d8affe6SAndreas Gohr    $ip[] = $_SERVER['REMOTE_ADDR'];
654bb4866bdSchris    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
6555cbeffbfSMarcel Pennewiß        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_FORWARDED_FOR'])));
656bb4866bdSchris    if(!empty($_SERVER['HTTP_X_REAL_IP']))
6575cbeffbfSMarcel Pennewiß        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_REAL_IP'])));
6586d8affe6SAndreas Gohr
659dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
660dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
661dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
662dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
663dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
664dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
665dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
666dc14c6d1SGuy Brand    $IPv6Address =
667dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
668dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
669dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
670dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
671dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
672dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
673dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
674dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
675dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
676dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
677dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
678dc14c6d1SGuy Brand
6796d8affe6SAndreas Gohr    // remove any non-IP stuff
6806d8affe6SAndreas Gohr    $cnt   = count($ip);
6814ff28443Schris    $match = array();
6826d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
683dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
6844ff28443Schris            $ip[$i] = $match[0];
6854ff28443Schris        } else {
6864ff28443Schris            $ip[$i] = '';
6874ff28443Schris        }
6886d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
689f3f0262cSandi    }
6906d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
6916d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6926d8affe6SAndreas Gohr
6936d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
6946d8affe6SAndreas Gohr
6956d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
6966d8affe6SAndreas Gohr    $ip = array_reverse($ip);
6976d8affe6SAndreas Gohr    foreach($ip as $i) {
6982343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
6996d8affe6SAndreas Gohr            continue;
7006d8affe6SAndreas Gohr        } else {
7016d8affe6SAndreas Gohr            return $i;
7026d8affe6SAndreas Gohr        }
7036d8affe6SAndreas Gohr    }
7046d8affe6SAndreas Gohr    // still here? just use the first (last) address
7056d8affe6SAndreas Gohr    return $ip[0];
706f3f0262cSandi}
707f3f0262cSandi
708f3f0262cSandi/**
7091c548ebeSAndreas Gohr * Check if the browser is on a mobile device
7101c548ebeSAndreas Gohr *
7111c548ebeSAndreas Gohr * Adapted from the example code at url below
7121c548ebeSAndreas Gohr *
7131c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
7141c548ebeSAndreas Gohr */
7151c548ebeSAndreas Gohrfunction clientismobile() {
7161c548ebeSAndreas Gohr
7171c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
7181c548ebeSAndreas Gohr
7191c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i', $_SERVER['HTTP_ACCEPT'])) return true;
7201c548ebeSAndreas Gohr
7211c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
7221c548ebeSAndreas Gohr
7231c548ebeSAndreas 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';
7241c548ebeSAndreas Gohr
7251c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i", $_SERVER['HTTP_USER_AGENT'])) return true;
7261c548ebeSAndreas Gohr
7271c548ebeSAndreas Gohr    return false;
7281c548ebeSAndreas Gohr}
7291c548ebeSAndreas Gohr
7301c548ebeSAndreas Gohr/**
73163211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
73263211f61SGlen Harris *
73322ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
73422ef1e32SAndreas Gohr *
73563211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
7363272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
7373272d797SAndreas Gohr * @return string a comma separated list of hostnames
73863211f61SGlen Harris */
73963211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
74022ef1e32SAndreas Gohr    global $conf;
74122ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
74222ef1e32SAndreas Gohr
74363211f61SGlen Harris    $hosts = array();
74463211f61SGlen Harris    $ips   = explode(',', $ips);
745551a720fSMichael Klier
746551a720fSMichael Klier    if(is_array($ips)) {
7473886270dSAndreas Gohr        foreach($ips as $ip) {
748551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
74963211f61SGlen Harris        }
750551a720fSMichael Klier        return join(',', $hosts);
751551a720fSMichael Klier    } else {
752551a720fSMichael Klier        return gethostbyaddr(trim($ips));
753551a720fSMichael Klier    }
75463211f61SGlen Harris}
75563211f61SGlen Harris
75663211f61SGlen Harris/**
75715fae107Sandi * Checks if a given page is currently locked.
75815fae107Sandi *
759f3f0262cSandi * removes stale lockfiles
76015fae107Sandi *
76115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
762f3f0262cSandi */
763f3f0262cSandifunction checklock($id) {
764f3f0262cSandi    global $conf;
765c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
766f3f0262cSandi
767f3f0262cSandi    //no lockfile
768f3f0262cSandi    if(!@file_exists($lock)) return false;
769f3f0262cSandi
770f3f0262cSandi    //lockfile expired
771f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
772d8186216SBen Coburn        @unlink($lock);
773f3f0262cSandi        return false;
774f3f0262cSandi    }
775f3f0262cSandi
776f3f0262cSandi    //my own lock
77785fef7e2SAndreas Gohr    list($ip, $session) = explode("\n", io_readFile($lock));
77885fef7e2SAndreas Gohr    if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
779f3f0262cSandi        return false;
780f3f0262cSandi    }
781f3f0262cSandi
782f3f0262cSandi    return $ip;
783f3f0262cSandi}
784f3f0262cSandi
785f3f0262cSandi/**
78615fae107Sandi * Lock a page for editing
78715fae107Sandi *
78815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
789f3f0262cSandi */
790f3f0262cSandifunction lock($id) {
791544ed901SDaniel Calviño Sánchez    global $conf;
792544ed901SDaniel Calviño Sánchez
793544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
794544ed901SDaniel Calviño Sánchez        return;
795544ed901SDaniel Calviño Sánchez    }
796544ed901SDaniel Calviño Sánchez
797c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
798f3f0262cSandi    if($_SERVER['REMOTE_USER']) {
799f3f0262cSandi        io_saveFile($lock, $_SERVER['REMOTE_USER']);
800f3f0262cSandi    } else {
80185fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
802f3f0262cSandi    }
803f3f0262cSandi}
804f3f0262cSandi
805f3f0262cSandi/**
80615fae107Sandi * Unlock a page if it was locked by the user
807f3f0262cSandi *
80815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
8093272d797SAndreas Gohr * @param string $id page id to unlock
81015fae107Sandi * @return bool true if a lock was removed
811f3f0262cSandi */
812f3f0262cSandifunction unlock($id) {
813c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
814f3f0262cSandi    if(@file_exists($lock)) {
81585fef7e2SAndreas Gohr        list($ip, $session) = explode("\n", io_readFile($lock));
81685fef7e2SAndreas Gohr        if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
817f3f0262cSandi            @unlink($lock);
818f3f0262cSandi            return true;
819f3f0262cSandi        }
820f3f0262cSandi    }
821f3f0262cSandi    return false;
822f3f0262cSandi}
823f3f0262cSandi
824f3f0262cSandi/**
825f3f0262cSandi * convert line ending to unix format
826f3f0262cSandi *
8276db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
8286db7468bSAndreas Gohr *
82915fae107Sandi * @see    formText() for 2crlf conversion
83015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
831f3f0262cSandi */
832f3f0262cSandifunction cleanText($text) {
833f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
8346db7468bSAndreas Gohr
8356db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
8366db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
8376db7468bSAndreas Gohr    // but might actually fix the problem in many cases
8386db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
8396db7468bSAndreas Gohr
840f3f0262cSandi    return $text;
841f3f0262cSandi}
842f3f0262cSandi
843f3f0262cSandi/**
844f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
845f3f0262cSandi * It also converts line endings to Windows format which is
846f3f0262cSandi * pseudo standard for webforms.
847f3f0262cSandi *
84815fae107Sandi * @see    cleanText() for 2unix conversion
84915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
850f3f0262cSandi */
851f3f0262cSandifunction formText($text) {
8525b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
853f3f0262cSandi    return htmlspecialchars($text);
854f3f0262cSandi}
855f3f0262cSandi
856f3f0262cSandi/**
85715fae107Sandi * Returns the specified local text in raw format
85815fae107Sandi *
85915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
860f3f0262cSandi */
8612adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
8622adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
863f3f0262cSandi}
864f3f0262cSandi
865f3f0262cSandi/**
866f3f0262cSandi * Returns the raw WikiText
86715fae107Sandi *
86815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
869f3f0262cSandi */
870f3f0262cSandifunction rawWiki($id, $rev = '') {
871cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
872f3f0262cSandi}
873f3f0262cSandi
874f3f0262cSandi/**
8757146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
8767146cee2SAndreas Gohr *
8777b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
8787146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8797146cee2SAndreas Gohr */
880fe17917eSAdrian Langfunction pageTemplate($id) {
881a15ce62dSEsther Brunner    global $conf;
882e29549feSAndreas Gohr
883fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
884e29549feSAndreas Gohr
8857b84afa2SAndreas Gohr    // prepare initial event data
8867b84afa2SAndreas Gohr    $data = array(
8877b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
8887b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
8897b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
8907b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
8917b84afa2SAndreas Gohr    );
8927b84afa2SAndreas Gohr
8937b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
8947b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
8957b84afa2SAndreas Gohr        // the before event might have loaded the content already
8967b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
8977b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
8987b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
899fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
900e29549feSAndreas Gohr                if(@file_exists($path.'/_template.txt')) {
9017b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
902e29549feSAndreas Gohr                } else {
903e29549feSAndreas Gohr                    // search upper namespaces for templates
904e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
905e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
906e29549feSAndreas Gohr                        if(@file_exists($path.'/__template.txt')) {
9077b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
908e29549feSAndreas Gohr                            break;
909e29549feSAndreas Gohr                        }
910e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
911e29549feSAndreas Gohr                    }
912e29549feSAndreas Gohr                }
9137b84afa2SAndreas Gohr            }
9147b84afa2SAndreas Gohr            // load the content
9153d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
9167b84afa2SAndreas Gohr        }
917a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
9187b84afa2SAndreas Gohr    }
9197b84afa2SAndreas Gohr    $evt->advise_after();
9207b84afa2SAndreas Gohr    unset($evt);
9217b84afa2SAndreas Gohr
922fe17917eSAdrian Lang    return $data['tpl'];
9232b1223ecSAdrian Lang}
9242b1223ecSAdrian Lang
9252b1223ecSAdrian Lang/**
9262b1223ecSAdrian Lang * Performs common page template replacements
9277b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
9282b1223ecSAdrian Lang *
9292b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
9302b1223ecSAdrian Lang */
931d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
9323272d797SAndreas Gohr    /**
9333272d797SAndreas Gohr     * @var string $id        the id of the page to be created
9343272d797SAndreas Gohr     * @var string $tpl       the text used as template
9353272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
9363272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
9373272d797SAndreas Gohr     */
938fe17917eSAdrian Lang    extract($data);
939fe17917eSAdrian Lang
940b856f7dfSAdrian Lang    global $USERINFO;
941bce53b1fSAdrian Lang    global $conf;
942e29549feSAndreas Gohr
943e29549feSAndreas Gohr    // replace placeholders
94426ece5a7SAndreas Gohr    $file = noNS($id);
94537c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
94626ece5a7SAndreas Gohr
9473272d797SAndreas Gohr    $tpl = str_replace(
9483272d797SAndreas Gohr        array(
94926ece5a7SAndreas Gohr             '@ID@',
95026ece5a7SAndreas Gohr             '@NS@',
95126ece5a7SAndreas Gohr             '@FILE@',
95226ece5a7SAndreas Gohr             '@!FILE@',
95326ece5a7SAndreas Gohr             '@!FILE!@',
95426ece5a7SAndreas Gohr             '@PAGE@',
95526ece5a7SAndreas Gohr             '@!PAGE@',
95626ece5a7SAndreas Gohr             '@!!PAGE@',
95726ece5a7SAndreas Gohr             '@!PAGE!@',
95826ece5a7SAndreas Gohr             '@USER@',
95926ece5a7SAndreas Gohr             '@NAME@',
96026ece5a7SAndreas Gohr             '@MAIL@',
96126ece5a7SAndreas Gohr             '@DATE@',
96226ece5a7SAndreas Gohr        ),
96326ece5a7SAndreas Gohr        array(
96426ece5a7SAndreas Gohr             $id,
96526ece5a7SAndreas Gohr             getNS($id),
96626ece5a7SAndreas Gohr             $file,
96726ece5a7SAndreas Gohr             utf8_ucfirst($file),
96826ece5a7SAndreas Gohr             utf8_strtoupper($file),
96926ece5a7SAndreas Gohr             $page,
97026ece5a7SAndreas Gohr             utf8_ucfirst($page),
97126ece5a7SAndreas Gohr             utf8_ucwords($page),
97226ece5a7SAndreas Gohr             utf8_strtoupper($page),
97326ece5a7SAndreas Gohr             $_SERVER['REMOTE_USER'],
974b856f7dfSAdrian Lang             $USERINFO['name'],
975b856f7dfSAdrian Lang             $USERINFO['mail'],
97626ece5a7SAndreas Gohr             $conf['dformat'],
9773272d797SAndreas Gohr        ), $tpl
9783272d797SAndreas Gohr    );
97926ece5a7SAndreas Gohr
9807d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
9817d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
982d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
983a15ce62dSEsther Brunner    return $tpl;
9847146cee2SAndreas Gohr}
9857146cee2SAndreas Gohr
9867146cee2SAndreas Gohr/**
98715fae107Sandi * Returns the raw Wiki Text in three slices.
98815fae107Sandi *
98915fae107Sandi * The range parameter needs to have the form "from-to"
99015cfe303Sandi * and gives the range of the section in bytes - no
99115cfe303Sandi * UTF-8 awareness is needed.
992f3f0262cSandi * The returned order is prefix, section and suffix.
99315fae107Sandi *
99415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
995f3f0262cSandi */
996f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
997cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
998f3f0262cSandi
99980fcb268SAdrian Lang    // Parse range
100080fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
100180fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
100280fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
100380fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
100480fcb268SAdrian Lang
100580fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
100680fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
100715cfe303Sandi    $slices[2] = substr($text, $to);
1008f3f0262cSandi    return $slices;
1009f3f0262cSandi}
1010f3f0262cSandi
1011f3f0262cSandi/**
101215fae107Sandi * Joins wiki text slices
101315fae107Sandi *
101480fcb268SAdrian Lang * function to join the text slices.
1015f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1016f3f0262cSandi * lines between sections if needed (used on saving).
101715fae107Sandi *
101815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1019f3f0262cSandi */
1020f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1021f3f0262cSandi    if($pretty) {
102280fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
10233272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
10243272d797SAndreas Gohr        ) {
102580fcb268SAdrian Lang            $pre .= "\n";
102680fcb268SAdrian Lang        }
102780fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
10283272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
10293272d797SAndreas Gohr        ) {
103080fcb268SAdrian Lang            $text .= "\n";
103180fcb268SAdrian Lang        }
1032f3f0262cSandi    }
1033f3f0262cSandi
1034f3f0262cSandi    return $pre.$text.$suf;
1035f3f0262cSandi}
1036f3f0262cSandi
1037f3f0262cSandi/**
1038a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1039a701424fSBen Coburn * Also directs changelog and attic updates.
104015fae107Sandi *
104115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
104271726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1043f3f0262cSandi */
1044b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1045a701424fSBen Coburn    /* Note to developers:
1046a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1047a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1048a701424fSBen Coburn       after any changes. External edits change the wiki page
1049a701424fSBen Coburn       directly without using php or dokuwiki.
1050a701424fSBen Coburn     */
1051f3f0262cSandi    global $conf;
1052f3f0262cSandi    global $lang;
105371726d78SBen Coburn    global $REV;
1054f3f0262cSandi    // ignore if no changes were made
1055f3f0262cSandi    if($text == rawWiki($id, '')) {
1056f3f0262cSandi        return;
1057f3f0262cSandi    }
1058f3f0262cSandi
1059f3f0262cSandi    $file        = wikiFN($id);
1060a701424fSBen Coburn    $old         = @filemtime($file); // from page
1061407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
1062d8186216SBen Coburn    $wasCreated  = !@file_exists($file);
106371726d78SBen Coburn    $wasReverted = ($REV == true);
1064f523c971SGerrit Uitslag    $pagelog     = new PageRevisionLog($id, 1024);
1065e45b34cdSBen Coburn    $newRev      = false;
1066f523c971SGerrit Uitslag    $oldRev      = $pagelog->getRevisions(-1, 1); // from changelog
1067a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1068a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
106946844156SBen Coburn        // add old revision to the attic if missing
107046844156SBen Coburn        saveOldRevision($id);
107146844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1072a701424fSBen Coburn        if($old > $oldRev) {
1073ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
107446844156SBen Coburn            // remove soon to be stale instructions
107546844156SBen Coburn            $cache = new cache_instructions($id, $file);
107646844156SBen Coburn            $cache->removeCache();
107746844156SBen Coburn        }
107846844156SBen Coburn    }
1079f3f0262cSandi
108071726d78SBen Coburn    if($wasRemoved) {
108130725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
108230725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
108330725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1084e45b34cdSBen Coburn        // pre-save deleted revision
1085e45b34cdSBen Coburn        @touch($file);
108646844156SBen Coburn        clearstatcache();
1087e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1088e1f3d9e1SEsther Brunner        // remove empty file
1089f3f0262cSandi        @unlink($file);
1090c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1091c5f92742SMichael Hamann        // purge non-persistant meta data
10923d1f9ec3SMichael Klier        p_purge_metadata($id);
1093f3f0262cSandi        $del = true;
10943ce054b3Sandi        // autoset summary on deletion
10953ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
109653d6ccfeSandi        // remove empty namespaces
1097cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1098cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1099f3f0262cSandi    } else {
1100cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1101cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
110246844156SBen Coburn        // pre-save the revision, to keep the attic in sync
110346844156SBen Coburn        $newRev = saveOldRevision($id);
1104f3f0262cSandi        $del    = false;
1105f3f0262cSandi    }
1106f3f0262cSandi
110771726d78SBen Coburn    // select changelog line type
110871726d78SBen Coburn    $extra = '';
1109ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
111071726d78SBen Coburn    if($wasReverted) {
1111ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
111271726d78SBen Coburn        $extra = $REV;
11133272d797SAndreas Gohr    } else if($wasCreated) {
11143272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
11153272d797SAndreas Gohr    } else if($wasRemoved) {
11163272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
11173272d797SAndreas Gohr    } else if($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) {
11183272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
11193272d797SAndreas Gohr    } //minor edits only for logged in users
112071726d78SBen Coburn
1121e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
112226a0801fSAndreas Gohr    // send notify mails
112390033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
112490033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1125f3f0262cSandi
1126ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
112798407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
11282eccbdaaSGina Haeussge
11292eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1130fe9ec250SChris Smith    if(useHeading('content')) {
113107ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
11322eccbdaaSGina Haeussge        foreach($pages as $page) {
11332eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
11342eccbdaaSGina Haeussge            $cache->removeCache();
11352eccbdaaSGina Haeussge        }
11362eccbdaaSGina Haeussge    }
1137f3f0262cSandi}
1138f3f0262cSandi
1139f3f0262cSandi/**
1140f3f0262cSandi * moves the current version to the attic and returns its
1141f3f0262cSandi * revision date
114215fae107Sandi *
114315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1144f3f0262cSandi */
1145f3f0262cSandifunction saveOldRevision($id) {
1146f3f0262cSandi    global $conf;
1147f3f0262cSandi    $oldf = wikiFN($id);
1148f3f0262cSandi    if(!@file_exists($oldf)) return '';
1149f3f0262cSandi    $date = filemtime($oldf);
1150f3f0262cSandi    $newf = wikiFN($id, $date);
1151cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1152f3f0262cSandi    return $date;
1153f3f0262cSandi}
1154f3f0262cSandi
1155f3f0262cSandi/**
1156fde10de4SAdrian Lang * Sends a notify mail on page change or registration
115726a0801fSAndreas Gohr *
115826a0801fSAndreas Gohr * @param string     $id       The changed page
1159fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
11603272d797SAndreas Gohr * @param int|string $rev Old page revision
116126a0801fSAndreas Gohr * @param string     $summary  What changed
116290033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
116302a498e7Schris * @param array      $replace  Additional string substitutions, @KEY@ to be replaced by value
116415fae107Sandi *
11653272d797SAndreas Gohr * @return bool
116615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1167f3f0262cSandi */
116802a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1169f3f0262cSandi    global $conf;
1170b158d625SSteven Danz
11716df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
117226a0801fSAndreas Gohr    if($who == 'admin') {
11733272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
11742ed38036SAndreas Gohr        $tpl = 'mailtext';
117526a0801fSAndreas Gohr        $to  = $conf['notify'];
117626a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
117784c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
11783272d797SAndreas Gohr        if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return false; //skip minors
11798881fcc9SAdrian Lang        $data = array('id' => $id, 'addresslist' => '', 'self' => false);
11803272d797SAndreas Gohr        trigger_event(
11813272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1182835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
11833272d797SAndreas Gohr        );
11842ed38036SAndreas Gohr        $to = $data['addresslist'];
11852ed38036SAndreas Gohr        if(empty($to)) return false;
11862ed38036SAndreas Gohr        $tpl = 'subscr_single';
118726a0801fSAndreas Gohr    } else {
11883272d797SAndreas Gohr        return false; //just to be safe
118926a0801fSAndreas Gohr    }
119026a0801fSAndreas Gohr
11916df843eeSAndreas Gohr    // prepare content
11922ed38036SAndreas Gohr    $subscription = new Subscription();
11932ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1194f3f0262cSandi}
11952ed38036SAndreas Gohr
119615fae107Sandi/**
119771f7bde7SAndreas Gohr * extracts the query from a search engine referrer
119815fae107Sandi *
119915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
120071f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1201f3f0262cSandi */
1202f3f0262cSandifunction getGoogleQuery() {
1203c66972f2SAdrian Lang    if(!isset($_SERVER['HTTP_REFERER'])) {
1204c66972f2SAdrian Lang        return '';
1205c66972f2SAdrian Lang    }
1206f3f0262cSandi    $url = parse_url($_SERVER['HTTP_REFERER']);
1207f3f0262cSandi
1208079b3ac1SAndreas Gohr    // only handle common SEs
1209079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1210e4d8a516SKazutaka Miyasaka
1211079b3ac1SAndreas Gohr    $query = array();
1212e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1213e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1214e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1215f3f0262cSandi    parse_str($url['query'], $query);
1216e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1217e4d8a516SKazutaka Miyasaka
1218c66972f2SAdrian Lang    $q = '';
1219079b3ac1SAndreas Gohr    if(isset($query['q'])){
1220079b3ac1SAndreas Gohr        $q = $query['q'];
1221079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1222079b3ac1SAndreas Gohr        $q = $query['p'];
1223079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1224079b3ac1SAndreas Gohr        $q = $query['query'];
1225079b3ac1SAndreas Gohr    }
1226079b3ac1SAndreas Gohr    $q = trim($q);
1227f3f0262cSandi
1228079b3ac1SAndreas Gohr    if(!$q) return '';
12296531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1230f93b3b50SAndreas Gohr    return $q;
1231f3f0262cSandi}
1232f3f0262cSandi
1233f3f0262cSandi/**
1234f3f0262cSandi * Return the human readable size of a file
1235f3f0262cSandi *
1236f3f0262cSandi * @param       int    $size   A file size
1237f3f0262cSandi * @param       int    $dec    A number of decimal places
1238f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1239f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1240f3f0262cSandi * @version     1.0.0
1241f3f0262cSandi */
1242f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1243f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1244f3f0262cSandi    $count = count($sizes);
1245f3f0262cSandi    $i     = 0;
1246f3f0262cSandi
1247f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1248f3f0262cSandi        $size /= 1024;
1249f3f0262cSandi        $i++;
1250f3f0262cSandi    }
1251f3f0262cSandi
1252f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1253f3f0262cSandi}
1254f3f0262cSandi
125515fae107Sandi/**
1256c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1257c57e365eSAndreas Gohr *
1258c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1259c57e365eSAndreas Gohr */
1260c57e365eSAndreas Gohrfunction datetime_h($dt) {
1261c57e365eSAndreas Gohr    global $lang;
1262c57e365eSAndreas Gohr
1263c57e365eSAndreas Gohr    $ago = time() - $dt;
1264c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1265c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1266c57e365eSAndreas Gohr    }
1267c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1268c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1269c57e365eSAndreas Gohr    }
1270c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1271c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1272c57e365eSAndreas Gohr    }
1273c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1274c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1275c57e365eSAndreas Gohr    }
1276c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1277c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1278c57e365eSAndreas Gohr    }
1279c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1280c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1281c57e365eSAndreas Gohr    }
1282c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1283c57e365eSAndreas Gohr}
1284c57e365eSAndreas Gohr
1285c57e365eSAndreas Gohr/**
1286f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1287f2263577SAndreas Gohr *
1288f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1289f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1290f2263577SAndreas Gohr *
1291f2263577SAndreas Gohr * @see datetime_h
1292f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1293f2263577SAndreas Gohr */
1294f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1295f2263577SAndreas Gohr    global $conf;
1296f2263577SAndreas Gohr
1297f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1298f2263577SAndreas Gohr    $dt = (int) $dt;
1299f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1300f2263577SAndreas Gohr
1301f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1302f2263577SAndreas Gohr    return strftime($format, $dt);
1303f2263577SAndreas Gohr}
1304f2263577SAndreas Gohr
1305f2263577SAndreas Gohr/**
1306c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1307c4f79b71SMichael Hamann *
1308c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1309c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
131063703ba5SAndreas Gohr * @param int $int_date: current date in UNIX timestamp
13113272d797SAndreas Gohr * @return string
1312c4f79b71SMichael Hamann */
1313c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1314c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1315c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1316c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1317c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1318c4f79b71SMichael Hamann    return $date_mod;
1319c4f79b71SMichael Hamann}
1320c4f79b71SMichael Hamann
1321c4f79b71SMichael Hamann/**
132200a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
132300a7b5adSEsther Brunner *
132400a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
132500a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
132600a7b5adSEsther Brunner */
132700a7b5adSEsther Brunnerfunction obfuscate($email) {
132800a7b5adSEsther Brunner    global $conf;
132900a7b5adSEsther Brunner
133000a7b5adSEsther Brunner    switch($conf['mailguard']) {
133100a7b5adSEsther Brunner        case 'visible' :
133200a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
133300a7b5adSEsther Brunner            return strtr($email, $obfuscate);
133400a7b5adSEsther Brunner
133500a7b5adSEsther Brunner        case 'hex' :
133600a7b5adSEsther Brunner            $encode = '';
133749eb6e38SAndreas Gohr            $len    = strlen($email);
133849eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
133949eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
134049eb6e38SAndreas Gohr            }
134100a7b5adSEsther Brunner            return $encode;
134200a7b5adSEsther Brunner
134300a7b5adSEsther Brunner        case 'none' :
134400a7b5adSEsther Brunner        default :
134500a7b5adSEsther Brunner            return $email;
134600a7b5adSEsther Brunner    }
134700a7b5adSEsther Brunner}
134800a7b5adSEsther Brunner
134900a7b5adSEsther Brunner/**
135089541d4bSAndreas Gohr * Removes quoting backslashes
135189541d4bSAndreas Gohr *
135289541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
135389541d4bSAndreas Gohr */
135489541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
135589541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
135689541d4bSAndreas Gohr}
135789541d4bSAndreas Gohr
135873038c47SAndreas Gohr/**
135973038c47SAndreas Gohr * Convert php.ini shorthands to byte
136073038c47SAndreas Gohr *
136173038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
136273038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
136373038c47SAndreas Gohr */
136473038c47SAndreas Gohrfunction php_to_byte($v) {
136573038c47SAndreas Gohr    $l   = substr($v, -1);
136673038c47SAndreas Gohr    $ret = substr($v, 0, -1);
136773038c47SAndreas Gohr    switch(strtoupper($l)) {
136873038c47SAndreas Gohr        case 'P':
136973038c47SAndreas Gohr            $ret *= 1024;
137073038c47SAndreas Gohr        case 'T':
137173038c47SAndreas Gohr            $ret *= 1024;
137273038c47SAndreas Gohr        case 'G':
137373038c47SAndreas Gohr            $ret *= 1024;
137473038c47SAndreas Gohr        case 'M':
137573038c47SAndreas Gohr            $ret *= 1024;
137673038c47SAndreas Gohr        case 'K':
137773038c47SAndreas Gohr            $ret *= 1024;
137873038c47SAndreas Gohr            break;
137949cbd23eSOtto Vainio        default;
138049cbd23eSOtto Vainio            $ret *= 10;
138149cbd23eSOtto Vainio            break;
138273038c47SAndreas Gohr    }
138373038c47SAndreas Gohr    return $ret;
138473038c47SAndreas Gohr}
138573038c47SAndreas Gohr
1386546d3a99SAndreas Gohr/**
1387546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1388546d3a99SAndreas Gohr */
1389546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1390546d3a99SAndreas Gohr    return preg_quote($string, '/');
1391546d3a99SAndreas Gohr}
139273038c47SAndreas Gohr
1393bd2f6c2fSAndreas Gohr/**
1394bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1395bd2f6c2fSAndreas Gohr *
1396c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1397bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1398bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1399bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1400bd2f6c2fSAndreas Gohr *
1401bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1402bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1403bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1404bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1405bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
14063272d797SAndreas Gohr * @return string
1407bd2f6c2fSAndreas Gohr */
1408a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1409bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1410bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1411bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1412bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1413bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1414bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1415bd2f6c2fSAndreas Gohr}
1416bd2f6c2fSAndreas Gohr
1417dc58b6f4SAndy Webber/**
1418dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1419dc58b6f4SAndy Webber * in page footer and recent changes pages
1420dc58b6f4SAndy Webber *
1421dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1422dc58b6f4SAndy Webber */
1423dc58b6f4SAndy Webberfunction editorinfo($username) {
1424dc58b6f4SAndy Webber    global $conf;
1425dc58b6f4SAndy Webber    global $auth;
1426dc58b6f4SAndy Webber
1427dc58b6f4SAndy Webber    switch($conf['showuseras']) {
1428dc58b6f4SAndy Webber        case 'username':
1429dc58b6f4SAndy Webber        case 'email':
1430dc58b6f4SAndy Webber        case 'email_link':
1431173d78c4SAndreas Gohr            if($auth) $info = $auth->getUserData($username);
1432dc58b6f4SAndy Webber            break;
1433dc58b6f4SAndy Webber        default:
1434dc58b6f4SAndy Webber            return hsc($username);
1435dc58b6f4SAndy Webber    }
1436dc58b6f4SAndy Webber
1437dc58b6f4SAndy Webber    if(isset($info) && $info) {
1438dc58b6f4SAndy Webber        switch($conf['showuseras']) {
1439dc58b6f4SAndy Webber            case 'username':
1440dc58b6f4SAndy Webber                return hsc($info['name']);
1441dc58b6f4SAndy Webber            case 'email':
1442dc58b6f4SAndy Webber                return obfuscate($info['mail']);
1443dc58b6f4SAndy Webber            case 'email_link':
1444dc58b6f4SAndy Webber                $mail = obfuscate($info['mail']);
1445dc58b6f4SAndy Webber                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1446dc58b6f4SAndy Webber            default:
1447dc58b6f4SAndy Webber                return hsc($username);
1448dc58b6f4SAndy Webber        }
1449dc58b6f4SAndy Webber    } else {
1450dc58b6f4SAndy Webber        return hsc($username);
1451dc58b6f4SAndy Webber    }
1452066fee30SAndreas Gohr}
1453066fee30SAndreas Gohr
1454066fee30SAndreas Gohr/**
1455066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1456066fee30SAndreas Gohr * When no image exists, returns an empty string
1457066fee30SAndreas Gohr *
1458066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1459066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
14603272d797SAndreas Gohr * @return string
1461066fee30SAndreas Gohr */
1462066fee30SAndreas Gohrfunction license_img($type) {
1463066fee30SAndreas Gohr    global $license;
1464066fee30SAndreas Gohr    global $conf;
1465066fee30SAndreas Gohr    if(!$conf['license']) return '';
1466066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1467066fee30SAndreas Gohr    $lic   = $license[$conf['license']];
1468066fee30SAndreas Gohr    $try   = array();
1469066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1470066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1471066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1472066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1473066fee30SAndreas Gohr    }
1474066fee30SAndreas Gohr    foreach($try as $src) {
1475066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1476066fee30SAndreas Gohr    }
1477066fee30SAndreas Gohr    return '';
1478dc58b6f4SAndy Webber}
1479dc58b6f4SAndy Webber
148013c08e2fSMichael Klier/**
148113c08e2fSMichael Klier * Checks if the given amount of memory is available
148213c08e2fSMichael Klier *
148313c08e2fSMichael Klier * If the memory_get_usage() function is not available the
148413c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
148513c08e2fSMichael Klier *
148613c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
148713c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
14883272d797SAndreas Gohr *
14893272d797SAndreas Gohr * @param  int $mem  Size of memory you want to allocate in bytes
14903272d797SAndreas Gohr * @param int  $bytes
14913272d797SAndreas Gohr * @internal param int $used already allocated memory (see above)
14923272d797SAndreas Gohr * @return bool
149313c08e2fSMichael Klier */
149413c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
149513c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
149613c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
149713c08e2fSMichael Klier
149813c08e2fSMichael Klier    // parse limit to bytes
149913c08e2fSMichael Klier    $limit = php_to_byte($limit);
150013c08e2fSMichael Klier
150113c08e2fSMichael Klier    // get used memory if possible
150213c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
150313c08e2fSMichael Klier        $used = memory_get_usage();
150449eb6e38SAndreas Gohr    } else {
150549eb6e38SAndreas Gohr        $used = $bytes;
150613c08e2fSMichael Klier    }
150713c08e2fSMichael Klier
150813c08e2fSMichael Klier    if($used + $mem > $limit) {
150913c08e2fSMichael Klier        return false;
151013c08e2fSMichael Klier    }
151113c08e2fSMichael Klier
151213c08e2fSMichael Klier    return true;
151313c08e2fSMichael Klier}
151413c08e2fSMichael Klier
1515af2408d5SAndreas Gohr/**
1516af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1517af2408d5SAndreas Gohr *
1518af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1519af2408d5SAndreas Gohr *
1520af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1521af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1522af2408d5SAndreas Gohr */
1523af2408d5SAndreas Gohrfunction send_redirect($url) {
15240181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
15250181f021SAndreas Gohr    global $MSG;
15260181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
15270181f021SAndreas Gohr        //reopen session, store data and close session again
15280181f021SAndreas Gohr        @session_start();
15290181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
15300181f021SAndreas Gohr    }
15310181f021SAndreas Gohr
1532d4869846SAndreas Gohr    // always close the session
1533d4869846SAndreas Gohr    session_write_close();
1534d4869846SAndreas Gohr
1535c10dcb7dSAndreas Gohr    // work around IE bug
1536c10dcb7dSAndreas Gohr    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
1537c10dcb7dSAndreas Gohr    list($url, $hash) = explode('#', $url);
1538c10dcb7dSAndreas Gohr    if($hash) {
1539c10dcb7dSAndreas Gohr        if(strpos($url, '?')) {
1540c10dcb7dSAndreas Gohr            $url = $url.'&#'.$hash;
1541c10dcb7dSAndreas Gohr        } else {
1542c10dcb7dSAndreas Gohr            $url = $url.'?&#'.$hash;
1543c10dcb7dSAndreas Gohr        }
1544c10dcb7dSAndreas Gohr    }
1545c10dcb7dSAndreas Gohr
1546af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1547af2408d5SAndreas Gohr    if(isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1548af2408d5SAndreas Gohr        (strpos($_SERVER['GATEWAY_INTERFACE'], 'CGI') !== false) &&
1549af2408d5SAndreas Gohr        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
15503272d797SAndreas Gohr        $matches[1] < 6
15513272d797SAndreas Gohr    ) {
1552af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1553af2408d5SAndreas Gohr    } else {
1554af2408d5SAndreas Gohr        header('Location: '.$url);
1555af2408d5SAndreas Gohr    }
1556af2408d5SAndreas Gohr    exit;
1557af2408d5SAndreas Gohr}
1558af2408d5SAndreas Gohr
15595b75cd1fSAdrian Lang/**
15605b75cd1fSAdrian Lang * Validate a value using a set of valid values
15615b75cd1fSAdrian Lang *
15625b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
15635b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
15645b75cd1fSAdrian Lang * default is specified, throws an exception.
15655b75cd1fSAdrian Lang *
15665b75cd1fSAdrian Lang * @param string $param        The name of the parameter
15675b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
15685b75cd1fSAdrian Lang *                             be marked by the key “default”.
15695b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
15705b75cd1fSAdrian Lang *                             or $_GET)
15715b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
15725b75cd1fSAdrian Lang *
15733272d797SAndreas Gohr * @throws Exception
15743272d797SAndreas Gohr * @return mixed
15755b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
15765b75cd1fSAdrian Lang */
15775b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
15785b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
15795b75cd1fSAdrian Lang        return $array[$param];
15805b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
15815b75cd1fSAdrian Lang        return $valid_values['default'];
15825b75cd1fSAdrian Lang    } else {
15835b75cd1fSAdrian Lang        throw new Exception($exc);
15845b75cd1fSAdrian Lang    }
15855b75cd1fSAdrian Lang}
15865b75cd1fSAdrian Lang
158763703ba5SAndreas Gohr/**
158863703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1589646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
159063703ba5SAndreas Gohr */
1591554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1592646a531aSChristopher Smith    $enc_pref = urlencode($pref);
1593646a531aSChristopher Smith    if(strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1594554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
159563703ba5SAndreas Gohr        $cnt   = count($parts);
159663703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1597646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1598646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1599554a8c9fSAdrian Lang            }
1600554a8c9fSAdrian Lang        }
1601554a8c9fSAdrian Lang    }
1602554a8c9fSAdrian Lang    return $default;
1603554a8c9fSAdrian Lang}
1604554a8c9fSAdrian Lang
16053c94d07bSAnika Henke/**
16063c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
160736ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
16083c94d07bSAnika Henke */
16093c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
16103c94d07bSAnika Henke    global $conf;
16113c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
16123c94d07bSAnika Henke    $cookieVal = '';
16133c94d07bSAnika Henke
16143c94d07bSAnika Henke    if($orig && ($orig != $val)) {
16153c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
16163c94d07bSAnika Henke        $cnt   = count($parts);
161736ec377eSChristopher Smith        // urlencode $pref for the comparison
161836ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
16193c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
162036ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
162136ec377eSChristopher Smith                $parts[$i + 1] = rawurlencode($val);
162250f261f7SMichael Hamann                break;
16233c94d07bSAnika Henke            }
16243c94d07bSAnika Henke        }
16253c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
16263c94d07bSAnika Henke    } else if (!$orig) {
162736ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
16283c94d07bSAnika Henke    }
16293c94d07bSAnika Henke
16303c94d07bSAnika Henke    if (!empty($cookieVal)) {
163175e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
163275e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
16333c94d07bSAnika Henke    }
16343c94d07bSAnika Henke}
16353c94d07bSAnika Henke
1636e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1637