xref: /dokuwiki/inc/common.php (revision 3272d797334d9d13a4e4ca43351b1607bb520445)
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) {
66df97eaacSAndreas Gohr    if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
67df97eaacSAndreas Gohr
68634d7150SAndreas Gohr    if(is_null($token)) $token = $_REQUEST['sectok'];
69634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
70634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
71634d7150SAndreas Gohr        return false;
72634d7150SAndreas Gohr    }
73634d7150SAndreas Gohr    return true;
74634d7150SAndreas Gohr}
75634d7150SAndreas Gohr
76634d7150SAndreas Gohr/**
77634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
78634d7150SAndreas Gohr *
79634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
80634d7150SAndreas Gohr */
81634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
822404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
83*3272d797SAndreas Gohr    if($print) echo $ret;
84634d7150SAndreas Gohr    return $ret;
85634d7150SAndreas Gohr}
86634d7150SAndreas Gohr
87634d7150SAndreas Gohr/**
8815fae107Sandi * Return info about the current document as associative
89f3f0262cSandi * array.
9015fae107Sandi *
9115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
92f3f0262cSandi */
93f3f0262cSandifunction pageinfo() {
94f3f0262cSandi    global $ID;
95f3f0262cSandi    global $REV;
967b3a6803SAndreas Gohr    global $RANGE;
97f3f0262cSandi    global $USERINFO;
987b3a6803SAndreas Gohr    global $lang;
99f3f0262cSandi
1006afe8dcaSchris    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1016afe8dcaSchris    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1026afe8dcaSchris    $info['id']  = $ID;
1036afe8dcaSchris    $info['rev'] = $REV;
1046afe8dcaSchris
105c66972f2SAdrian Lang    // set info about manager/admin status.
106c66972f2SAdrian Lang    $info['isadmin']   = false;
107c66972f2SAdrian Lang    $info['ismanager'] = false;
108c66972f2SAdrian Lang    if(isset($_SERVER['REMOTE_USER'])) {
109f3f0262cSandi        $info['userinfo']   = $USERINFO;
110f3f0262cSandi        $info['perm']       = auth_quickaclcheck($ID);
1115b75cd1fSAdrian Lang        $info['subscribed'] = get_info_subscribed();
112ee4c4a1bSAndreas Gohr        $info['client']     = $_SERVER['REMOTE_USER'];
11317ee7f66SAndreas Gohr
114f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
115f8cc712eSAndreas Gohr            $info['isadmin']   = true;
116f8cc712eSAndreas Gohr            $info['ismanager'] = true;
117f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
118f8cc712eSAndreas Gohr            $info['ismanager'] = true;
119f8cc712eSAndreas Gohr        }
120f8cc712eSAndreas Gohr
12117ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
12217ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
12317ee7f66SAndreas Gohr            $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
12417ee7f66SAndreas Gohr        }
125ee4c4a1bSAndreas Gohr
126f3f0262cSandi    } else {
127f3f0262cSandi        $info['perm']       = auth_aclcheck($ID, '', null);
1281380fc45SAndreas Gohr        $info['subscribed'] = false;
129ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
130f3f0262cSandi    }
131f3f0262cSandi
132f3f0262cSandi    $info['namespace'] = getNS($ID);
133f3f0262cSandi    $info['locked']    = checklock($ID);
13400976812SAndreas Gohr    $info['filepath']  = fullpath(wikiFN($ID));
1352ca9d91cSBen Coburn    $info['exists']    = @file_exists($info['filepath']);
1362ca9d91cSBen Coburn    if($REV) {
1372ca9d91cSBen Coburn        //check if current revision was meant
1382ca9d91cSBen Coburn        if($info['exists'] && (@filemtime($info['filepath']) == $REV)) {
1392ca9d91cSBen Coburn            $REV = '';
1407b3a6803SAndreas Gohr        } elseif($RANGE) {
1417b3a6803SAndreas Gohr            //section editing does not work with old revisions!
1427b3a6803SAndreas Gohr            $REV   = '';
1437b3a6803SAndreas Gohr            $RANGE = '';
1447b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
1452ca9d91cSBen Coburn        } else {
1462ca9d91cSBen Coburn            //really use old revision
14700976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID, $REV));
148f3f0262cSandi            $info['exists']   = @file_exists($info['filepath']);
149f3f0262cSandi        }
150f3f0262cSandi    }
151c112d578Sandi    $info['rev'] = $REV;
152f3f0262cSandi    if($info['exists']) {
153f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
154f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
155f3f0262cSandi    } else {
156f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
157f3f0262cSandi    }
15850e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
159f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
160f3f0262cSandi
16171726d78SBen Coburn    //load page meta data
16271726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
16371726d78SBen Coburn
164652610a2Sandi    //who's the editor
165652610a2Sandi    if($REV) {
16671726d78SBen Coburn        $revinfo = getRevisionInfo($ID, $REV, 1024);
167652610a2Sandi    } else {
168aa27cf05SAndreas Gohr        if(is_array($info['meta']['last_change'])) {
169aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
170aa27cf05SAndreas Gohr        } else {
171cd00a034SBen Coburn            $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
172cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
173cd00a034SBen Coburn            if($revinfo !== false) {
174cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
175cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
176cd00a034SBen Coburn            }
177cd00a034SBen Coburn        }
178cd00a034SBen Coburn    }
179cd00a034SBen Coburn    //and check for an external edit
180cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
181cd00a034SBen Coburn        // cached changelog line no longer valid
182cd00a034SBen Coburn        $revinfo                     = false;
183cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
184cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
185652610a2Sandi    }
186bb4866bdSchris
187652610a2Sandi    $info['ip']   = $revinfo['ip'];
188652610a2Sandi    $info['user'] = $revinfo['user'];
189652610a2Sandi    $info['sum']  = $revinfo['sum'];
19071726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
191ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
19259f257aeSchris
19388f522e9Sandi    if($revinfo['user']) {
19488f522e9Sandi        $info['editor'] = $revinfo['user'];
19588f522e9Sandi    } else {
19688f522e9Sandi        $info['editor'] = $revinfo['ip'];
19788f522e9Sandi    }
198652610a2Sandi
199ee4c4a1bSAndreas Gohr    // draft
200ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
201ee4c4a1bSAndreas Gohr    if(@file_exists($draft)) {
202ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
203ee4c4a1bSAndreas Gohr            // remove stale draft
204ee4c4a1bSAndreas Gohr            @unlink($draft);
205ee4c4a1bSAndreas Gohr        } else {
206ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
207ee4c4a1bSAndreas Gohr        }
208ee4c4a1bSAndreas Gohr    }
209ee4c4a1bSAndreas Gohr
2101c548ebeSAndreas Gohr    // mobile detection
2111c548ebeSAndreas Gohr    $info['ismobile'] = clientismobile();
2121c548ebeSAndreas Gohr
213f3f0262cSandi    return $info;
214f3f0262cSandi}
215f3f0262cSandi
216f3f0262cSandi/**
2172684e50aSAndreas Gohr * Build an string of URL parameters
2182684e50aSAndreas Gohr *
2192684e50aSAndreas Gohr * @author Andreas Gohr
2202684e50aSAndreas Gohr */
221b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
2222684e50aSAndreas Gohr    $url = '';
2232684e50aSAndreas Gohr    $amp = false;
2242684e50aSAndreas Gohr    foreach($params as $key => $val) {
225b174aeaeSchris        if($amp) $url .= $sep;
2262684e50aSAndreas Gohr
22785e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
2283a50618cSgweissbach        $url .= rawurlencode((string) $val);
2292684e50aSAndreas Gohr        $amp = true;
2302684e50aSAndreas Gohr    }
2312684e50aSAndreas Gohr    return $url;
2322684e50aSAndreas Gohr}
2332684e50aSAndreas Gohr
2342684e50aSAndreas Gohr/**
2352684e50aSAndreas Gohr * Build an string of html tag attributes
2362684e50aSAndreas Gohr *
2377bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2387bff22c0SAndreas Gohr *
2392684e50aSAndreas Gohr * @author Andreas Gohr
2402684e50aSAndreas Gohr */
2414b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
2422684e50aSAndreas Gohr    $url   = '';
2439063ec14SAdrian Lang    $white = false;
2442684e50aSAndreas Gohr    foreach($params as $key => $val) {
2457bff22c0SAndreas Gohr        if($key{0} == '_') continue;
246b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
2479063ec14SAdrian Lang        if($white) $url .= ' ';
2487bff22c0SAndreas Gohr
2492684e50aSAndreas Gohr        $url .= $key.'="';
2502684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
2512684e50aSAndreas Gohr        $url .= '"';
2529063ec14SAdrian Lang        $white = true;
2532684e50aSAndreas Gohr    }
2542684e50aSAndreas Gohr    return $url;
2552684e50aSAndreas Gohr}
2562684e50aSAndreas Gohr
2572684e50aSAndreas Gohr/**
25815fae107Sandi * This builds the breadcrumb trail and returns it as array
25915fae107Sandi *
26015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
261f3f0262cSandi */
262f3f0262cSandifunction breadcrumbs() {
2638746e727Sandi    // we prepare the breadcrumbs early for quick session closing
2648746e727Sandi    static $crumbs = null;
2658746e727Sandi    if($crumbs != null) return $crumbs;
2668746e727Sandi
267f3f0262cSandi    global $ID;
268f3f0262cSandi    global $ACT;
269f3f0262cSandi    global $conf;
270f3f0262cSandi
271f3f0262cSandi    //first visit?
272c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
273f3f0262cSandi    //we only save on show and existing wiki documents
274a77f5846Sjan    $file = wikiFN($ID);
275a77f5846Sjan    if($ACT != 'show' || !@file_exists($file)) {
276e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
277f3f0262cSandi        return $crumbs;
278f3f0262cSandi    }
279a77f5846Sjan
280a77f5846Sjan    // page names
2811a84a0f3SAnika Henke    $name = noNSorNS($ID);
282fe9ec250SChris Smith    if(useHeading('navigation')) {
283a77f5846Sjan        // get page title
28467c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
285a77f5846Sjan        if($title) {
286a77f5846Sjan            $name = $title;
287a77f5846Sjan        }
288a77f5846Sjan    }
289a77f5846Sjan
290f3f0262cSandi    //remove ID from array
291a77f5846Sjan    if(isset($crumbs[$ID])) {
292a77f5846Sjan        unset($crumbs[$ID]);
293f3f0262cSandi    }
294f3f0262cSandi
295f3f0262cSandi    //add to array
296a77f5846Sjan    $crumbs[$ID] = $name;
297f3f0262cSandi    //reduce size
298f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
299f3f0262cSandi        array_shift($crumbs);
300f3f0262cSandi    }
301f3f0262cSandi    //save to session
302e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
303f3f0262cSandi    return $crumbs;
304f3f0262cSandi}
305f3f0262cSandi
306f3f0262cSandi/**
30715fae107Sandi * Filter for page IDs
30815fae107Sandi *
309f3f0262cSandi * This is run on a ID before it is outputted somewhere
310f3f0262cSandi * currently used to replace the colon with something else
311f3f0262cSandi * on Windows systems and to have proper URL encoding
31215fae107Sandi *
31349c713a3Sandi * Urlencoding is ommitted when the second parameter is false
31449c713a3Sandi *
31515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
316f3f0262cSandi */
31749c713a3Sandifunction idfilter($id, $ue = true) {
318f3f0262cSandi    global $conf;
319f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
320f3f0262cSandi        $id = strtr($id, ':', '/');
321f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
322*3272d797SAndreas Gohr        $conf['userewrite']
323*3272d797SAndreas Gohr    ) {
324f3f0262cSandi        $id = strtr($id, ':', ';');
325f3f0262cSandi    }
32649c713a3Sandi    if($ue) {
327b6c6979fSAndreas Gohr        $id = rawurlencode($id);
328f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
329f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
33049c713a3Sandi    }
331f3f0262cSandi    return $id;
332f3f0262cSandi}
333f3f0262cSandi
334f3f0262cSandi/**
335ed7b5f09Sandi * This builds a link to a wikipage
33615fae107Sandi *
3376c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3386c7843b5Sandi * given in $more
3396c7843b5Sandi *
34015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
341f3f0262cSandi */
34216f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
343f3f0262cSandi    global $conf;
34416f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
34516f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
3466de3759aSAndreas Gohr    } else {
34716f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
3486de3759aSAndreas Gohr    }
34916f15a81SDominik Eckelmann    if($id === '') {
35016f15a81SDominik Eckelmann        $id = $conf['start'];
35116f15a81SDominik Eckelmann    }
352f3f0262cSandi    $id = idfilter($id);
35316f15a81SDominik Eckelmann    if($absolute) {
354ed7b5f09Sandi        $xlink = DOKU_URL;
355ed7b5f09Sandi    } else {
356ed7b5f09Sandi        $xlink = DOKU_BASE;
357ed7b5f09Sandi    }
358f3f0262cSandi
3596c7843b5Sandi    if($conf['userewrite'] == 2) {
3606c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
36116f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
3626c7843b5Sandi    } elseif($conf['userewrite']) {
363f3f0262cSandi        $xlink .= $id;
36416f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
365bce3726dSAndreas Gohr    } elseif($id) {
3666c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
36716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
368bce3726dSAndreas Gohr    } else {
369bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
37016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
371f3f0262cSandi    }
372f3f0262cSandi
373f3f0262cSandi    return $xlink;
374f3f0262cSandi}
375f3f0262cSandi
376f3f0262cSandi/**
377f5c2808fSBen Coburn * This builds a link to an alternate page format
378f5c2808fSBen Coburn *
379f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
380f5c2808fSBen Coburn *
381f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
382f5c2808fSBen Coburn */
383f5c2808fSBen Coburnfunction exportlink($id = '', $format = 'raw', $more = '', $abs = false, $sep = '&amp;') {
384f5c2808fSBen Coburn    global $conf;
385f5c2808fSBen Coburn    if(is_array($more)) {
386f5c2808fSBen Coburn        $more = buildURLparams($more, $sep);
387f5c2808fSBen Coburn    } else {
388f5c2808fSBen Coburn        $more = str_replace(',', $sep, $more);
389f5c2808fSBen Coburn    }
390f5c2808fSBen Coburn
391f5c2808fSBen Coburn    $format = rawurlencode($format);
392f5c2808fSBen Coburn    $id     = idfilter($id);
393f5c2808fSBen Coburn    if($abs) {
394f5c2808fSBen Coburn        $xlink = DOKU_URL;
395f5c2808fSBen Coburn    } else {
396f5c2808fSBen Coburn        $xlink = DOKU_BASE;
397f5c2808fSBen Coburn    }
398f5c2808fSBen Coburn
399f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
400f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
401f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
402f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
403f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
404f5c2808fSBen Coburn        if($more) $xlink .= '?'.$more;
405f5c2808fSBen Coburn    } else {
406f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
407f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
408f5c2808fSBen Coburn    }
409f5c2808fSBen Coburn
410f5c2808fSBen Coburn    return $xlink;
411f5c2808fSBen Coburn}
412f5c2808fSBen Coburn
413f5c2808fSBen Coburn/**
4146de3759aSAndreas Gohr * Build a link to a media file
4156de3759aSAndreas Gohr *
4166de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4178c08db0aSAndreas Gohr *
4188c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4198c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4208c08db0aSAndreas Gohr *
421*3272d797SAndreas Gohr * @param string  $id     the media file id or URL
422*3272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
423*3272d797SAndreas Gohr * @param bool    $direct link to detail page if false
424*3272d797SAndreas Gohr * @param string  $sep    URL parameter separator
425*3272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
426*3272d797SAndreas Gohr * @return string
4276de3759aSAndreas Gohr */
42855b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
4296de3759aSAndreas Gohr    global $conf;
4306de3759aSAndreas Gohr    if(is_array($more)) {
4318c08db0aSAndreas Gohr        // strip defaults for shorter URLs
4328c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
4338c08db0aSAndreas Gohr        if(!$more['w']) unset($more['w']);
4348c08db0aSAndreas Gohr        if(!$more['h']) unset($more['h']);
4358c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
436b174aeaeSchris        $more = buildURLparams($more, $sep);
4376de3759aSAndreas Gohr    } else {
4388c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
4398c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
440b174aeaeSchris        $more = str_replace(',', $sep, $more);
4416de3759aSAndreas Gohr    }
4426de3759aSAndreas Gohr
44355b2b31bSAndreas Gohr    if($abs) {
44455b2b31bSAndreas Gohr        $xlink = DOKU_URL;
44555b2b31bSAndreas Gohr    } else {
4466de3759aSAndreas Gohr        $xlink = DOKU_BASE;
44755b2b31bSAndreas Gohr    }
4486de3759aSAndreas Gohr
4496de3759aSAndreas Gohr    // external URLs are always direct without rewriting
4506de3759aSAndreas Gohr    if(preg_match('#^(https?|ftp)://#i', $id)) {
4516de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
45269d17d94SAndreas Gohr        // add hash:
45369d17d94SAndreas Gohr        $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id), 0, 6);
4546de3759aSAndreas Gohr        if($more) {
45569d17d94SAndreas Gohr            $xlink .= $sep.$more;
456b174aeaeSchris            $xlink .= $sep.'media='.rawurlencode($id);
4576de3759aSAndreas Gohr        } else {
45869d17d94SAndreas Gohr            $xlink .= $sep.'media='.rawurlencode($id);
4596de3759aSAndreas Gohr        }
4606de3759aSAndreas Gohr        return $xlink;
4616de3759aSAndreas Gohr    }
4626de3759aSAndreas Gohr
4636de3759aSAndreas Gohr    $id = idfilter($id);
4646de3759aSAndreas Gohr
4656de3759aSAndreas Gohr    // decide on scriptname
4666de3759aSAndreas Gohr    if($direct) {
4676de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
4686de3759aSAndreas Gohr            $script = '_media';
4696de3759aSAndreas Gohr        } else {
4706de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
4716de3759aSAndreas Gohr        }
4726de3759aSAndreas Gohr    } else {
4736de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
4746de3759aSAndreas Gohr            $script = '_detail';
4756de3759aSAndreas Gohr        } else {
4766de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
4776de3759aSAndreas Gohr        }
4786de3759aSAndreas Gohr    }
4796de3759aSAndreas Gohr
4806de3759aSAndreas Gohr    // build URL based on rewrite mode
4816de3759aSAndreas Gohr    if($conf['userewrite']) {
4826de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
4836de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
4846de3759aSAndreas Gohr    } else {
4856de3759aSAndreas Gohr        if($more) {
486a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
487b174aeaeSchris            $xlink .= $sep.'media='.$id;
4886de3759aSAndreas Gohr        } else {
489a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
4906de3759aSAndreas Gohr        }
4916de3759aSAndreas Gohr    }
4926de3759aSAndreas Gohr
4936de3759aSAndreas Gohr    return $xlink;
4946de3759aSAndreas Gohr}
4956de3759aSAndreas Gohr
4966de3759aSAndreas Gohr/**
497f3f0262cSandi * Just builds a link to a script
49815fae107Sandi *
499ed7b5f09Sandi * @todo   maybe obsolete
50015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
501f3f0262cSandi */
502f3f0262cSandifunction script($script = 'doku.php') {
503ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
504f3f0262cSandi}
505f3f0262cSandi
506f3f0262cSandi/**
50715fae107Sandi * Spamcheck against wordlist
50815fae107Sandi *
509f3f0262cSandi * Checks the wikitext against a list of blocked expressions
510f3f0262cSandi * returns true if the text contains any bad words
51115fae107Sandi *
512e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
513e403cc58SMichael Klier *
514e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
515e403cc58SMichael Klier *  and gain information about the user who was blocked.
516e403cc58SMichael Klier *
517e403cc58SMichael Klier *  Event data:
518e403cc58SMichael Klier *    data['matches']  - array of matches
519e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
520e403cc58SMichael Klier *      [ip]           - ip address
521e403cc58SMichael Klier *      [user]         - username (if logged in)
522e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
523e403cc58SMichael Klier *      [name]         - real name (if logged in)
524e403cc58SMichael Klier *
52515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5266dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
5276dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
5286dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
529f3f0262cSandi */
5306dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
531f3f0262cSandi    global $TEXT;
5326dffa0e0SAndreas Gohr    global $PRE;
5336dffa0e0SAndreas Gohr    global $SUF;
534f3f0262cSandi    global $conf;
535e403cc58SMichael Klier    global $INFO;
536f3f0262cSandi
537f3f0262cSandi    if(!$conf['usewordblock']) return false;
538f3f0262cSandi
5396dffa0e0SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF";
5406dffa0e0SAndreas Gohr
541041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
5426dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
543041d1964SAndreas Gohr
544b9ac8716Schris    $wordblocks = getWordblocks();
5453e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
5463e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
5473e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
5483e2965d7Sandi        // backreferences are used - the maximum is 99
5493e2965d7Sandi        // this is very bad performancewise and may even be too high still
5503e2965d7Sandi        $chunksize = 40;
5513e2965d7Sandi    } else {
552a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
5533e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
554a51d08efSAndreas Gohr        $chunksize = 200;
5553e2965d7Sandi    }
556b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
557f3f0262cSandi        $re = array();
55849eb6e38SAndreas Gohr        // build regexp from blocks
559f3f0262cSandi        foreach($blocks as $block) {
560f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
561f3f0262cSandi            $block = trim($block);
562f3f0262cSandi            if(empty($block)) continue;
563f3f0262cSandi            $re[] = $block;
564f3f0262cSandi        }
565e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
566e403cc58SMichael Klier            // prepare event data
567e403cc58SMichael Klier            $data['matches']        = $matches;
568e403cc58SMichael Klier            $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
569e403cc58SMichael Klier            if($_SERVER['REMOTE_USER']) {
570e403cc58SMichael Klier                $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
571e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
572e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
573e403cc58SMichael Klier            }
574e403cc58SMichael Klier            $callback = create_function('', 'return true;');
575e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
576b9ac8716Schris        }
577703f6fdeSandi    }
578f3f0262cSandi    return false;
579f3f0262cSandi}
580f3f0262cSandi
581f3f0262cSandi/**
58215fae107Sandi * Return the IP of the client
58315fae107Sandi *
5846d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
58515fae107Sandi *
5866d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
5876d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
5886d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
5896d8affe6SAndreas Gohr * headers
5906d8affe6SAndreas Gohr *
59115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
592*3272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
593*3272d797SAndreas Gohr * @return string
594f3f0262cSandi */
5956d8affe6SAndreas Gohrfunction clientIP($single = false) {
5966d8affe6SAndreas Gohr    $ip   = array();
5976d8affe6SAndreas Gohr    $ip[] = $_SERVER['REMOTE_ADDR'];
598bb4866bdSchris    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
5995cbeffbfSMarcel Pennewiß        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_FORWARDED_FOR'])));
600bb4866bdSchris    if(!empty($_SERVER['HTTP_X_REAL_IP']))
6015cbeffbfSMarcel Pennewiß        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_REAL_IP'])));
6026d8affe6SAndreas Gohr
603dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
604dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
605dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
606dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
607dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
608dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
609dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
610dc14c6d1SGuy Brand    $IPv6Address =
611dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
612dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
613dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
614dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
615dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
616dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
617dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
618dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
619dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
620dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
621dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
622dc14c6d1SGuy Brand
6236d8affe6SAndreas Gohr    // remove any non-IP stuff
6246d8affe6SAndreas Gohr    $cnt   = count($ip);
6254ff28443Schris    $match = array();
6266d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
627dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
6284ff28443Schris            $ip[$i] = $match[0];
6294ff28443Schris        } else {
6304ff28443Schris            $ip[$i] = '';
6314ff28443Schris        }
6326d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
633f3f0262cSandi    }
6346d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
6356d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6366d8affe6SAndreas Gohr
6376d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
6386d8affe6SAndreas Gohr
6396d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
6406d8affe6SAndreas Gohr    $ip = array_reverse($ip);
6416d8affe6SAndreas Gohr    foreach($ip as $i) {
6422343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
6436d8affe6SAndreas Gohr            continue;
6446d8affe6SAndreas Gohr        } else {
6456d8affe6SAndreas Gohr            return $i;
6466d8affe6SAndreas Gohr        }
6476d8affe6SAndreas Gohr    }
6486d8affe6SAndreas Gohr    // still here? just use the first (last) address
6496d8affe6SAndreas Gohr    return $ip[0];
650f3f0262cSandi}
651f3f0262cSandi
652f3f0262cSandi/**
6531c548ebeSAndreas Gohr * Check if the browser is on a mobile device
6541c548ebeSAndreas Gohr *
6551c548ebeSAndreas Gohr * Adapted from the example code at url below
6561c548ebeSAndreas Gohr *
6571c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
6581c548ebeSAndreas Gohr */
6591c548ebeSAndreas Gohrfunction clientismobile() {
6601c548ebeSAndreas Gohr
6611c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
6621c548ebeSAndreas Gohr
6631c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i', $_SERVER['HTTP_ACCEPT'])) return true;
6641c548ebeSAndreas Gohr
6651c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
6661c548ebeSAndreas Gohr
6671c548ebeSAndreas 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';
6681c548ebeSAndreas Gohr
6691c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i", $_SERVER['HTTP_USER_AGENT'])) return true;
6701c548ebeSAndreas Gohr
6711c548ebeSAndreas Gohr    return false;
6721c548ebeSAndreas Gohr}
6731c548ebeSAndreas Gohr
6741c548ebeSAndreas Gohr/**
67563211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
67663211f61SGlen Harris *
67722ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
67822ef1e32SAndreas Gohr *
67963211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
680*3272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
681*3272d797SAndreas Gohr * @return string a comma separated list of hostnames
68263211f61SGlen Harris */
68363211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
68422ef1e32SAndreas Gohr    global $conf;
68522ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
68622ef1e32SAndreas Gohr
68763211f61SGlen Harris    $hosts = array();
68863211f61SGlen Harris    $ips   = explode(',', $ips);
689551a720fSMichael Klier
690551a720fSMichael Klier    if(is_array($ips)) {
6913886270dSAndreas Gohr        foreach($ips as $ip) {
692551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
69363211f61SGlen Harris        }
694551a720fSMichael Klier        return join(',', $hosts);
695551a720fSMichael Klier    } else {
696551a720fSMichael Klier        return gethostbyaddr(trim($ips));
697551a720fSMichael Klier    }
69863211f61SGlen Harris}
69963211f61SGlen Harris
70063211f61SGlen Harris/**
70115fae107Sandi * Checks if a given page is currently locked.
70215fae107Sandi *
703f3f0262cSandi * removes stale lockfiles
70415fae107Sandi *
70515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
706f3f0262cSandi */
707f3f0262cSandifunction checklock($id) {
708f3f0262cSandi    global $conf;
709c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
710f3f0262cSandi
711f3f0262cSandi    //no lockfile
712f3f0262cSandi    if(!@file_exists($lock)) return false;
713f3f0262cSandi
714f3f0262cSandi    //lockfile expired
715f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
716d8186216SBen Coburn        @unlink($lock);
717f3f0262cSandi        return false;
718f3f0262cSandi    }
719f3f0262cSandi
720f3f0262cSandi    //my own lock
72185fef7e2SAndreas Gohr    list($ip, $session) = explode("\n", io_readFile($lock));
72285fef7e2SAndreas Gohr    if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
723f3f0262cSandi        return false;
724f3f0262cSandi    }
725f3f0262cSandi
726f3f0262cSandi    return $ip;
727f3f0262cSandi}
728f3f0262cSandi
729f3f0262cSandi/**
73015fae107Sandi * Lock a page for editing
73115fae107Sandi *
73215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
733f3f0262cSandi */
734f3f0262cSandifunction lock($id) {
735544ed901SDaniel Calviño Sánchez    global $conf;
736544ed901SDaniel Calviño Sánchez
737544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
738544ed901SDaniel Calviño Sánchez        return;
739544ed901SDaniel Calviño Sánchez    }
740544ed901SDaniel Calviño Sánchez
741c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
742f3f0262cSandi    if($_SERVER['REMOTE_USER']) {
743f3f0262cSandi        io_saveFile($lock, $_SERVER['REMOTE_USER']);
744f3f0262cSandi    } else {
74585fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
746f3f0262cSandi    }
747f3f0262cSandi}
748f3f0262cSandi
749f3f0262cSandi/**
75015fae107Sandi * Unlock a page if it was locked by the user
751f3f0262cSandi *
75215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
753*3272d797SAndreas Gohr * @param string $id page id to unlock
75415fae107Sandi * @return bool true if a lock was removed
755f3f0262cSandi */
756f3f0262cSandifunction unlock($id) {
757c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
758f3f0262cSandi    if(@file_exists($lock)) {
75985fef7e2SAndreas Gohr        list($ip, $session) = explode("\n", io_readFile($lock));
76085fef7e2SAndreas Gohr        if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
761f3f0262cSandi            @unlink($lock);
762f3f0262cSandi            return true;
763f3f0262cSandi        }
764f3f0262cSandi    }
765f3f0262cSandi    return false;
766f3f0262cSandi}
767f3f0262cSandi
768f3f0262cSandi/**
769f3f0262cSandi * convert line ending to unix format
770f3f0262cSandi *
77115fae107Sandi * @see    formText() for 2crlf conversion
77215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
773f3f0262cSandi */
774f3f0262cSandifunction cleanText($text) {
775f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
776f3f0262cSandi    return $text;
777f3f0262cSandi}
778f3f0262cSandi
779f3f0262cSandi/**
780f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
781f3f0262cSandi * It also converts line endings to Windows format which is
782f3f0262cSandi * pseudo standard for webforms.
783f3f0262cSandi *
78415fae107Sandi * @see    cleanText() for 2unix conversion
78515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
786f3f0262cSandi */
787f3f0262cSandifunction formText($text) {
7885b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
789f3f0262cSandi    return htmlspecialchars($text);
790f3f0262cSandi}
791f3f0262cSandi
792f3f0262cSandi/**
79315fae107Sandi * Returns the specified local text in raw format
79415fae107Sandi *
79515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
796f3f0262cSandi */
7972adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
7982adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
799f3f0262cSandi}
800f3f0262cSandi
801f3f0262cSandi/**
802f3f0262cSandi * Returns the raw WikiText
80315fae107Sandi *
80415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
805f3f0262cSandi */
806f3f0262cSandifunction rawWiki($id, $rev = '') {
807cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
808f3f0262cSandi}
809f3f0262cSandi
810f3f0262cSandi/**
8117146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
8127146cee2SAndreas Gohr *
8137b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
8147146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8157146cee2SAndreas Gohr */
816fe17917eSAdrian Langfunction pageTemplate($id) {
817a15ce62dSEsther Brunner    global $conf;
818e29549feSAndreas Gohr
819fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
820e29549feSAndreas Gohr
8217b84afa2SAndreas Gohr    // prepare initial event data
8227b84afa2SAndreas Gohr    $data = array(
8237b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
8247b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
8257b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
8267b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
8277b84afa2SAndreas Gohr    );
8287b84afa2SAndreas Gohr
8297b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
8307b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
8317b84afa2SAndreas Gohr        // the before event might have loaded the content already
8327b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
8337b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
8347b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
835fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
836e29549feSAndreas Gohr                if(@file_exists($path.'/_template.txt')) {
8377b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
838e29549feSAndreas Gohr                } else {
839e29549feSAndreas Gohr                    // search upper namespaces for templates
840e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
841e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
842e29549feSAndreas Gohr                        if(@file_exists($path.'/__template.txt')) {
8437b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
844e29549feSAndreas Gohr                            break;
845e29549feSAndreas Gohr                        }
846e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
847e29549feSAndreas Gohr                    }
848e29549feSAndreas Gohr                }
8497b84afa2SAndreas Gohr            }
8507b84afa2SAndreas Gohr            // load the content
8513d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
8527b84afa2SAndreas Gohr        }
853a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
8547b84afa2SAndreas Gohr    }
8557b84afa2SAndreas Gohr    $evt->advise_after();
8567b84afa2SAndreas Gohr    unset($evt);
8577b84afa2SAndreas Gohr
858fe17917eSAdrian Lang    return $data['tpl'];
8592b1223ecSAdrian Lang}
8602b1223ecSAdrian Lang
8612b1223ecSAdrian Lang/**
8622b1223ecSAdrian Lang * Performs common page template replacements
8637b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
8642b1223ecSAdrian Lang *
8652b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
8662b1223ecSAdrian Lang */
867d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
868*3272d797SAndreas Gohr    /**
869*3272d797SAndreas Gohr     * @var string $id        the id of the page to be created
870*3272d797SAndreas Gohr     * @var string $tpl       the text used as template
871*3272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
872*3272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
873*3272d797SAndreas Gohr     */
874fe17917eSAdrian Lang    extract($data);
875fe17917eSAdrian Lang
876b856f7dfSAdrian Lang    global $USERINFO;
877bce53b1fSAdrian Lang    global $conf;
878e29549feSAndreas Gohr
879e29549feSAndreas Gohr    // replace placeholders
88026ece5a7SAndreas Gohr    $file = noNS($id);
88137c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
88226ece5a7SAndreas Gohr
883*3272d797SAndreas Gohr    $tpl = str_replace(
884*3272d797SAndreas Gohr        array(
88526ece5a7SAndreas Gohr             '@ID@',
88626ece5a7SAndreas Gohr             '@NS@',
88726ece5a7SAndreas Gohr             '@FILE@',
88826ece5a7SAndreas Gohr             '@!FILE@',
88926ece5a7SAndreas Gohr             '@!FILE!@',
89026ece5a7SAndreas Gohr             '@PAGE@',
89126ece5a7SAndreas Gohr             '@!PAGE@',
89226ece5a7SAndreas Gohr             '@!!PAGE@',
89326ece5a7SAndreas Gohr             '@!PAGE!@',
89426ece5a7SAndreas Gohr             '@USER@',
89526ece5a7SAndreas Gohr             '@NAME@',
89626ece5a7SAndreas Gohr             '@MAIL@',
89726ece5a7SAndreas Gohr             '@DATE@',
89826ece5a7SAndreas Gohr        ),
89926ece5a7SAndreas Gohr        array(
90026ece5a7SAndreas Gohr             $id,
90126ece5a7SAndreas Gohr             getNS($id),
90226ece5a7SAndreas Gohr             $file,
90326ece5a7SAndreas Gohr             utf8_ucfirst($file),
90426ece5a7SAndreas Gohr             utf8_strtoupper($file),
90526ece5a7SAndreas Gohr             $page,
90626ece5a7SAndreas Gohr             utf8_ucfirst($page),
90726ece5a7SAndreas Gohr             utf8_ucwords($page),
90826ece5a7SAndreas Gohr             utf8_strtoupper($page),
90926ece5a7SAndreas Gohr             $_SERVER['REMOTE_USER'],
910b856f7dfSAdrian Lang             $USERINFO['name'],
911b856f7dfSAdrian Lang             $USERINFO['mail'],
91226ece5a7SAndreas Gohr             $conf['dformat'],
913*3272d797SAndreas Gohr        ), $tpl
914*3272d797SAndreas Gohr    );
91526ece5a7SAndreas Gohr
9167d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
9177d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
918d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
919a15ce62dSEsther Brunner    return $tpl;
9207146cee2SAndreas Gohr}
9217146cee2SAndreas Gohr
9227146cee2SAndreas Gohr/**
92315fae107Sandi * Returns the raw Wiki Text in three slices.
92415fae107Sandi *
92515fae107Sandi * The range parameter needs to have the form "from-to"
92615cfe303Sandi * and gives the range of the section in bytes - no
92715cfe303Sandi * UTF-8 awareness is needed.
928f3f0262cSandi * The returned order is prefix, section and suffix.
92915fae107Sandi *
93015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
931f3f0262cSandi */
932f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
933cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
934f3f0262cSandi
93580fcb268SAdrian Lang    // Parse range
93680fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
93780fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
93880fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
93980fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
94080fcb268SAdrian Lang
94180fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
94280fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
94315cfe303Sandi    $slices[2] = substr($text, $to);
944f3f0262cSandi    return $slices;
945f3f0262cSandi}
946f3f0262cSandi
947f3f0262cSandi/**
94815fae107Sandi * Joins wiki text slices
94915fae107Sandi *
95080fcb268SAdrian Lang * function to join the text slices.
951f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
952f3f0262cSandi * lines between sections if needed (used on saving).
95315fae107Sandi *
95415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
955f3f0262cSandi */
956f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
957f3f0262cSandi    if($pretty) {
95880fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
959*3272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
960*3272d797SAndreas Gohr        ) {
96180fcb268SAdrian Lang            $pre .= "\n";
96280fcb268SAdrian Lang        }
96380fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
964*3272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
965*3272d797SAndreas Gohr        ) {
96680fcb268SAdrian Lang            $text .= "\n";
96780fcb268SAdrian Lang        }
968f3f0262cSandi    }
969f3f0262cSandi
970f3f0262cSandi    return $pre.$text.$suf;
971f3f0262cSandi}
972f3f0262cSandi
973f3f0262cSandi/**
974a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
975a701424fSBen Coburn * Also directs changelog and attic updates.
97615fae107Sandi *
97715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
97871726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
979f3f0262cSandi */
980b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
981a701424fSBen Coburn    /* Note to developers:
982a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
983a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
984a701424fSBen Coburn       after any changes. External edits change the wiki page
985a701424fSBen Coburn       directly without using php or dokuwiki.
986a701424fSBen Coburn     */
987f3f0262cSandi    global $conf;
988f3f0262cSandi    global $lang;
98971726d78SBen Coburn    global $REV;
990f3f0262cSandi    // ignore if no changes were made
991f3f0262cSandi    if($text == rawWiki($id, '')) {
992f3f0262cSandi        return;
993f3f0262cSandi    }
994f3f0262cSandi
995f3f0262cSandi    $file        = wikiFN($id);
996a701424fSBen Coburn    $old         = @filemtime($file); // from page
997407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
998d8186216SBen Coburn    $wasCreated  = !@file_exists($file);
99971726d78SBen Coburn    $wasReverted = ($REV == true);
1000e45b34cdSBen Coburn    $newRev      = false;
1001a701424fSBen Coburn    $oldRev      = getRevisions($id, -1, 1, 1024); // from changelog
1002a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1003a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
100446844156SBen Coburn        // add old revision to the attic if missing
100546844156SBen Coburn        saveOldRevision($id);
100646844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1007a701424fSBen Coburn        if($old > $oldRev) {
1008ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
100946844156SBen Coburn            // remove soon to be stale instructions
101046844156SBen Coburn            $cache = new cache_instructions($id, $file);
101146844156SBen Coburn            $cache->removeCache();
101246844156SBen Coburn        }
101346844156SBen Coburn    }
1014f3f0262cSandi
101571726d78SBen Coburn    if($wasRemoved) {
101630725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
101730725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
101830725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1019e45b34cdSBen Coburn        // pre-save deleted revision
1020e45b34cdSBen Coburn        @touch($file);
102146844156SBen Coburn        clearstatcache();
1022e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1023e1f3d9e1SEsther Brunner        // remove empty file
1024f3f0262cSandi        @unlink($file);
1025c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1026c5f92742SMichael Hamann        // purge non-persistant meta data
10273d1f9ec3SMichael Klier        p_purge_metadata($id);
1028f3f0262cSandi        $del = true;
10293ce054b3Sandi        // autoset summary on deletion
10303ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
103153d6ccfeSandi        // remove empty namespaces
1032cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1033cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1034f3f0262cSandi    } else {
1035cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1036cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
103746844156SBen Coburn        // pre-save the revision, to keep the attic in sync
103846844156SBen Coburn        $newRev = saveOldRevision($id);
1039f3f0262cSandi        $del    = false;
1040f3f0262cSandi    }
1041f3f0262cSandi
104271726d78SBen Coburn    // select changelog line type
104371726d78SBen Coburn    $extra = '';
1044ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
104571726d78SBen Coburn    if($wasReverted) {
1046ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
104771726d78SBen Coburn        $extra = $REV;
1048*3272d797SAndreas Gohr    } else if($wasCreated) {
1049*3272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
1050*3272d797SAndreas Gohr    } else if($wasRemoved) {
1051*3272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
1052*3272d797SAndreas Gohr    } else if($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) {
1053*3272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
1054*3272d797SAndreas Gohr    } //minor edits only for logged in users
105571726d78SBen Coburn
1056e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
105726a0801fSAndreas Gohr    // send notify mails
105890033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
105990033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1060f3f0262cSandi
1061ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
106298407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
10632eccbdaaSGina Haeussge
10642eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1065fe9ec250SChris Smith    if(useHeading('content')) {
10662eccbdaaSGina Haeussge        $pages = ft_backlinks($id);
10672eccbdaaSGina Haeussge        foreach($pages as $page) {
10682eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
10692eccbdaaSGina Haeussge            $cache->removeCache();
10702eccbdaaSGina Haeussge        }
10712eccbdaaSGina Haeussge    }
1072f3f0262cSandi}
1073f3f0262cSandi
1074f3f0262cSandi/**
1075f3f0262cSandi * moves the current version to the attic and returns its
1076f3f0262cSandi * revision date
107715fae107Sandi *
107815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1079f3f0262cSandi */
1080f3f0262cSandifunction saveOldRevision($id) {
1081f3f0262cSandi    global $conf;
1082f3f0262cSandi    $oldf = wikiFN($id);
1083f3f0262cSandi    if(!@file_exists($oldf)) return '';
1084f3f0262cSandi    $date = filemtime($oldf);
1085f3f0262cSandi    $newf = wikiFN($id, $date);
1086cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1087f3f0262cSandi    return $date;
1088f3f0262cSandi}
1089f3f0262cSandi
1090f3f0262cSandi/**
1091fde10de4SAdrian Lang * Sends a notify mail on page change or registration
109226a0801fSAndreas Gohr *
109326a0801fSAndreas Gohr * @param string     $id       The changed page
1094fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
1095*3272d797SAndreas Gohr * @param int|string $rev Old page revision
109626a0801fSAndreas Gohr * @param string     $summary  What changed
109790033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
109802a498e7Schris * @param array      $replace  Additional string substitutions, @KEY@ to be replaced by value
109915fae107Sandi *
1100*3272d797SAndreas Gohr * @return bool
110115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1102f3f0262cSandi */
110302a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1104f3f0262cSandi    global $lang;
1105f3f0262cSandi    global $conf;
110630d7d718SMike Frysinger    global $INFO;
110747a906eaSAndreas Gohr    global $DIFF_INLINESTYLES;
1108b158d625SSteven Danz
11096df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
111026a0801fSAndreas Gohr    if($who == 'admin') {
1111*3272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
1112f3f0262cSandi        $text = rawLocale('mailtext');
111326a0801fSAndreas Gohr        $to   = $conf['notify'];
111426a0801fSAndreas Gohr        $bcc  = '';
111526a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
1116*3272d797SAndreas Gohr        if(!$conf['subscribers']) return false; //subscribers enabled?
1117*3272d797SAndreas Gohr        if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return false; //skip minors
11188881fcc9SAdrian Lang        $data = array('id' => $id, 'addresslist' => '', 'self' => false);
1119*3272d797SAndreas Gohr        trigger_event(
1120*3272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1121*3272d797SAndreas Gohr            'subscription_addresslist'
1122*3272d797SAndreas Gohr        );
11238881fcc9SAdrian Lang        $bcc = $data['addresslist'];
1124*3272d797SAndreas Gohr        if(empty($bcc)) return false;
112526a0801fSAndreas Gohr        $to   = '';
11265b75cd1fSAdrian Lang        $text = rawLocale('subscr_single');
1127a06e4bdbSSebastian Harl    } elseif($who == 'register') {
1128*3272d797SAndreas Gohr        if(empty($conf['registernotify'])) return false;
1129a06e4bdbSSebastian Harl        $text = rawLocale('registermail');
1130a06e4bdbSSebastian Harl        $to   = $conf['registernotify'];
1131a06e4bdbSSebastian Harl        $bcc  = '';
113226a0801fSAndreas Gohr    } else {
1133*3272d797SAndreas Gohr        return false; //just to be safe
113426a0801fSAndreas Gohr    }
113526a0801fSAndreas Gohr
11366df843eeSAndreas Gohr    // prepare replacements (keys not set in hrep will be taken from trep)
11376df843eeSAndreas Gohr    $trep = array(
11386df843eeSAndreas Gohr        'NEWPAGE' => wl($id, '', true, '&'),
11396df843eeSAndreas Gohr        'PAGE'    => $id,
11406df843eeSAndreas Gohr        'SUMMARY' => $summary
11416df843eeSAndreas Gohr    );
11426df843eeSAndreas Gohr    $trep = array_merge($trep, $replace);
11436df843eeSAndreas Gohr    $hrep = array();
1144f3f0262cSandi
11456df843eeSAndreas Gohr    // prepare content
1146a06e4bdbSSebastian Harl    if($who == 'register') {
1147a06e4bdbSSebastian Harl        $subject = $lang['mail_new_user'].' '.$summary;
1148a06e4bdbSSebastian Harl    } elseif($rev) {
1149f3f0262cSandi        $subject         = $lang['mail_changed'].' '.$id;
11506df843eeSAndreas Gohr        $trep['OLDPAGE'] = wl($id, "rev=$rev", true, '&');
11514b7f9e70STom N Harris        $df              = new Diff(explode("\n", rawWiki($id, $rev)),
11524b7f9e70STom N Harris                                    explode("\n", rawWiki($id)));
1153f3f0262cSandi        $dformat         = new UnifiedDiffFormatter();
11546df843eeSAndreas Gohr        $tdiff           = $dformat->format($df);
115547a906eaSAndreas Gohr
115647a906eaSAndreas Gohr        $DIFF_INLINESTYLES = true;
11576df843eeSAndreas Gohr        $dformat           = new InlineDiffFormatter();
11586df843eeSAndreas Gohr        $hdiff             = $dformat->format($df);
115904058413SAndreas Gohr        $hdiff             = '<table>'.$hdiff.'</table>';
116047a906eaSAndreas Gohr        $DIFF_INLINESTYLES = false;
1161f3f0262cSandi    } else {
1162f3f0262cSandi        $subject         = $lang['mail_newpage'].' '.$id;
11636df843eeSAndreas Gohr        $trep['OLDPAGE'] = '---';
11646df843eeSAndreas Gohr        $tdiff           = rawWiki($id);
11656df843eeSAndreas Gohr        $hdiff           = nl2br(hsc($tdiff));
1166f3f0262cSandi    }
11676df843eeSAndreas Gohr    $trep['DIFF'] = $tdiff;
11686df843eeSAndreas Gohr    $hrep['DIFF'] = $hdiff;
11696df843eeSAndreas Gohr
11706df843eeSAndreas Gohr    // send mail
11716df843eeSAndreas Gohr    $mail = new Mailer();
11726df843eeSAndreas Gohr    $mail->to($to);
11736df843eeSAndreas Gohr    $mail->bcc($bcc);
11746df843eeSAndreas Gohr    $mail->subject($subject);
1175b796e32eSAndreas Gohr    $mail->setBody($text, $trep, $hrep);
11769f3eca0bSAndreas Gohr    if($who == 'subscribers') {
11779f3eca0bSAndreas Gohr        $mail->setHeader(
11789f3eca0bSAndreas Gohr            'List-Unsubscribe',
11799f3eca0bSAndreas Gohr            '<'.wl($id, array('do'=> 'subscribe'), true, '&').'>',
11809f3eca0bSAndreas Gohr            false
11819f3eca0bSAndreas Gohr        );
11829f3eca0bSAndreas Gohr    }
11836df843eeSAndreas Gohr    return $mail->send();
1184f3f0262cSandi}
1185f3f0262cSandi
118615fae107Sandi/**
118771f7bde7SAndreas Gohr * extracts the query from a search engine referrer
118815fae107Sandi *
118915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
119071f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1191f3f0262cSandi */
1192f3f0262cSandifunction getGoogleQuery() {
1193c66972f2SAdrian Lang    if(!isset($_SERVER['HTTP_REFERER'])) {
1194c66972f2SAdrian Lang        return '';
1195c66972f2SAdrian Lang    }
1196f3f0262cSandi    $url = parse_url($_SERVER['HTTP_REFERER']);
1197f3f0262cSandi
1198f3f0262cSandi    $query = array();
1199e4d8a516SKazutaka Miyasaka
1200e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1201e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1202e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1203f3f0262cSandi    parse_str($url['query'], $query);
1204e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1205e4d8a516SKazutaka Miyasaka
1206c66972f2SAdrian Lang    $q = '';
120771f7bde7SAndreas Gohr    if(isset($query['q']))
1208f93b3b50SAndreas Gohr        $q = $query['q']; // google, live/msn, aol, ask, altavista, alltheweb, gigablast
120971f7bde7SAndreas Gohr    elseif(isset($query['p']))
1210f93b3b50SAndreas Gohr        $q = $query['p']; // yahoo
121171f7bde7SAndreas Gohr    elseif(isset($query['query']))
1212f93b3b50SAndreas Gohr        $q = $query['query']; // lycos, netscape, clusty, hotbot
121371f7bde7SAndreas Gohr    elseif(preg_match("#a9\.com#i", $url['host'])) // a9
1214f93b3b50SAndreas Gohr        $q = urldecode(ltrim($url['path'], '/'));
1215f3f0262cSandi
1216c66972f2SAdrian Lang    if($q === '') return '';
12176531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1218f93b3b50SAndreas Gohr    return $q;
1219f3f0262cSandi}
1220f3f0262cSandi
1221f3f0262cSandi/**
122215fae107Sandi * Try to set correct locale
122315fae107Sandi *
1224095bfd5cSandi * @deprecated No longer used
122515fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1226f3f0262cSandi */
1227f3f0262cSandifunction setCorrectLocale() {
1228f3f0262cSandi    global $conf;
1229f3f0262cSandi    global $lang;
1230f3f0262cSandi
1231f3f0262cSandi    $enc = strtoupper($lang['encoding']);
1232f3f0262cSandi    foreach($lang['locales'] as $loc) {
1233f3f0262cSandi        //try locale
1234f3f0262cSandi        if(@setlocale(LC_ALL, $loc)) return;
1235f3f0262cSandi        //try loceale with encoding
1236f3f0262cSandi        if(@setlocale(LC_ALL, "$loc.$enc")) return;
1237f3f0262cSandi    }
1238f3f0262cSandi    //still here? try to set from environment
1239f3f0262cSandi    @setlocale(LC_ALL, "");
1240f3f0262cSandi}
1241f3f0262cSandi
1242f3f0262cSandi/**
1243f3f0262cSandi * Return the human readable size of a file
1244f3f0262cSandi *
1245f3f0262cSandi * @param       int    $size   A file size
1246f3f0262cSandi * @param       int    $dec    A number of decimal places
1247f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1248f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1249f3f0262cSandi * @version     1.0.0
1250f3f0262cSandi */
1251f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1252f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1253f3f0262cSandi    $count = count($sizes);
1254f3f0262cSandi    $i     = 0;
1255f3f0262cSandi
1256f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1257f3f0262cSandi        $size /= 1024;
1258f3f0262cSandi        $i++;
1259f3f0262cSandi    }
1260f3f0262cSandi
1261f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1262f3f0262cSandi}
1263f3f0262cSandi
126415fae107Sandi/**
1265c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1266c57e365eSAndreas Gohr *
1267c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1268c57e365eSAndreas Gohr */
1269c57e365eSAndreas Gohrfunction datetime_h($dt) {
1270c57e365eSAndreas Gohr    global $lang;
1271c57e365eSAndreas Gohr
1272c57e365eSAndreas Gohr    $ago = time() - $dt;
1273c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1274c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1275c57e365eSAndreas Gohr    }
1276c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1277c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1278c57e365eSAndreas Gohr    }
1279c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1280c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1281c57e365eSAndreas Gohr    }
1282c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1283c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1284c57e365eSAndreas Gohr    }
1285c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1286c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1287c57e365eSAndreas Gohr    }
1288c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1289c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1290c57e365eSAndreas Gohr    }
1291c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1292c57e365eSAndreas Gohr}
1293c57e365eSAndreas Gohr
1294c57e365eSAndreas Gohr/**
1295f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1296f2263577SAndreas Gohr *
1297f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1298f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1299f2263577SAndreas Gohr *
1300f2263577SAndreas Gohr * @see datetime_h
1301f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1302f2263577SAndreas Gohr */
1303f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1304f2263577SAndreas Gohr    global $conf;
1305f2263577SAndreas Gohr
1306f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1307f2263577SAndreas Gohr    $dt = (int) $dt;
1308f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1309f2263577SAndreas Gohr
1310f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1311f2263577SAndreas Gohr    return strftime($format, $dt);
1312f2263577SAndreas Gohr}
1313f2263577SAndreas Gohr
1314f2263577SAndreas Gohr/**
1315c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1316c4f79b71SMichael Hamann *
1317c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1318c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
131963703ba5SAndreas Gohr * @param int $int_date: current date in UNIX timestamp
1320*3272d797SAndreas Gohr * @return string
1321c4f79b71SMichael Hamann */
1322c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1323c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1324c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1325c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1326c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1327c4f79b71SMichael Hamann    return $date_mod;
1328c4f79b71SMichael Hamann}
1329c4f79b71SMichael Hamann
1330c4f79b71SMichael Hamann/**
133100a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
133200a7b5adSEsther Brunner *
133300a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
133400a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
133500a7b5adSEsther Brunner */
133600a7b5adSEsther Brunnerfunction obfuscate($email) {
133700a7b5adSEsther Brunner    global $conf;
133800a7b5adSEsther Brunner
133900a7b5adSEsther Brunner    switch($conf['mailguard']) {
134000a7b5adSEsther Brunner        case 'visible' :
134100a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
134200a7b5adSEsther Brunner            return strtr($email, $obfuscate);
134300a7b5adSEsther Brunner
134400a7b5adSEsther Brunner        case 'hex' :
134500a7b5adSEsther Brunner            $encode = '';
134649eb6e38SAndreas Gohr            $len    = strlen($email);
134749eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
134849eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
134949eb6e38SAndreas Gohr            }
135000a7b5adSEsther Brunner            return $encode;
135100a7b5adSEsther Brunner
135200a7b5adSEsther Brunner        case 'none' :
135300a7b5adSEsther Brunner        default :
135400a7b5adSEsther Brunner            return $email;
135500a7b5adSEsther Brunner    }
135600a7b5adSEsther Brunner}
135700a7b5adSEsther Brunner
135800a7b5adSEsther Brunner/**
135989541d4bSAndreas Gohr * Removes quoting backslashes
136089541d4bSAndreas Gohr *
136189541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
136289541d4bSAndreas Gohr */
136389541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
136489541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
136589541d4bSAndreas Gohr}
136689541d4bSAndreas Gohr
136773038c47SAndreas Gohr/**
136873038c47SAndreas Gohr * Convert php.ini shorthands to byte
136973038c47SAndreas Gohr *
137073038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
137173038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
137273038c47SAndreas Gohr */
137373038c47SAndreas Gohrfunction php_to_byte($v) {
137473038c47SAndreas Gohr    $l   = substr($v, -1);
137573038c47SAndreas Gohr    $ret = substr($v, 0, -1);
137673038c47SAndreas Gohr    switch(strtoupper($l)) {
137773038c47SAndreas Gohr        case 'P':
137873038c47SAndreas Gohr            $ret *= 1024;
137973038c47SAndreas Gohr        case 'T':
138073038c47SAndreas Gohr            $ret *= 1024;
138173038c47SAndreas Gohr        case 'G':
138273038c47SAndreas Gohr            $ret *= 1024;
138373038c47SAndreas Gohr        case 'M':
138473038c47SAndreas Gohr            $ret *= 1024;
138573038c47SAndreas Gohr        case 'K':
138673038c47SAndreas Gohr            $ret *= 1024;
138773038c47SAndreas Gohr            break;
138849cbd23eSOtto Vainio        default;
138949cbd23eSOtto Vainio            $ret *= 10;
139049cbd23eSOtto Vainio            break;
139173038c47SAndreas Gohr    }
139273038c47SAndreas Gohr    return $ret;
139373038c47SAndreas Gohr}
139473038c47SAndreas Gohr
1395546d3a99SAndreas Gohr/**
1396546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1397546d3a99SAndreas Gohr */
1398546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1399546d3a99SAndreas Gohr    return preg_quote($string, '/');
1400546d3a99SAndreas Gohr}
140173038c47SAndreas Gohr
1402bd2f6c2fSAndreas Gohr/**
1403bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1404bd2f6c2fSAndreas Gohr *
1405c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1406bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1407bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1408bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1409bd2f6c2fSAndreas Gohr *
1410bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1411bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1412bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1413bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1414bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
1415*3272d797SAndreas Gohr * @return string
1416bd2f6c2fSAndreas Gohr */
1417a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1418bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1419bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1420bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1421bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1422bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1423bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1424bd2f6c2fSAndreas Gohr}
1425bd2f6c2fSAndreas Gohr
1426dc58b6f4SAndy Webber/**
1427dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1428dc58b6f4SAndy Webber * in page footer and recent changes pages
1429dc58b6f4SAndy Webber *
1430dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1431dc58b6f4SAndy Webber */
1432dc58b6f4SAndy Webberfunction editorinfo($username) {
1433dc58b6f4SAndy Webber    global $conf;
1434dc58b6f4SAndy Webber    global $auth;
1435dc58b6f4SAndy Webber
1436dc58b6f4SAndy Webber    switch($conf['showuseras']) {
1437dc58b6f4SAndy Webber        case 'username':
1438dc58b6f4SAndy Webber        case 'email':
1439dc58b6f4SAndy Webber        case 'email_link':
1440173d78c4SAndreas Gohr            if($auth) $info = $auth->getUserData($username);
1441dc58b6f4SAndy Webber            break;
1442dc58b6f4SAndy Webber        default:
1443dc58b6f4SAndy Webber            return hsc($username);
1444dc58b6f4SAndy Webber    }
1445dc58b6f4SAndy Webber
1446dc58b6f4SAndy Webber    if(isset($info) && $info) {
1447dc58b6f4SAndy Webber        switch($conf['showuseras']) {
1448dc58b6f4SAndy Webber            case 'username':
1449dc58b6f4SAndy Webber                return hsc($info['name']);
1450dc58b6f4SAndy Webber            case 'email':
1451dc58b6f4SAndy Webber                return obfuscate($info['mail']);
1452dc58b6f4SAndy Webber            case 'email_link':
1453dc58b6f4SAndy Webber                $mail = obfuscate($info['mail']);
1454dc58b6f4SAndy Webber                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1455dc58b6f4SAndy Webber            default:
1456dc58b6f4SAndy Webber                return hsc($username);
1457dc58b6f4SAndy Webber        }
1458dc58b6f4SAndy Webber    } else {
1459dc58b6f4SAndy Webber        return hsc($username);
1460dc58b6f4SAndy Webber    }
1461066fee30SAndreas Gohr}
1462066fee30SAndreas Gohr
1463066fee30SAndreas Gohr/**
1464066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1465066fee30SAndreas Gohr * When no image exists, returns an empty string
1466066fee30SAndreas Gohr *
1467066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1468066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
1469*3272d797SAndreas Gohr * @return string
1470066fee30SAndreas Gohr */
1471066fee30SAndreas Gohrfunction license_img($type) {
1472066fee30SAndreas Gohr    global $license;
1473066fee30SAndreas Gohr    global $conf;
1474066fee30SAndreas Gohr    if(!$conf['license']) return '';
1475066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1476066fee30SAndreas Gohr    $lic   = $license[$conf['license']];
1477066fee30SAndreas Gohr    $try   = array();
1478066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1479066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1480066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1481066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1482066fee30SAndreas Gohr    }
1483066fee30SAndreas Gohr    foreach($try as $src) {
1484066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1485066fee30SAndreas Gohr    }
1486066fee30SAndreas Gohr    return '';
1487dc58b6f4SAndy Webber}
1488dc58b6f4SAndy Webber
148913c08e2fSMichael Klier/**
149013c08e2fSMichael Klier * Checks if the given amount of memory is available
149113c08e2fSMichael Klier *
149213c08e2fSMichael Klier * If the memory_get_usage() function is not available the
149313c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
149413c08e2fSMichael Klier *
149513c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
149613c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
1497*3272d797SAndreas Gohr *
1498*3272d797SAndreas Gohr * @param  int $mem  Size of memory you want to allocate in bytes
1499*3272d797SAndreas Gohr * @param int  $bytes
1500*3272d797SAndreas Gohr * @internal param int $used already allocated memory (see above)
1501*3272d797SAndreas Gohr * @return bool
150213c08e2fSMichael Klier */
150313c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
150413c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
150513c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
150613c08e2fSMichael Klier
150713c08e2fSMichael Klier    // parse limit to bytes
150813c08e2fSMichael Klier    $limit = php_to_byte($limit);
150913c08e2fSMichael Klier
151013c08e2fSMichael Klier    // get used memory if possible
151113c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
151213c08e2fSMichael Klier        $used = memory_get_usage();
151349eb6e38SAndreas Gohr    } else {
151449eb6e38SAndreas Gohr        $used = $bytes;
151513c08e2fSMichael Klier    }
151613c08e2fSMichael Klier
151713c08e2fSMichael Klier    if($used + $mem > $limit) {
151813c08e2fSMichael Klier        return false;
151913c08e2fSMichael Klier    }
152013c08e2fSMichael Klier
152113c08e2fSMichael Klier    return true;
152213c08e2fSMichael Klier}
152313c08e2fSMichael Klier
1524af2408d5SAndreas Gohr/**
1525af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1526af2408d5SAndreas Gohr *
1527af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1528af2408d5SAndreas Gohr *
1529af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1530af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1531af2408d5SAndreas Gohr */
1532af2408d5SAndreas Gohrfunction send_redirect($url) {
15330181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
15340181f021SAndreas Gohr    global $MSG;
15350181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
15360181f021SAndreas Gohr        //reopen session, store data and close session again
15370181f021SAndreas Gohr        @session_start();
15380181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
15390181f021SAndreas Gohr    }
15400181f021SAndreas Gohr
1541d4869846SAndreas Gohr    // always close the session
1542d4869846SAndreas Gohr    session_write_close();
1543d4869846SAndreas Gohr
1544c10dcb7dSAndreas Gohr    // work around IE bug
1545c10dcb7dSAndreas Gohr    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
1546c10dcb7dSAndreas Gohr    list($url, $hash) = explode('#', $url);
1547c10dcb7dSAndreas Gohr    if($hash) {
1548c10dcb7dSAndreas Gohr        if(strpos($url, '?')) {
1549c10dcb7dSAndreas Gohr            $url = $url.'&#'.$hash;
1550c10dcb7dSAndreas Gohr        } else {
1551c10dcb7dSAndreas Gohr            $url = $url.'?&#'.$hash;
1552c10dcb7dSAndreas Gohr        }
1553c10dcb7dSAndreas Gohr    }
1554c10dcb7dSAndreas Gohr
1555af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1556af2408d5SAndreas Gohr    if(isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1557af2408d5SAndreas Gohr        (strpos($_SERVER['GATEWAY_INTERFACE'], 'CGI') !== false) &&
1558af2408d5SAndreas Gohr        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1559*3272d797SAndreas Gohr        $matches[1] < 6
1560*3272d797SAndreas Gohr    ) {
1561af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1562af2408d5SAndreas Gohr    } else {
1563af2408d5SAndreas Gohr        header('Location: '.$url);
1564af2408d5SAndreas Gohr    }
1565af2408d5SAndreas Gohr    exit;
1566af2408d5SAndreas Gohr}
1567af2408d5SAndreas Gohr
15685b75cd1fSAdrian Lang/**
15695b75cd1fSAdrian Lang * Validate a value using a set of valid values
15705b75cd1fSAdrian Lang *
15715b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
15725b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
15735b75cd1fSAdrian Lang * default is specified, throws an exception.
15745b75cd1fSAdrian Lang *
15755b75cd1fSAdrian Lang * @param string $param        The name of the parameter
15765b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
15775b75cd1fSAdrian Lang *                             be marked by the key “default”.
15785b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
15795b75cd1fSAdrian Lang *                             or $_GET)
15805b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
15815b75cd1fSAdrian Lang *
1582*3272d797SAndreas Gohr * @throws Exception
1583*3272d797SAndreas Gohr * @return mixed
15845b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
15855b75cd1fSAdrian Lang */
15865b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
15875b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
15885b75cd1fSAdrian Lang        return $array[$param];
15895b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
15905b75cd1fSAdrian Lang        return $valid_values['default'];
15915b75cd1fSAdrian Lang    } else {
15925b75cd1fSAdrian Lang        throw new Exception($exc);
15935b75cd1fSAdrian Lang    }
15945b75cd1fSAdrian Lang}
15955b75cd1fSAdrian Lang
159663703ba5SAndreas Gohr/**
159763703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
159863703ba5SAndreas Gohr */
1599554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1600554a8c9fSAdrian Lang    if(strpos($_COOKIE['DOKU_PREFS'], $pref) !== false) {
1601554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
160263703ba5SAndreas Gohr        $cnt   = count($parts);
160363703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1604554a8c9fSAdrian Lang            if($parts[$i] == $pref) {
1605554a8c9fSAdrian Lang                return $parts[$i + 1];
1606554a8c9fSAdrian Lang            }
1607554a8c9fSAdrian Lang        }
1608554a8c9fSAdrian Lang    }
1609554a8c9fSAdrian Lang    return $default;
1610554a8c9fSAdrian Lang}
1611554a8c9fSAdrian Lang
1612e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1613