xref: /dokuwiki/inc/common.php (revision 16f15a8172591c8e5725677b192ec836030b424a)
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";
83634d7150SAndreas Gohr    if($print){
84634d7150SAndreas Gohr        echo $ret;
85634d7150SAndreas Gohr    }else{
86634d7150SAndreas Gohr        return $ret;
87634d7150SAndreas Gohr    }
88634d7150SAndreas Gohr}
89634d7150SAndreas Gohr
90634d7150SAndreas Gohr/**
9115fae107Sandi * Return info about the current document as associative
92f3f0262cSandi * array.
9315fae107Sandi *
9415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
95f3f0262cSandi */
96f3f0262cSandifunction pageinfo(){
97f3f0262cSandi    global $ID;
98f3f0262cSandi    global $REV;
997b3a6803SAndreas Gohr    global $RANGE;
100f3f0262cSandi    global $USERINFO;
1017b3a6803SAndreas Gohr    global $lang;
102f3f0262cSandi
1036afe8dcaSchris    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1046afe8dcaSchris    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1056afe8dcaSchris    $info['id'] = $ID;
1066afe8dcaSchris    $info['rev'] = $REV;
1076afe8dcaSchris
108c66972f2SAdrian Lang    // set info about manager/admin status.
109c66972f2SAdrian Lang    $info['isadmin']   = false;
110c66972f2SAdrian Lang    $info['ismanager'] = false;
111c66972f2SAdrian Lang    if(isset($_SERVER['REMOTE_USER'])){
112f3f0262cSandi        $info['userinfo']     = $USERINFO;
113f3f0262cSandi        $info['perm']         = auth_quickaclcheck($ID);
1145b75cd1fSAdrian Lang        $info['subscribed']   = get_info_subscribed();
115ee4c4a1bSAndreas Gohr        $info['client']       = $_SERVER['REMOTE_USER'];
11617ee7f66SAndreas Gohr
117f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN){
118f8cc712eSAndreas Gohr            $info['isadmin']   = true;
119f8cc712eSAndreas Gohr            $info['ismanager'] = true;
120f8cc712eSAndreas Gohr        }elseif(auth_ismanager()){
121f8cc712eSAndreas Gohr            $info['ismanager'] = true;
122f8cc712eSAndreas Gohr        }
123f8cc712eSAndreas Gohr
12417ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
12517ee7f66SAndreas Gohr        if(!$info['userinfo']['name']){
12617ee7f66SAndreas Gohr            $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
12717ee7f66SAndreas Gohr        }
128ee4c4a1bSAndreas Gohr
129f3f0262cSandi    }else{
130f3f0262cSandi        $info['perm']       = auth_aclcheck($ID,'',null);
1311380fc45SAndreas Gohr        $info['subscribed'] = false;
132ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
133f3f0262cSandi    }
134f3f0262cSandi
135f3f0262cSandi    $info['namespace'] = getNS($ID);
136f3f0262cSandi    $info['locked']    = checklock($ID);
13700976812SAndreas Gohr    $info['filepath']  = fullpath(wikiFN($ID));
1382ca9d91cSBen Coburn    $info['exists']    = @file_exists($info['filepath']);
1392ca9d91cSBen Coburn    if($REV){
1402ca9d91cSBen Coburn        //check if current revision was meant
1412ca9d91cSBen Coburn        if($info['exists'] && (@filemtime($info['filepath'])==$REV)){
1422ca9d91cSBen Coburn            $REV = '';
1437b3a6803SAndreas Gohr        }elseif($RANGE){
1447b3a6803SAndreas Gohr            //section editing does not work with old revisions!
1457b3a6803SAndreas Gohr            $REV   = '';
1467b3a6803SAndreas Gohr            $RANGE = '';
1477b3a6803SAndreas Gohr            msg($lang['nosecedit'],0);
1482ca9d91cSBen Coburn        }else{
1492ca9d91cSBen Coburn            //really use old revision
15000976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID,$REV));
151f3f0262cSandi            $info['exists']   = @file_exists($info['filepath']);
152f3f0262cSandi        }
153f3f0262cSandi    }
154c112d578Sandi    $info['rev'] = $REV;
155f3f0262cSandi    if($info['exists']){
156f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
157f3f0262cSandi                ($info['perm'] >= AUTH_EDIT));
158f3f0262cSandi    }else{
159f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
160f3f0262cSandi    }
16150e988b1SAndreas Gohr    $info['editable']  = ($info['writable'] && empty($info['locked']));
162f3f0262cSandi    $info['lastmod']   = @filemtime($info['filepath']);
163f3f0262cSandi
16471726d78SBen Coburn    //load page meta data
16571726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
16671726d78SBen Coburn
167652610a2Sandi    //who's the editor
168652610a2Sandi    if($REV){
16971726d78SBen Coburn        $revinfo = getRevisionInfo($ID, $REV, 1024);
170652610a2Sandi    }else{
171aa27cf05SAndreas Gohr        if (is_array($info['meta']['last_change'])) {
172aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
173aa27cf05SAndreas Gohr        } else {
174cd00a034SBen Coburn            $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
175cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
176cd00a034SBen Coburn            if ($revinfo!==false) {
177cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
178cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
179cd00a034SBen Coburn            }
180cd00a034SBen Coburn        }
181cd00a034SBen Coburn    }
182cd00a034SBen Coburn    //and check for an external edit
183cd00a034SBen Coburn    if($revinfo!==false && $revinfo['date']!=$info['lastmod']){
184cd00a034SBen Coburn        // cached changelog line no longer valid
185cd00a034SBen Coburn        $revinfo = false;
186cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
187cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
188652610a2Sandi    }
189bb4866bdSchris
190652610a2Sandi    $info['ip']     = $revinfo['ip'];
191652610a2Sandi    $info['user']   = $revinfo['user'];
192652610a2Sandi    $info['sum']    = $revinfo['sum'];
19371726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
194ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
19559f257aeSchris
19688f522e9Sandi    if($revinfo['user']){
19788f522e9Sandi        $info['editor'] = $revinfo['user'];
19888f522e9Sandi    }else{
19988f522e9Sandi        $info['editor'] = $revinfo['ip'];
20088f522e9Sandi    }
201652610a2Sandi
202ee4c4a1bSAndreas Gohr    // draft
203ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID,'.draft');
204ee4c4a1bSAndreas Gohr    if(@file_exists($draft)){
205ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))){
206ee4c4a1bSAndreas Gohr            // remove stale draft
207ee4c4a1bSAndreas Gohr            @unlink($draft);
208ee4c4a1bSAndreas Gohr        }else{
209ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
210ee4c4a1bSAndreas Gohr        }
211ee4c4a1bSAndreas Gohr    }
212ee4c4a1bSAndreas Gohr
2131c548ebeSAndreas Gohr    // mobile detection
2141c548ebeSAndreas Gohr    $info['ismobile'] = clientismobile();
2151c548ebeSAndreas Gohr
216f3f0262cSandi    return $info;
217f3f0262cSandi}
218f3f0262cSandi
219f3f0262cSandi/**
2202684e50aSAndreas Gohr * Build an string of URL parameters
2212684e50aSAndreas Gohr *
2222684e50aSAndreas Gohr * @author Andreas Gohr
2232684e50aSAndreas Gohr */
224b174aeaeSchrisfunction buildURLparams($params, $sep='&amp;'){
2252684e50aSAndreas Gohr    $url = '';
2262684e50aSAndreas Gohr    $amp = false;
2272684e50aSAndreas Gohr    foreach($params as $key => $val){
228b174aeaeSchris        if($amp) $url .= $sep;
2292684e50aSAndreas Gohr
23085e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
2313a50618cSgweissbach        $url .= rawurlencode((string)$val);
2322684e50aSAndreas Gohr        $amp = true;
2332684e50aSAndreas Gohr    }
2342684e50aSAndreas Gohr    return $url;
2352684e50aSAndreas Gohr}
2362684e50aSAndreas Gohr
2372684e50aSAndreas Gohr/**
2382684e50aSAndreas Gohr * Build an string of html tag attributes
2392684e50aSAndreas Gohr *
2407bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2417bff22c0SAndreas Gohr *
2422684e50aSAndreas Gohr * @author Andreas Gohr
2432684e50aSAndreas Gohr */
2444b030ce7SAndreas Gohrfunction buildAttributes($params,$skipempty=false){
2452684e50aSAndreas Gohr    $url = '';
2469063ec14SAdrian Lang    $white = false;
2472684e50aSAndreas Gohr    foreach($params as $key => $val){
2487bff22c0SAndreas Gohr        if($key{0} == '_') continue;
249b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
2509063ec14SAdrian Lang        if($white) $url .= ' ';
2517bff22c0SAndreas Gohr
2522684e50aSAndreas Gohr        $url .= $key.'="';
2532684e50aSAndreas Gohr        $url .= htmlspecialchars ($val);
2542684e50aSAndreas Gohr        $url .= '"';
2559063ec14SAdrian Lang        $white = true;
2562684e50aSAndreas Gohr    }
2572684e50aSAndreas Gohr    return $url;
2582684e50aSAndreas Gohr}
2592684e50aSAndreas Gohr
2602684e50aSAndreas Gohr
2612684e50aSAndreas Gohr/**
26215fae107Sandi * This builds the breadcrumb trail and returns it as array
26315fae107Sandi *
26415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
265f3f0262cSandi */
266f3f0262cSandifunction breadcrumbs(){
2678746e727Sandi    // we prepare the breadcrumbs early for quick session closing
2688746e727Sandi    static $crumbs = null;
2698746e727Sandi    if($crumbs != null) return $crumbs;
2708746e727Sandi
271f3f0262cSandi    global $ID;
272f3f0262cSandi    global $ACT;
273f3f0262cSandi    global $conf;
274f3f0262cSandi
275f3f0262cSandi    //first visit?
276c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
277f3f0262cSandi    //we only save on show and existing wiki documents
278a77f5846Sjan    $file = wikiFN($ID);
279a77f5846Sjan    if($ACT != 'show' || !@file_exists($file)){
280e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
281f3f0262cSandi        return $crumbs;
282f3f0262cSandi    }
283a77f5846Sjan
284a77f5846Sjan    // page names
2851a84a0f3SAnika Henke    $name = noNSorNS($ID);
286fe9ec250SChris Smith    if (useHeading('navigation')) {
287a77f5846Sjan        // get page title
28867c15eceSMichael Hamann        $title = p_get_first_heading($ID,METADATA_RENDER_USING_SIMPLE_CACHE);
289a77f5846Sjan        if ($title) {
290a77f5846Sjan            $name = $title;
291a77f5846Sjan        }
292a77f5846Sjan    }
293a77f5846Sjan
294f3f0262cSandi    //remove ID from array
295a77f5846Sjan    if (isset($crumbs[$ID])) {
296a77f5846Sjan        unset($crumbs[$ID]);
297f3f0262cSandi    }
298f3f0262cSandi
299f3f0262cSandi    //add to array
300a77f5846Sjan    $crumbs[$ID] = $name;
301f3f0262cSandi    //reduce size
302f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']){
303f3f0262cSandi        array_shift($crumbs);
304f3f0262cSandi    }
305f3f0262cSandi    //save to session
306e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
307f3f0262cSandi    return $crumbs;
308f3f0262cSandi}
309f3f0262cSandi
310f3f0262cSandi/**
31115fae107Sandi * Filter for page IDs
31215fae107Sandi *
313f3f0262cSandi * This is run on a ID before it is outputted somewhere
314f3f0262cSandi * currently used to replace the colon with something else
315f3f0262cSandi * on Windows systems and to have proper URL encoding
31615fae107Sandi *
31749c713a3Sandi * Urlencoding is ommitted when the second parameter is false
31849c713a3Sandi *
31915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
320f3f0262cSandi */
32149c713a3Sandifunction idfilter($id,$ue=true){
322f3f0262cSandi    global $conf;
323f3f0262cSandi    if ($conf['useslash'] && $conf['userewrite']){
324f3f0262cSandi        $id = strtr($id,':','/');
325f3f0262cSandi    }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
326f3f0262cSandi            $conf['userewrite']) {
327f3f0262cSandi        $id = strtr($id,':',';');
328f3f0262cSandi    }
32949c713a3Sandi    if($ue){
330b6c6979fSAndreas Gohr        $id = rawurlencode($id);
331f3f0262cSandi        $id = str_replace('%3A',':',$id); //keep as colon
332f3f0262cSandi        $id = str_replace('%2F','/',$id); //keep as slash
33349c713a3Sandi    }
334f3f0262cSandi    return $id;
335f3f0262cSandi}
336f3f0262cSandi
337f3f0262cSandi/**
338ed7b5f09Sandi * This builds a link to a wikipage
33915fae107Sandi *
3406c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3416c7843b5Sandi * given in $more
3426c7843b5Sandi *
34315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
344f3f0262cSandi */
345*16f15a81SDominik Eckelmannfunction wl($id='',$urlParameters='',$absolute=false,$separator='&amp;'){
346f3f0262cSandi    global $conf;
347*16f15a81SDominik Eckelmann    if(is_array($urlParameters)){
348*16f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters,$separator);
3496de3759aSAndreas Gohr    }else{
350*16f15a81SDominik Eckelmann        $urlParameters = str_replace(',',$separator,$urlParameters);
3516de3759aSAndreas Gohr    }
352*16f15a81SDominik Eckelmann    if ($id === '') {
353*16f15a81SDominik Eckelmann        $id = $conf['start'];
354*16f15a81SDominik Eckelmann    }
355f3f0262cSandi    $id = idfilter($id);
356*16f15a81SDominik Eckelmann    if($absolute){
357ed7b5f09Sandi        $xlink = DOKU_URL;
358ed7b5f09Sandi    }else{
359ed7b5f09Sandi        $xlink = DOKU_BASE;
360ed7b5f09Sandi    }
361f3f0262cSandi
3626c7843b5Sandi    if($conf['userewrite'] == 2){
3636c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
364*16f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
3656c7843b5Sandi    }elseif($conf['userewrite']){
366f3f0262cSandi        $xlink .= $id;
367*16f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
368bce3726dSAndreas Gohr    }elseif($id){
3696c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
370*16f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
371bce3726dSAndreas Gohr    }else{
372bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
373*16f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
374f3f0262cSandi    }
375f3f0262cSandi
376f3f0262cSandi    return $xlink;
377f3f0262cSandi}
378f3f0262cSandi
379f3f0262cSandi/**
380f5c2808fSBen Coburn * This builds a link to an alternate page format
381f5c2808fSBen Coburn *
382f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
383f5c2808fSBen Coburn *
384f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
385f5c2808fSBen Coburn */
386f5c2808fSBen Coburnfunction exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
387f5c2808fSBen Coburn    global $conf;
388f5c2808fSBen Coburn    if(is_array($more)){
389f5c2808fSBen Coburn        $more = buildURLparams($more,$sep);
390f5c2808fSBen Coburn    }else{
391f5c2808fSBen Coburn        $more = str_replace(',',$sep,$more);
392f5c2808fSBen Coburn    }
393f5c2808fSBen Coburn
394f5c2808fSBen Coburn    $format = rawurlencode($format);
395f5c2808fSBen Coburn    $id = idfilter($id);
396f5c2808fSBen Coburn    if($abs){
397f5c2808fSBen Coburn        $xlink = DOKU_URL;
398f5c2808fSBen Coburn    }else{
399f5c2808fSBen Coburn        $xlink = DOKU_BASE;
400f5c2808fSBen Coburn    }
401f5c2808fSBen Coburn
402f5c2808fSBen Coburn    if($conf['userewrite'] == 2){
403f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
404f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
405f5c2808fSBen Coburn    }elseif($conf['userewrite'] == 1){
406f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
407f5c2808fSBen Coburn        if($more) $xlink .= '?'.$more;
408f5c2808fSBen Coburn    }else{
409f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
410f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
411f5c2808fSBen Coburn    }
412f5c2808fSBen Coburn
413f5c2808fSBen Coburn    return $xlink;
414f5c2808fSBen Coburn}
415f5c2808fSBen Coburn
416f5c2808fSBen Coburn/**
4176de3759aSAndreas Gohr * Build a link to a media file
4186de3759aSAndreas Gohr *
4196de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4208c08db0aSAndreas Gohr *
4218c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4228c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4238c08db0aSAndreas Gohr *
4248c08db0aSAndreas Gohr * @param string  $id     - the media file id or URL
4258c08db0aSAndreas Gohr * @param mixed   $more   - string or array with additional parameters
4268c08db0aSAndreas Gohr * @param boolean $direct - link to detail page if false
4278c08db0aSAndreas Gohr * @param string  $sep    - URL parameter separator
4288c08db0aSAndreas Gohr * @param boolean $abs    - Create an absolute URL
4296de3759aSAndreas Gohr */
43055b2b31bSAndreas Gohrfunction ml($id='',$more='',$direct=true,$sep='&amp;',$abs=false){
4316de3759aSAndreas Gohr    global $conf;
4326de3759aSAndreas Gohr    if(is_array($more)){
4338c08db0aSAndreas Gohr        // strip defaults for shorter URLs
4348c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
4358c08db0aSAndreas Gohr        if(!$more['w']) unset($more['w']);
4368c08db0aSAndreas Gohr        if(!$more['h']) unset($more['h']);
4378c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
438b174aeaeSchris        $more = buildURLparams($more,$sep);
4396de3759aSAndreas Gohr    }else{
4408c08db0aSAndreas Gohr        $more = str_replace('cache=cache','',$more); //skip default
4418c08db0aSAndreas Gohr        $more = str_replace(',,',',',$more);
442b174aeaeSchris        $more = str_replace(',',$sep,$more);
4436de3759aSAndreas Gohr    }
4446de3759aSAndreas Gohr
44555b2b31bSAndreas Gohr    if($abs){
44655b2b31bSAndreas Gohr        $xlink = DOKU_URL;
44755b2b31bSAndreas Gohr    }else{
4486de3759aSAndreas Gohr        $xlink = DOKU_BASE;
44955b2b31bSAndreas Gohr    }
4506de3759aSAndreas Gohr
4516de3759aSAndreas Gohr    // external URLs are always direct without rewriting
4526de3759aSAndreas Gohr    if(preg_match('#^(https?|ftp)://#i',$id)){
4536de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
45469d17d94SAndreas Gohr        // add hash:
45569d17d94SAndreas Gohr        $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id),0,6);
4566de3759aSAndreas Gohr        if($more){
45769d17d94SAndreas Gohr            $xlink .= $sep.$more;
458b174aeaeSchris            $xlink .= $sep.'media='.rawurlencode($id);
4596de3759aSAndreas Gohr        }else{
46069d17d94SAndreas Gohr            $xlink .= $sep.'media='.rawurlencode($id);
4616de3759aSAndreas Gohr        }
4626de3759aSAndreas Gohr        return $xlink;
4636de3759aSAndreas Gohr    }
4646de3759aSAndreas Gohr
4656de3759aSAndreas Gohr    $id = idfilter($id);
4666de3759aSAndreas Gohr
4676de3759aSAndreas Gohr    // decide on scriptname
4686de3759aSAndreas Gohr    if($direct){
4696de3759aSAndreas Gohr        if($conf['userewrite'] == 1){
4706de3759aSAndreas Gohr            $script = '_media';
4716de3759aSAndreas Gohr        }else{
4726de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
4736de3759aSAndreas Gohr        }
4746de3759aSAndreas Gohr    }else{
4756de3759aSAndreas Gohr        if($conf['userewrite'] == 1){
4766de3759aSAndreas Gohr            $script = '_detail';
4776de3759aSAndreas Gohr        }else{
4786de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
4796de3759aSAndreas Gohr        }
4806de3759aSAndreas Gohr    }
4816de3759aSAndreas Gohr
4826de3759aSAndreas Gohr    // build URL based on rewrite mode
4836de3759aSAndreas Gohr    if($conf['userewrite']){
4846de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
4856de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
4866de3759aSAndreas Gohr    }else{
4876de3759aSAndreas Gohr        if($more){
488a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
489b174aeaeSchris            $xlink .= $sep.'media='.$id;
4906de3759aSAndreas Gohr        }else{
491a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
4926de3759aSAndreas Gohr        }
4936de3759aSAndreas Gohr    }
4946de3759aSAndreas Gohr
4956de3759aSAndreas Gohr    return $xlink;
4966de3759aSAndreas Gohr}
4976de3759aSAndreas Gohr
4986de3759aSAndreas Gohr
4996de3759aSAndreas Gohr
5006de3759aSAndreas Gohr/**
501f3f0262cSandi * Just builds a link to a script
50215fae107Sandi *
503ed7b5f09Sandi * @todo   maybe obsolete
50415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
505f3f0262cSandi */
506f3f0262cSandifunction script($script='doku.php'){
507ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
508f3f0262cSandi}
509f3f0262cSandi
510f3f0262cSandi/**
51115fae107Sandi * Spamcheck against wordlist
51215fae107Sandi *
513f3f0262cSandi * Checks the wikitext against a list of blocked expressions
514f3f0262cSandi * returns true if the text contains any bad words
51515fae107Sandi *
516e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
517e403cc58SMichael Klier *
518e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
519e403cc58SMichael Klier *  and gain information about the user who was blocked.
520e403cc58SMichael Klier *
521e403cc58SMichael Klier *  Event data:
522e403cc58SMichael Klier *    data['matches']  - array of matches
523e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
524e403cc58SMichael Klier *      [ip]           - ip address
525e403cc58SMichael Klier *      [user]         - username (if logged in)
526e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
527e403cc58SMichael Klier *      [name]         - real name (if logged in)
528e403cc58SMichael Klier *
52915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5306dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
5316dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
5326dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
533f3f0262cSandi */
5346dffa0e0SAndreas Gohrfunction checkwordblock($text=''){
535f3f0262cSandi    global $TEXT;
5366dffa0e0SAndreas Gohr    global $PRE;
5376dffa0e0SAndreas Gohr    global $SUF;
538f3f0262cSandi    global $conf;
539e403cc58SMichael Klier    global $INFO;
540f3f0262cSandi
541f3f0262cSandi    if(!$conf['usewordblock']) return false;
542f3f0262cSandi
5436dffa0e0SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF";
5446dffa0e0SAndreas Gohr
545041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
5466dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text);
547041d1964SAndreas Gohr
548b9ac8716Schris    $wordblocks = getWordblocks();
5493e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
5503e2965d7Sandi    if(version_compare(phpversion(),'4.3.0','<')){
5513e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
5523e2965d7Sandi        // backreferences are used - the maximum is 99
5533e2965d7Sandi        // this is very bad performancewise and may even be too high still
5543e2965d7Sandi        $chunksize = 40;
5553e2965d7Sandi    }else{
556a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
5573e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
558a51d08efSAndreas Gohr        $chunksize = 200;
5593e2965d7Sandi    }
560b9ac8716Schris    while($blocks = array_splice($wordblocks,0,$chunksize)){
561f3f0262cSandi        $re = array();
56249eb6e38SAndreas Gohr        // build regexp from blocks
563f3f0262cSandi        foreach($blocks as $block){
564f3f0262cSandi            $block = preg_replace('/#.*$/','',$block);
565f3f0262cSandi            $block = trim($block);
566f3f0262cSandi            if(empty($block)) continue;
567f3f0262cSandi            $re[]  = $block;
568f3f0262cSandi        }
569e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
570e403cc58SMichael Klier            // prepare event data
571e403cc58SMichael Klier            $data['matches'] = $matches;
572e403cc58SMichael Klier            $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
573e403cc58SMichael Klier            if($_SERVER['REMOTE_USER']) {
574e403cc58SMichael Klier                $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
575e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
576e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
577e403cc58SMichael Klier            }
578e403cc58SMichael Klier            $callback = create_function('', 'return true;');
579e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
580b9ac8716Schris        }
581703f6fdeSandi    }
582f3f0262cSandi    return false;
583f3f0262cSandi}
584f3f0262cSandi
585f3f0262cSandi/**
58615fae107Sandi * Return the IP of the client
58715fae107Sandi *
5886d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
58915fae107Sandi *
5906d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
5916d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
5926d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
5936d8affe6SAndreas Gohr * headers
5946d8affe6SAndreas Gohr *
5956d8affe6SAndreas Gohr * @param  boolean $single If set only a single IP is returned
59615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
597f3f0262cSandi */
5986d8affe6SAndreas Gohrfunction clientIP($single=false){
5996d8affe6SAndreas Gohr    $ip = array();
6006d8affe6SAndreas Gohr    $ip[] = $_SERVER['REMOTE_ADDR'];
601bb4866bdSchris    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
6025cbeffbfSMarcel Pennewiß        $ip = array_merge($ip,explode(',',str_replace(' ','',$_SERVER['HTTP_X_FORWARDED_FOR'])));
603bb4866bdSchris    if(!empty($_SERVER['HTTP_X_REAL_IP']))
6045cbeffbfSMarcel Pennewiß        $ip = array_merge($ip,explode(',',str_replace(' ','',$_SERVER['HTTP_X_REAL_IP'])));
6056d8affe6SAndreas Gohr
606dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
607dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
608dc14c6d1SGuy Brand    $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
609dc14c6d1SGuy Brand    $hex_digit = '[A-Fa-f0-9]';
610dc14c6d1SGuy Brand    $h16 = "{$hex_digit}{1,4}";
611dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
612dc14c6d1SGuy Brand    $ls32 = "(?:$h16:$h16|$IPv4Address)";
613dc14c6d1SGuy Brand    $IPv6Address =
614dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
615dc14c6d1SGuy Brand        "(?:$h16:){6}$ls32" .
616dc14c6d1SGuy Brand        "|::(?:$h16:){5}$ls32" .
617dc14c6d1SGuy Brand        "|(?:$h16)?::(?:$h16:){4}$ls32" .
618dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
619dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
620dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
621dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
622dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,5}$h16)?::$h16" .
623dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,6}$h16)?::" .
624dc14c6d1SGuy Brand        ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
625dc14c6d1SGuy Brand
6266d8affe6SAndreas Gohr    // remove any non-IP stuff
6276d8affe6SAndreas Gohr    $cnt = count($ip);
6284ff28443Schris    $match = array();
6296d8affe6SAndreas Gohr    for($i=0; $i<$cnt; $i++){
630dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
6314ff28443Schris            $ip[$i] = $match[0];
6324ff28443Schris        } else {
6334ff28443Schris            $ip[$i] = '';
6344ff28443Schris        }
6356d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
636f3f0262cSandi    }
6376d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
6386d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6396d8affe6SAndreas Gohr
6406d8affe6SAndreas Gohr    if(!$single) return join(',',$ip);
6416d8affe6SAndreas Gohr
6426d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
6436d8affe6SAndreas Gohr    $ip = array_reverse($ip);
6446d8affe6SAndreas Gohr    foreach($ip as $i){
6452343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
6466d8affe6SAndreas Gohr            continue;
6476d8affe6SAndreas Gohr        }else{
6486d8affe6SAndreas Gohr            return $i;
6496d8affe6SAndreas Gohr        }
6506d8affe6SAndreas Gohr    }
6516d8affe6SAndreas Gohr    // still here? just use the first (last) address
6526d8affe6SAndreas Gohr    return $ip[0];
653f3f0262cSandi}
654f3f0262cSandi
655f3f0262cSandi/**
6561c548ebeSAndreas Gohr * Check if the browser is on a mobile device
6571c548ebeSAndreas Gohr *
6581c548ebeSAndreas Gohr * Adapted from the example code at url below
6591c548ebeSAndreas Gohr *
6601c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
6611c548ebeSAndreas Gohr */
6621c548ebeSAndreas Gohrfunction clientismobile(){
6631c548ebeSAndreas Gohr
6641c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
6651c548ebeSAndreas Gohr
6661c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
6671c548ebeSAndreas Gohr
6681c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
6691c548ebeSAndreas Gohr
6701c548ebeSAndreas 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';
6711c548ebeSAndreas Gohr
6721c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
6731c548ebeSAndreas Gohr
6741c548ebeSAndreas Gohr    return false;
6751c548ebeSAndreas Gohr}
6761c548ebeSAndreas Gohr
6771c548ebeSAndreas Gohr
6781c548ebeSAndreas Gohr/**
67963211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
68063211f61SGlen Harris *
68122ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
68222ef1e32SAndreas Gohr *
68363211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
68463211f61SGlen Harris * @returns a comma separated list of hostnames
68563211f61SGlen Harris */
68663211f61SGlen Harrisfunction gethostsbyaddrs($ips){
68722ef1e32SAndreas Gohr    global $conf;
68822ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
68922ef1e32SAndreas Gohr
69063211f61SGlen Harris    $hosts = array();
69163211f61SGlen Harris    $ips = explode(',',$ips);
692551a720fSMichael Klier
693551a720fSMichael Klier    if(is_array($ips)) {
6943886270dSAndreas Gohr        foreach($ips as $ip){
695551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
69663211f61SGlen Harris        }
697551a720fSMichael Klier        return join(',',$hosts);
698551a720fSMichael Klier    } else {
699551a720fSMichael Klier        return gethostbyaddr(trim($ips));
700551a720fSMichael Klier    }
70163211f61SGlen Harris}
70263211f61SGlen Harris
70363211f61SGlen Harris/**
70415fae107Sandi * Checks if a given page is currently locked.
70515fae107Sandi *
706f3f0262cSandi * removes stale lockfiles
70715fae107Sandi *
70815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
709f3f0262cSandi */
710f3f0262cSandifunction checklock($id){
711f3f0262cSandi    global $conf;
712c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
713f3f0262cSandi
714f3f0262cSandi    //no lockfile
715f3f0262cSandi    if(!@file_exists($lock)) return false;
716f3f0262cSandi
717f3f0262cSandi    //lockfile expired
718f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']){
719d8186216SBen Coburn        @unlink($lock);
720f3f0262cSandi        return false;
721f3f0262cSandi    }
722f3f0262cSandi
723f3f0262cSandi    //my own lock
72485fef7e2SAndreas Gohr    list($ip,$session) = explode("\n",io_readFile($lock));
72585fef7e2SAndreas Gohr    if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()){
726f3f0262cSandi        return false;
727f3f0262cSandi    }
728f3f0262cSandi
729f3f0262cSandi    return $ip;
730f3f0262cSandi}
731f3f0262cSandi
732f3f0262cSandi/**
73315fae107Sandi * Lock a page for editing
73415fae107Sandi *
73515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
736f3f0262cSandi */
737f3f0262cSandifunction lock($id){
738544ed901SDaniel Calviño Sánchez    global $conf;
739544ed901SDaniel Calviño Sánchez
740544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0){
741544ed901SDaniel Calviño Sánchez        return;
742544ed901SDaniel Calviño Sánchez    }
743544ed901SDaniel Calviño Sánchez
744c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
745f3f0262cSandi    if($_SERVER['REMOTE_USER']){
746f3f0262cSandi        io_saveFile($lock,$_SERVER['REMOTE_USER']);
747f3f0262cSandi    }else{
74885fef7e2SAndreas Gohr        io_saveFile($lock,clientIP()."\n".session_id());
749f3f0262cSandi    }
750f3f0262cSandi}
751f3f0262cSandi
752f3f0262cSandi/**
75315fae107Sandi * Unlock a page if it was locked by the user
754f3f0262cSandi *
75515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
75615fae107Sandi * @return bool true if a lock was removed
757f3f0262cSandi */
758f3f0262cSandifunction unlock($id){
759c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
760f3f0262cSandi    if(@file_exists($lock)){
76185fef7e2SAndreas Gohr        list($ip,$session) = explode("\n",io_readFile($lock));
76285fef7e2SAndreas Gohr        if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()){
763f3f0262cSandi            @unlink($lock);
764f3f0262cSandi            return true;
765f3f0262cSandi        }
766f3f0262cSandi    }
767f3f0262cSandi    return false;
768f3f0262cSandi}
769f3f0262cSandi
770f3f0262cSandi/**
771f3f0262cSandi * convert line ending to unix format
772f3f0262cSandi *
77315fae107Sandi * @see    formText() for 2crlf conversion
77415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
775f3f0262cSandi */
776f3f0262cSandifunction cleanText($text){
777f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
778f3f0262cSandi    return $text;
779f3f0262cSandi}
780f3f0262cSandi
781f3f0262cSandi/**
782f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
783f3f0262cSandi * It also converts line endings to Windows format which is
784f3f0262cSandi * pseudo standard for webforms.
785f3f0262cSandi *
78615fae107Sandi * @see    cleanText() for 2unix conversion
78715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
788f3f0262cSandi */
789f3f0262cSandifunction formText($text){
7905b7d45a5SAndreas Gohr    $text = str_replace("\012","\015\012",$text);
791f3f0262cSandi    return htmlspecialchars($text);
792f3f0262cSandi}
793f3f0262cSandi
794f3f0262cSandi/**
79515fae107Sandi * Returns the specified local text in raw format
79615fae107Sandi *
79715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
798f3f0262cSandi */
7992adaf2b8SAndreas Gohrfunction rawLocale($id,$ext='txt'){
8002adaf2b8SAndreas Gohr    return io_readFile(localeFN($id,$ext));
801f3f0262cSandi}
802f3f0262cSandi
803f3f0262cSandi/**
804f3f0262cSandi * Returns the raw WikiText
80515fae107Sandi *
80615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
807f3f0262cSandi */
808f3f0262cSandifunction rawWiki($id,$rev=''){
809cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
810f3f0262cSandi}
811f3f0262cSandi
812f3f0262cSandi/**
8137146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
8147146cee2SAndreas Gohr *
8157b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
8167146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8177146cee2SAndreas Gohr */
818fe17917eSAdrian Langfunction pageTemplate($id){
819a15ce62dSEsther Brunner    global $conf;
820e29549feSAndreas Gohr
821fe17917eSAdrian Lang    if (is_array($id)) $id = $id[0];
822e29549feSAndreas Gohr
8237b84afa2SAndreas Gohr    // prepare initial event data
8247b84afa2SAndreas Gohr    $data = array(
8257b84afa2SAndreas Gohr        'id'        => $id,   // the id of the page to be created
8267b84afa2SAndreas Gohr        'tpl'       => '',    // the text used as template
8277b84afa2SAndreas Gohr        'tplfile'   => '',    // the file above text was/should be loaded from
8287b84afa2SAndreas Gohr        'doreplace' => true   // should wildcard replacements be done on the text?
8297b84afa2SAndreas Gohr    );
8307b84afa2SAndreas Gohr
8317b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD',$data);
8327b84afa2SAndreas Gohr    if($evt->advise_before(true)){
8337b84afa2SAndreas Gohr        // the before event might have loaded the content already
8347b84afa2SAndreas Gohr        if(empty($data['tpl'])){
8357b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
8367b84afa2SAndreas Gohr            if(empty($data['tplfile'])){
837fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
838fe17917eSAdrian Lang                $tpl = '';
839e29549feSAndreas Gohr                if(@file_exists($path.'/_template.txt')){
8407b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
841e29549feSAndreas Gohr                }else{
842e29549feSAndreas Gohr                    // search upper namespaces for templates
843e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'],'/'));
844e29549feSAndreas Gohr                    while (strlen($path) >= $len){
845e29549feSAndreas Gohr                        if(@file_exists($path.'/__template.txt')){
8467b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
847e29549feSAndreas Gohr                            break;
848e29549feSAndreas Gohr                        }
849e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
850e29549feSAndreas Gohr                    }
851e29549feSAndreas Gohr                }
8527b84afa2SAndreas Gohr            }
8537b84afa2SAndreas Gohr            // load the content
8543d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
8557b84afa2SAndreas Gohr        }
856a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
8577b84afa2SAndreas Gohr    }
8587b84afa2SAndreas Gohr    $evt->advise_after();
8597b84afa2SAndreas Gohr    unset($evt);
8607b84afa2SAndreas Gohr
861fe17917eSAdrian Lang    return $data['tpl'];
8622b1223ecSAdrian Lang}
8632b1223ecSAdrian Lang
8642b1223ecSAdrian Lang/**
8652b1223ecSAdrian Lang * Performs common page template replacements
8667b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
8672b1223ecSAdrian Lang *
8682b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
8692b1223ecSAdrian Lang */
870d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
871fe17917eSAdrian Lang    extract($data);
872fe17917eSAdrian Lang
873b856f7dfSAdrian Lang    global $USERINFO;
874bce53b1fSAdrian Lang    global $conf;
875e29549feSAndreas Gohr
876e29549feSAndreas Gohr    // replace placeholders
87726ece5a7SAndreas Gohr    $file = noNS($id);
87837c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
87926ece5a7SAndreas Gohr
88026ece5a7SAndreas Gohr    $tpl = str_replace(array(
88126ece5a7SAndreas Gohr                '@ID@',
88226ece5a7SAndreas Gohr                '@NS@',
88326ece5a7SAndreas Gohr                '@FILE@',
88426ece5a7SAndreas Gohr                '@!FILE@',
88526ece5a7SAndreas Gohr                '@!FILE!@',
88626ece5a7SAndreas Gohr                '@PAGE@',
88726ece5a7SAndreas Gohr                '@!PAGE@',
88826ece5a7SAndreas Gohr                '@!!PAGE@',
88926ece5a7SAndreas Gohr                '@!PAGE!@',
89026ece5a7SAndreas Gohr                '@USER@',
89126ece5a7SAndreas Gohr                '@NAME@',
89226ece5a7SAndreas Gohr                '@MAIL@',
89326ece5a7SAndreas Gohr                '@DATE@',
89426ece5a7SAndreas Gohr                ),
89526ece5a7SAndreas Gohr            array(
89626ece5a7SAndreas Gohr                $id,
89726ece5a7SAndreas Gohr                getNS($id),
89826ece5a7SAndreas Gohr                $file,
89926ece5a7SAndreas Gohr                utf8_ucfirst($file),
90026ece5a7SAndreas Gohr                utf8_strtoupper($file),
90126ece5a7SAndreas Gohr                $page,
90226ece5a7SAndreas Gohr                utf8_ucfirst($page),
90326ece5a7SAndreas Gohr                utf8_ucwords($page),
90426ece5a7SAndreas Gohr                utf8_strtoupper($page),
90526ece5a7SAndreas Gohr                $_SERVER['REMOTE_USER'],
906b856f7dfSAdrian Lang                $USERINFO['name'],
907b856f7dfSAdrian Lang                $USERINFO['mail'],
90826ece5a7SAndreas Gohr                $conf['dformat'],
90926ece5a7SAndreas Gohr                ), $tpl);
91026ece5a7SAndreas Gohr
9117d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
9127d644fc8SAndreas Gohr    $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
913d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
914a15ce62dSEsther Brunner    return $tpl;
9157146cee2SAndreas Gohr}
9167146cee2SAndreas Gohr
9177146cee2SAndreas Gohr/**
91815fae107Sandi * Returns the raw Wiki Text in three slices.
91915fae107Sandi *
92015fae107Sandi * The range parameter needs to have the form "from-to"
92115cfe303Sandi * and gives the range of the section in bytes - no
92215cfe303Sandi * UTF-8 awareness is needed.
923f3f0262cSandi * The returned order is prefix, section and suffix.
92415fae107Sandi *
92515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
926f3f0262cSandi */
927f3f0262cSandifunction rawWikiSlices($range,$id,$rev=''){
928cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
929f3f0262cSandi
93080fcb268SAdrian Lang    // Parse range
93180fcb268SAdrian Lang    list($from,$to) = explode('-',$range,2);
93280fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
93380fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
93480fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
93580fcb268SAdrian Lang
93680fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
93780fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to-$from);
93815cfe303Sandi    $slices[2] = substr($text, $to);
939f3f0262cSandi    return $slices;
940f3f0262cSandi}
941f3f0262cSandi
942f3f0262cSandi/**
94315fae107Sandi * Joins wiki text slices
94415fae107Sandi *
94580fcb268SAdrian Lang * function to join the text slices.
946f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
947f3f0262cSandi * lines between sections if needed (used on saving).
94815fae107Sandi *
94915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
950f3f0262cSandi */
951f3f0262cSandifunction con($pre,$text,$suf,$pretty=false){
952f3f0262cSandi    if($pretty){
95380fcb268SAdrian Lang        if ($pre !== '' && substr($pre, -1) !== "\n" &&
95480fcb268SAdrian Lang            substr($text, 0, 1) !== "\n") {
95580fcb268SAdrian Lang            $pre .= "\n";
95680fcb268SAdrian Lang        }
95780fcb268SAdrian Lang        if ($suf !== '' && substr($text, -1) !== "\n" &&
95880fcb268SAdrian Lang            substr($suf, 0, 1) !== "\n") {
95980fcb268SAdrian Lang            $text .= "\n";
96080fcb268SAdrian Lang        }
961f3f0262cSandi    }
962f3f0262cSandi
963f3f0262cSandi    return $pre.$text.$suf;
964f3f0262cSandi}
965f3f0262cSandi
966f3f0262cSandi/**
967a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
968a701424fSBen Coburn * Also directs changelog and attic updates.
96915fae107Sandi *
97015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
97171726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
972f3f0262cSandi */
973b6912aeaSAndreas Gohrfunction saveWikiText($id,$text,$summary,$minor=false){
974a701424fSBen Coburn    /* Note to developers:
975a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
976a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
977a701424fSBen Coburn       after any changes. External edits change the wiki page
978a701424fSBen Coburn       directly without using php or dokuwiki.
979a701424fSBen Coburn     */
980f3f0262cSandi    global $conf;
981f3f0262cSandi    global $lang;
98271726d78SBen Coburn    global $REV;
983f3f0262cSandi    // ignore if no changes were made
984f3f0262cSandi    if($text == rawWiki($id,'')){
985f3f0262cSandi        return;
986f3f0262cSandi    }
987f3f0262cSandi
988f3f0262cSandi    $file = wikiFN($id);
989a701424fSBen Coburn    $old = @filemtime($file); // from page
990407e65b9SAndreas Gohr    $wasRemoved = (trim($text) == ''); // check for empty or whitespace only
991d8186216SBen Coburn    $wasCreated = !@file_exists($file);
99271726d78SBen Coburn    $wasReverted = ($REV==true);
993e45b34cdSBen Coburn    $newRev = false;
994a701424fSBen Coburn    $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
995a701424fSBen Coburn    $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
996a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
99746844156SBen Coburn        // add old revision to the attic if missing
99846844156SBen Coburn        saveOldRevision($id);
99946844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1000a701424fSBen Coburn        if ($old>$oldRev) {
1001ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
100246844156SBen Coburn            // remove soon to be stale instructions
100346844156SBen Coburn            $cache = new cache_instructions($id, $file);
100446844156SBen Coburn            $cache->removeCache();
100546844156SBen Coburn        }
100646844156SBen Coburn    }
1007f3f0262cSandi
100871726d78SBen Coburn    if ($wasRemoved){
100930725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
101030725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
101130725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1012e45b34cdSBen Coburn        // pre-save deleted revision
1013e45b34cdSBen Coburn        @touch($file);
101446844156SBen Coburn        clearstatcache();
1015e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1016e1f3d9e1SEsther Brunner        // remove empty file
1017f3f0262cSandi        @unlink($file);
1018c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1019c5f92742SMichael Hamann        // purge non-persistant meta data
10203d1f9ec3SMichael Klier        p_purge_metadata($id);
1021f3f0262cSandi        $del = true;
10223ce054b3Sandi        // autoset summary on deletion
10233ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
102453d6ccfeSandi        // remove empty namespaces
1025cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1026cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1027f3f0262cSandi    }else{
1028cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1029cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
103046844156SBen Coburn        // pre-save the revision, to keep the attic in sync
103146844156SBen Coburn        $newRev = saveOldRevision($id);
1032f3f0262cSandi        $del = false;
1033f3f0262cSandi    }
1034f3f0262cSandi
103571726d78SBen Coburn    // select changelog line type
103671726d78SBen Coburn    $extra = '';
1037ebf1501fSBen Coburn    $type = DOKU_CHANGE_TYPE_EDIT;
103871726d78SBen Coburn    if ($wasReverted) {
1039ebf1501fSBen Coburn        $type = DOKU_CHANGE_TYPE_REVERT;
104071726d78SBen Coburn        $extra = $REV;
104171726d78SBen Coburn    }
1042ebf1501fSBen Coburn    else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
1043ebf1501fSBen Coburn    else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
1044ebf1501fSBen Coburn    else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
104571726d78SBen Coburn
1046e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
104726a0801fSAndreas Gohr    // send notify mails
104890033e9dSAndreas Gohr    notify($id,'admin',$old,$summary,$minor);
104990033e9dSAndreas Gohr    notify($id,'subscribers',$old,$summary,$minor);
1050f3f0262cSandi
1051ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
105298407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile',time());
10532eccbdaaSGina Haeussge
10542eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1055fe9ec250SChris Smith    if(useHeading('content')){
10562eccbdaaSGina Haeussge        $pages = ft_backlinks($id);
10572eccbdaaSGina Haeussge        foreach ($pages as $page) {
10582eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
10592eccbdaaSGina Haeussge            $cache->removeCache();
10602eccbdaaSGina Haeussge        }
10612eccbdaaSGina Haeussge    }
1062f3f0262cSandi}
1063f3f0262cSandi
1064f3f0262cSandi/**
1065f3f0262cSandi * moves the current version to the attic and returns its
1066f3f0262cSandi * revision date
106715fae107Sandi *
106815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1069f3f0262cSandi */
1070f3f0262cSandifunction saveOldRevision($id){
1071f3f0262cSandi    global $conf;
1072f3f0262cSandi    $oldf = wikiFN($id);
1073f3f0262cSandi    if(!@file_exists($oldf)) return '';
1074f3f0262cSandi    $date = filemtime($oldf);
1075f3f0262cSandi    $newf = wikiFN($id,$date);
1076cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1077f3f0262cSandi    return $date;
1078f3f0262cSandi}
1079f3f0262cSandi
1080f3f0262cSandi/**
1081fde10de4SAdrian Lang * Sends a notify mail on page change or registration
108226a0801fSAndreas Gohr *
108326a0801fSAndreas Gohr * @param  string  $id       The changed page
1084fde10de4SAdrian Lang * @param  string  $who      Who to notify (admin|subscribers|register)
108526a0801fSAndreas Gohr * @param  int     $rev      Old page revision
108626a0801fSAndreas Gohr * @param  string  $summary  What changed
108790033e9dSAndreas Gohr * @param  boolean $minor    Is this a minor edit?
108802a498e7Schris * @param  array   $replace  Additional string substitutions, @KEY@ to be replaced by value
108915fae107Sandi *
109015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1091f3f0262cSandi */
109202a498e7Schrisfunction notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1093f3f0262cSandi    global $lang;
1094f3f0262cSandi    global $conf;
109530d7d718SMike Frysinger    global $INFO;
109647a906eaSAndreas Gohr    global $DIFF_INLINESTYLES;
1097b158d625SSteven Danz
10986df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
109926a0801fSAndreas Gohr    if($who == 'admin'){
110026a0801fSAndreas Gohr        if(empty($conf['notify'])) return; //notify enabled?
1101f3f0262cSandi        $text = rawLocale('mailtext');
110226a0801fSAndreas Gohr        $to   = $conf['notify'];
110326a0801fSAndreas Gohr        $bcc  = '';
110426a0801fSAndreas Gohr    }elseif($who == 'subscribers'){
110526a0801fSAndreas Gohr        if(!$conf['subscribers']) return; //subscribers enabled?
110690033e9dSAndreas Gohr        if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
11078881fcc9SAdrian Lang        $data = array('id' => $id, 'addresslist' => '', 'self' => false);
11088881fcc9SAdrian Lang        trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data,
11098881fcc9SAdrian Lang                      'subscription_addresslist');
11108881fcc9SAdrian Lang        $bcc = $data['addresslist'];
111126a0801fSAndreas Gohr        if(empty($bcc)) return;
111226a0801fSAndreas Gohr        $to   = '';
11135b75cd1fSAdrian Lang        $text = rawLocale('subscr_single');
1114a06e4bdbSSebastian Harl    }elseif($who == 'register'){
1115a06e4bdbSSebastian Harl        if(empty($conf['registernotify'])) return;
1116a06e4bdbSSebastian Harl        $text = rawLocale('registermail');
1117a06e4bdbSSebastian Harl        $to   = $conf['registernotify'];
1118a06e4bdbSSebastian Harl        $bcc  = '';
111926a0801fSAndreas Gohr    }else{
112026a0801fSAndreas Gohr        return; //just to be safe
112126a0801fSAndreas Gohr    }
112226a0801fSAndreas Gohr
11236df843eeSAndreas Gohr    // prepare replacements (keys not set in hrep will be taken from trep)
11246df843eeSAndreas Gohr    $trep = array(
11256df843eeSAndreas Gohr        'NEWPAGE' => wl($id,'',true,'&'),
11266df843eeSAndreas Gohr        'PAGE'    => $id,
11276df843eeSAndreas Gohr        'SUMMARY' => $summary
11286df843eeSAndreas Gohr    );
11296df843eeSAndreas Gohr    $trep = array_merge($trep,$replace);
11306df843eeSAndreas Gohr    $hrep = array();
1131f3f0262cSandi
11326df843eeSAndreas Gohr    // prepare content
1133a06e4bdbSSebastian Harl    if($who == 'register'){
1134a06e4bdbSSebastian Harl        $subject         = $lang['mail_new_user'].' '.$summary;
1135a06e4bdbSSebastian Harl    }elseif($rev){
1136f3f0262cSandi        $subject         = $lang['mail_changed'].' '.$id;
11376df843eeSAndreas Gohr        $trep['OLDPAGE'] = wl($id,"rev=$rev",true,'&');
11384b7f9e70STom N Harris        $df              = new Diff(explode("\n",rawWiki($id,$rev)),
11394b7f9e70STom N Harris                                    explode("\n",rawWiki($id)));
1140f3f0262cSandi        $dformat         = new UnifiedDiffFormatter();
11416df843eeSAndreas Gohr        $tdiff           = $dformat->format($df);
114247a906eaSAndreas Gohr
114347a906eaSAndreas Gohr        $DIFF_INLINESTYLES = true;
11446df843eeSAndreas Gohr        $dformat         = new InlineDiffFormatter();
11456df843eeSAndreas Gohr        $hdiff           = $dformat->format($df);
114604058413SAndreas Gohr        $hdiff           = '<table>'.$hdiff.'</table>';
114747a906eaSAndreas Gohr        $DIFF_INLINESTYLES = false;
1148f3f0262cSandi    }else{
1149f3f0262cSandi        $subject         = $lang['mail_newpage'].' '.$id;
11506df843eeSAndreas Gohr        $trep['OLDPAGE'] = '---';
11516df843eeSAndreas Gohr        $tdiff           = rawWiki($id);
11526df843eeSAndreas Gohr        $hdiff           = nl2br(hsc($tdiff));
1153f3f0262cSandi    }
11546df843eeSAndreas Gohr    $trep['DIFF'] = $tdiff;
11556df843eeSAndreas Gohr    $hrep['DIFF'] = $hdiff;
11566df843eeSAndreas Gohr
11576df843eeSAndreas Gohr    // send mail
11586df843eeSAndreas Gohr    $mail = new Mailer();
11596df843eeSAndreas Gohr    $mail->to($to);
11606df843eeSAndreas Gohr    $mail->bcc($bcc);
11616df843eeSAndreas Gohr    $mail->subject($subject);
1162b796e32eSAndreas Gohr    $mail->setBody($text,$trep,$hrep);
11639f3eca0bSAndreas Gohr    if($who == 'subscribers'){
11649f3eca0bSAndreas Gohr        $mail->setHeader(
11659f3eca0bSAndreas Gohr            'List-Unsubscribe',
11669f3eca0bSAndreas Gohr            '<'.wl($id,array('do'=>'subscribe'),true,'&').'>',
11679f3eca0bSAndreas Gohr            false
11689f3eca0bSAndreas Gohr        );
11699f3eca0bSAndreas Gohr    }
11706df843eeSAndreas Gohr    return $mail->send();
1171f3f0262cSandi}
1172f3f0262cSandi
117315fae107Sandi/**
117471f7bde7SAndreas Gohr * extracts the query from a search engine referrer
117515fae107Sandi *
117615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
117771f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1178f3f0262cSandi */
1179f3f0262cSandifunction getGoogleQuery(){
1180c66972f2SAdrian Lang    if (!isset($_SERVER['HTTP_REFERER'])) {
1181c66972f2SAdrian Lang        return '';
1182c66972f2SAdrian Lang    }
1183f3f0262cSandi    $url = parse_url($_SERVER['HTTP_REFERER']);
1184f3f0262cSandi
1185f3f0262cSandi    $query = array();
1186e4d8a516SKazutaka Miyasaka
1187e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1188e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1189e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1190f3f0262cSandi    parse_str($url['query'],$query);
1191e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1192e4d8a516SKazutaka Miyasaka
1193c66972f2SAdrian Lang    $q = '';
119471f7bde7SAndreas Gohr    if(isset($query['q']))
1195f93b3b50SAndreas Gohr        $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
119671f7bde7SAndreas Gohr    elseif(isset($query['p']))
1197f93b3b50SAndreas Gohr        $q = $query['p'];        // yahoo
119871f7bde7SAndreas Gohr    elseif(isset($query['query']))
1199f93b3b50SAndreas Gohr        $q = $query['query'];    // lycos, netscape, clusty, hotbot
120071f7bde7SAndreas Gohr    elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1201f93b3b50SAndreas Gohr        $q = urldecode(ltrim($url['path'],'/'));
1202f3f0262cSandi
1203c66972f2SAdrian Lang    if($q === '') return '';
12046531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1205f93b3b50SAndreas Gohr    return $q;
1206f3f0262cSandi}
1207f3f0262cSandi
1208f3f0262cSandi/**
120915fae107Sandi * Try to set correct locale
121015fae107Sandi *
1211095bfd5cSandi * @deprecated No longer used
121215fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1213f3f0262cSandi */
1214f3f0262cSandifunction setCorrectLocale(){
1215f3f0262cSandi    global $conf;
1216f3f0262cSandi    global $lang;
1217f3f0262cSandi
1218f3f0262cSandi    $enc = strtoupper($lang['encoding']);
1219f3f0262cSandi    foreach ($lang['locales'] as $loc){
1220f3f0262cSandi        //try locale
1221f3f0262cSandi        if(@setlocale(LC_ALL,$loc)) return;
1222f3f0262cSandi        //try loceale with encoding
1223f3f0262cSandi        if(@setlocale(LC_ALL,"$loc.$enc")) return;
1224f3f0262cSandi    }
1225f3f0262cSandi    //still here? try to set from environment
1226f3f0262cSandi    @setlocale(LC_ALL,"");
1227f3f0262cSandi}
1228f3f0262cSandi
1229f3f0262cSandi/**
1230f3f0262cSandi * Return the human readable size of a file
1231f3f0262cSandi *
1232f3f0262cSandi * @param       int    $size   A file size
1233f3f0262cSandi * @param       int    $dec    A number of decimal places
1234f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1235f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1236f3f0262cSandi * @version     1.0.0
1237f3f0262cSandi */
1238f31d5b73Sandifunction filesize_h($size, $dec = 1){
1239f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1240f3f0262cSandi    $count = count($sizes);
1241f3f0262cSandi    $i = 0;
1242f3f0262cSandi
1243f3f0262cSandi    while ($size >= 1024 && ($i < $count - 1)) {
1244f3f0262cSandi        $size /= 1024;
1245f3f0262cSandi        $i++;
1246f3f0262cSandi    }
1247f3f0262cSandi
1248f3f0262cSandi    return round($size, $dec) . ' ' . $sizes[$i];
1249f3f0262cSandi}
1250f3f0262cSandi
125115fae107Sandi/**
1252c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1253c57e365eSAndreas Gohr *
1254c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1255c57e365eSAndreas Gohr */
1256c57e365eSAndreas Gohrfunction datetime_h($dt){
1257c57e365eSAndreas Gohr    global $lang;
1258c57e365eSAndreas Gohr
1259c57e365eSAndreas Gohr    $ago = time() - $dt;
1260c57e365eSAndreas Gohr    if($ago > 24*60*60*30*12*2){
1261c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1262c57e365eSAndreas Gohr    }
1263c57e365eSAndreas Gohr    if($ago > 24*60*60*30*2){
1264c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago/(24*60*60*30)));
1265c57e365eSAndreas Gohr    }
1266c57e365eSAndreas Gohr    if($ago > 24*60*60*7*2){
1267c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1268c57e365eSAndreas Gohr    }
1269c57e365eSAndreas Gohr    if($ago > 24*60*60*2){
1270c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago/(24*60*60)));
1271c57e365eSAndreas Gohr    }
1272c57e365eSAndreas Gohr    if($ago > 60*60*2){
1273c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago/(60*60)));
1274c57e365eSAndreas Gohr    }
1275c57e365eSAndreas Gohr    if($ago > 60*2){
1276c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago/(60)));
1277c57e365eSAndreas Gohr    }
1278c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1279c57e365eSAndreas Gohr}
1280c57e365eSAndreas Gohr
1281c57e365eSAndreas Gohr/**
1282f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1283f2263577SAndreas Gohr *
1284f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1285f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1286f2263577SAndreas Gohr *
1287f2263577SAndreas Gohr * @see datetime_h
1288f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1289f2263577SAndreas Gohr */
1290f2263577SAndreas Gohrfunction dformat($dt=null,$format=''){
1291f2263577SAndreas Gohr    global $conf;
1292f2263577SAndreas Gohr
1293f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1294f2263577SAndreas Gohr    $dt = (int) $dt;
1295f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1296f2263577SAndreas Gohr
1297f2263577SAndreas Gohr    $format = str_replace('%f',datetime_h($dt),$format);
1298f2263577SAndreas Gohr    return strftime($format,$dt);
1299f2263577SAndreas Gohr}
1300f2263577SAndreas Gohr
1301f2263577SAndreas Gohr/**
1302c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1303c4f79b71SMichael Hamann *
1304c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1305c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
130663703ba5SAndreas Gohr * @param int $int_date: current date in UNIX timestamp
1307c4f79b71SMichael Hamann */
1308c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1309c4f79b71SMichael Hamann    $date_mod = date('Y-m-d\TH:i:s', $int_date);
1310c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1311c4f79b71SMichael Hamann    $time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1312c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1313c4f79b71SMichael Hamann    return $date_mod;
1314c4f79b71SMichael Hamann}
1315c4f79b71SMichael Hamann
1316c4f79b71SMichael Hamann/**
131700a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
131800a7b5adSEsther Brunner *
131900a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
132000a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
132100a7b5adSEsther Brunner */
132200a7b5adSEsther Brunnerfunction obfuscate($email) {
132300a7b5adSEsther Brunner    global $conf;
132400a7b5adSEsther Brunner
132500a7b5adSEsther Brunner    switch ($conf['mailguard']) {
132600a7b5adSEsther Brunner        case 'visible' :
132700a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
132800a7b5adSEsther Brunner            return strtr($email, $obfuscate);
132900a7b5adSEsther Brunner
133000a7b5adSEsther Brunner        case 'hex' :
133100a7b5adSEsther Brunner            $encode = '';
133249eb6e38SAndreas Gohr            $len = strlen($email);
133349eb6e38SAndreas Gohr            for ($x=0; $x < $len; $x++){
133449eb6e38SAndreas Gohr                $encode .= '&#x' . bin2hex($email{$x}).';';
133549eb6e38SAndreas Gohr            }
133600a7b5adSEsther Brunner            return $encode;
133700a7b5adSEsther Brunner
133800a7b5adSEsther Brunner        case 'none' :
133900a7b5adSEsther Brunner        default :
134000a7b5adSEsther Brunner            return $email;
134100a7b5adSEsther Brunner    }
134200a7b5adSEsther Brunner}
134300a7b5adSEsther Brunner
134400a7b5adSEsther Brunner/**
134589541d4bSAndreas Gohr * Removes quoting backslashes
134689541d4bSAndreas Gohr *
134789541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
134889541d4bSAndreas Gohr */
134989541d4bSAndreas Gohrfunction unslash($string,$char="'"){
135089541d4bSAndreas Gohr    return str_replace('\\'.$char,$char,$string);
135189541d4bSAndreas Gohr}
135289541d4bSAndreas Gohr
135373038c47SAndreas Gohr/**
135473038c47SAndreas Gohr * Convert php.ini shorthands to byte
135573038c47SAndreas Gohr *
135673038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
135773038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
135873038c47SAndreas Gohr */
135973038c47SAndreas Gohrfunction php_to_byte($v){
136073038c47SAndreas Gohr    $l = substr($v, -1);
136173038c47SAndreas Gohr    $ret = substr($v, 0, -1);
136273038c47SAndreas Gohr    switch(strtoupper($l)){
136373038c47SAndreas Gohr        case 'P':
136473038c47SAndreas Gohr            $ret *= 1024;
136573038c47SAndreas Gohr        case 'T':
136673038c47SAndreas Gohr            $ret *= 1024;
136773038c47SAndreas Gohr        case 'G':
136873038c47SAndreas Gohr            $ret *= 1024;
136973038c47SAndreas Gohr        case 'M':
137073038c47SAndreas Gohr            $ret *= 1024;
137173038c47SAndreas Gohr        case 'K':
137273038c47SAndreas Gohr            $ret *= 1024;
137373038c47SAndreas Gohr        break;
137449cbd23eSOtto Vainio        default;
137549cbd23eSOtto Vainio            $ret *= 10;
137649cbd23eSOtto Vainio        break;
137773038c47SAndreas Gohr    }
137873038c47SAndreas Gohr    return $ret;
137973038c47SAndreas Gohr}
138073038c47SAndreas Gohr
1381546d3a99SAndreas Gohr/**
1382546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1383546d3a99SAndreas Gohr */
1384546d3a99SAndreas Gohrfunction preg_quote_cb($string){
1385546d3a99SAndreas Gohr    return preg_quote($string,'/');
1386546d3a99SAndreas Gohr}
138773038c47SAndreas Gohr
1388bd2f6c2fSAndreas Gohr/**
1389bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1390bd2f6c2fSAndreas Gohr *
1391c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1392bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1393bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1394bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1395bd2f6c2fSAndreas Gohr *
1396bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1397bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1398bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1399bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1400bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
1401bd2f6c2fSAndreas Gohr */
1402a5d27328SAndreas Gohrfunction shorten($keep,$short,$max,$min=9,$char='…'){
1403bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1404bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1405bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1406bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1407bd2f6c2fSAndreas Gohr    $half = floor($max/2);
1408bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1409bd2f6c2fSAndreas Gohr}
1410bd2f6c2fSAndreas Gohr
1411dc58b6f4SAndy Webber/**
1412dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1413dc58b6f4SAndy Webber * in page footer and recent changes pages
1414dc58b6f4SAndy Webber *
1415dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1416dc58b6f4SAndy Webber */
1417dc58b6f4SAndy Webberfunction editorinfo($username){
1418dc58b6f4SAndy Webber    global $conf;
1419dc58b6f4SAndy Webber    global $auth;
1420dc58b6f4SAndy Webber
1421dc58b6f4SAndy Webber    switch($conf['showuseras']){
1422dc58b6f4SAndy Webber        case 'username':
1423dc58b6f4SAndy Webber        case 'email':
1424dc58b6f4SAndy Webber        case 'email_link':
1425173d78c4SAndreas Gohr            if($auth) $info = $auth->getUserData($username);
1426dc58b6f4SAndy Webber            break;
1427dc58b6f4SAndy Webber        default:
1428dc58b6f4SAndy Webber            return hsc($username);
1429dc58b6f4SAndy Webber    }
1430dc58b6f4SAndy Webber
1431dc58b6f4SAndy Webber    if(isset($info) && $info) {
1432dc58b6f4SAndy Webber        switch($conf['showuseras']){
1433dc58b6f4SAndy Webber            case 'username':
1434dc58b6f4SAndy Webber                return hsc($info['name']);
1435dc58b6f4SAndy Webber            case 'email':
1436dc58b6f4SAndy Webber                return obfuscate($info['mail']);
1437dc58b6f4SAndy Webber            case 'email_link':
1438dc58b6f4SAndy Webber                $mail=obfuscate($info['mail']);
1439dc58b6f4SAndy Webber                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1440dc58b6f4SAndy Webber            default:
1441dc58b6f4SAndy Webber                return hsc($username);
1442dc58b6f4SAndy Webber        }
1443dc58b6f4SAndy Webber    } else {
1444dc58b6f4SAndy Webber        return hsc($username);
1445dc58b6f4SAndy Webber    }
1446066fee30SAndreas Gohr}
1447066fee30SAndreas Gohr
1448066fee30SAndreas Gohr/**
1449066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1450066fee30SAndreas Gohr * When no image exists, returns an empty string
1451066fee30SAndreas Gohr *
1452066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1453066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
1454066fee30SAndreas Gohr */
1455066fee30SAndreas Gohrfunction license_img($type){
1456066fee30SAndreas Gohr    global $license;
1457066fee30SAndreas Gohr    global $conf;
1458066fee30SAndreas Gohr    if(!$conf['license']) return '';
1459066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1460066fee30SAndreas Gohr    $lic = $license[$conf['license']];
1461066fee30SAndreas Gohr    $try = array();
1462066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1463066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1464066fee30SAndreas Gohr    if(substr($conf['license'],0,3) == 'cc-'){
1465066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1466066fee30SAndreas Gohr    }
1467066fee30SAndreas Gohr    foreach($try as $src){
1468066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1469066fee30SAndreas Gohr    }
1470066fee30SAndreas Gohr    return '';
1471dc58b6f4SAndy Webber}
1472dc58b6f4SAndy Webber
147313c08e2fSMichael Klier/**
147413c08e2fSMichael Klier * Checks if the given amount of memory is available
147513c08e2fSMichael Klier *
147613c08e2fSMichael Klier * If the memory_get_usage() function is not available the
147713c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
147813c08e2fSMichael Klier *
147913c08e2fSMichael Klier * @param  int $mem  Size of memory you want to allocate in bytes
148013c08e2fSMichael Klier * @param  int $used already allocated memory (see above)
148113c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
148213c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
148313c08e2fSMichael Klier */
148413c08e2fSMichael Klierfunction is_mem_available($mem,$bytes=1048576){
148513c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
148613c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
148713c08e2fSMichael Klier
148813c08e2fSMichael Klier    // parse limit to bytes
148913c08e2fSMichael Klier    $limit = php_to_byte($limit);
149013c08e2fSMichael Klier
149113c08e2fSMichael Klier    // get used memory if possible
149213c08e2fSMichael Klier    if(function_exists('memory_get_usage')){
149313c08e2fSMichael Klier        $used = memory_get_usage();
149449eb6e38SAndreas Gohr    }else{
149549eb6e38SAndreas Gohr        $used = $bytes;
149613c08e2fSMichael Klier    }
149713c08e2fSMichael Klier
149813c08e2fSMichael Klier    if($used+$mem > $limit){
149913c08e2fSMichael Klier        return false;
150013c08e2fSMichael Klier    }
150113c08e2fSMichael Klier
150213c08e2fSMichael Klier    return true;
150313c08e2fSMichael Klier}
150413c08e2fSMichael Klier
1505af2408d5SAndreas Gohr/**
1506af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1507af2408d5SAndreas Gohr *
1508af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1509af2408d5SAndreas Gohr *
1510af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1511af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1512af2408d5SAndreas Gohr */
1513af2408d5SAndreas Gohrfunction send_redirect($url){
15140181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
15150181f021SAndreas Gohr    global $MSG;
15160181f021SAndreas Gohr    if (isset($MSG) && count($MSG) && !defined('NOSESSION')){
15170181f021SAndreas Gohr        //reopen session, store data and close session again
15180181f021SAndreas Gohr        @session_start();
15190181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
15200181f021SAndreas Gohr    }
15210181f021SAndreas Gohr
1522d4869846SAndreas Gohr    // always close the session
1523d4869846SAndreas Gohr    session_write_close();
1524d4869846SAndreas Gohr
1525c10dcb7dSAndreas Gohr    // work around IE bug
1526c10dcb7dSAndreas Gohr    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
1527c10dcb7dSAndreas Gohr    list($url,$hash) = explode('#',$url);
1528c10dcb7dSAndreas Gohr    if($hash){
1529c10dcb7dSAndreas Gohr        if(strpos($url,'?')){
1530c10dcb7dSAndreas Gohr            $url = $url.'&#'.$hash;
1531c10dcb7dSAndreas Gohr        }else{
1532c10dcb7dSAndreas Gohr            $url = $url.'?&#'.$hash;
1533c10dcb7dSAndreas Gohr        }
1534c10dcb7dSAndreas Gohr    }
1535c10dcb7dSAndreas Gohr
1536af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1537af2408d5SAndreas Gohr    if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1538af2408d5SAndreas Gohr        (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1539af2408d5SAndreas Gohr        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1540af2408d5SAndreas Gohr        $matches[1] < 6 ){
1541af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1542af2408d5SAndreas Gohr    }else{
1543af2408d5SAndreas Gohr        header('Location: '.$url);
1544af2408d5SAndreas Gohr    }
1545af2408d5SAndreas Gohr    exit;
1546af2408d5SAndreas Gohr}
1547af2408d5SAndreas Gohr
15485b75cd1fSAdrian Lang/**
15495b75cd1fSAdrian Lang * Validate a value using a set of valid values
15505b75cd1fSAdrian Lang *
15515b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
15525b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
15535b75cd1fSAdrian Lang * default is specified, throws an exception.
15545b75cd1fSAdrian Lang *
15555b75cd1fSAdrian Lang * @param string $param        The name of the parameter
15565b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
15575b75cd1fSAdrian Lang *                             be marked by the key “default”.
15585b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
15595b75cd1fSAdrian Lang *                             or $_GET)
15605b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
15615b75cd1fSAdrian Lang *
15625b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
15635b75cd1fSAdrian Lang */
15645b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
15655b75cd1fSAdrian Lang    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
15665b75cd1fSAdrian Lang        return $array[$param];
15675b75cd1fSAdrian Lang    } elseif (isset($valid_values['default'])) {
15685b75cd1fSAdrian Lang        return $valid_values['default'];
15695b75cd1fSAdrian Lang    } else {
15705b75cd1fSAdrian Lang        throw new Exception($exc);
15715b75cd1fSAdrian Lang    }
15725b75cd1fSAdrian Lang}
15735b75cd1fSAdrian Lang
157463703ba5SAndreas Gohr/**
157563703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
157663703ba5SAndreas Gohr */
1577554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1578554a8c9fSAdrian Lang    if (strpos($_COOKIE['DOKU_PREFS'], $pref) !== false) {
1579554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
158063703ba5SAndreas Gohr        $cnt   = count($parts);
158163703ba5SAndreas Gohr        for ($i = 0; $i < $cnt; $i+=2){
1582554a8c9fSAdrian Lang            if ($parts[$i] == $pref) {
1583554a8c9fSAdrian Lang                return $parts[$i+1];
1584554a8c9fSAdrian Lang            }
1585554a8c9fSAdrian Lang        }
1586554a8c9fSAdrian Lang    }
1587554a8c9fSAdrian Lang    return $default;
1588554a8c9fSAdrian Lang}
1589554a8c9fSAdrian Lang
1590e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1591