xref: /dokuwiki/inc/common.php (revision 80fcb26867ee7f89b0c1e7db9c9e59dc4c9aeb58)
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);
1799c8d7f2Smichaeldefine('RECENTS_MEDIA_CHANGES',16);
18b6912aeaSAndreas Gohr
19b6912aeaSAndreas Gohr/**
20d5197206Schris * Wrapper around htmlspecialchars()
21d5197206Schris *
22d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
23d5197206Schris * @see    htmlspecialchars()
24d5197206Schris */
25d5197206Schrisfunction hsc($string){
26d5197206Schris    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
27d5197206Schris}
28d5197206Schris
29d5197206Schris/**
30d5197206Schris * print a newline terminated string
31d5197206Schris *
32d5197206Schris * You can give an indention as optional parameter
33d5197206Schris *
34d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
35d5197206Schris */
3625ec097bSChris Smithfunction ptln($string,$indent=0){
3725ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
3802b0b681SAndreas Gohr}
3902b0b681SAndreas Gohr
4002b0b681SAndreas Gohr/**
4102b0b681SAndreas Gohr * strips control characters (<32) from the given string
4202b0b681SAndreas Gohr *
4302b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4402b0b681SAndreas Gohr */
4502b0b681SAndreas Gohrfunction stripctl($string){
4602b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s','',$string);
47d5197206Schris}
48d5197206Schris
49d5197206Schris/**
50634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
51634d7150SAndreas Gohr *
52634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
53634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
54634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
55634d7150SAndreas Gohr * @return  string
56634d7150SAndreas Gohr */
57634d7150SAndreas Gohrfunction getSecurityToken(){
58634d7150SAndreas Gohr    return md5(auth_cookiesalt().session_id());
59634d7150SAndreas Gohr}
60634d7150SAndreas Gohr
61634d7150SAndreas Gohr/**
62634d7150SAndreas Gohr * Check the secret CSRF token
63634d7150SAndreas Gohr */
64634d7150SAndreas Gohrfunction checkSecurityToken($token=null){
65df97eaacSAndreas Gohr    if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
66df97eaacSAndreas Gohr
67634d7150SAndreas Gohr    if(is_null($token)) $token = $_REQUEST['sectok'];
68634d7150SAndreas Gohr    if(getSecurityToken() != $token){
69634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.',-1);
70634d7150SAndreas Gohr        return false;
71634d7150SAndreas Gohr    }
72634d7150SAndreas Gohr    return true;
73634d7150SAndreas Gohr}
74634d7150SAndreas Gohr
75634d7150SAndreas Gohr/**
76634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
77634d7150SAndreas Gohr *
78634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
79634d7150SAndreas Gohr */
80634d7150SAndreas Gohrfunction formSecurityToken($print=true){
812404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
82634d7150SAndreas Gohr    if($print){
83634d7150SAndreas Gohr        echo $ret;
84634d7150SAndreas Gohr    }else{
85634d7150SAndreas Gohr        return $ret;
86634d7150SAndreas Gohr    }
87634d7150SAndreas Gohr}
88634d7150SAndreas Gohr
89634d7150SAndreas Gohr/**
9015fae107Sandi * Return info about the current document as associative
91f3f0262cSandi * array.
9215fae107Sandi *
9315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
94f3f0262cSandi */
95f3f0262cSandifunction pageinfo(){
96f3f0262cSandi    global $ID;
97f3f0262cSandi    global $REV;
987b3a6803SAndreas Gohr    global $RANGE;
99f3f0262cSandi    global $USERINFO;
100f3f0262cSandi    global $conf;
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
2302684e50aSAndreas Gohr        $url .= $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 = '';
2462684e50aSAndreas Gohr    foreach($params as $key => $val){
2477bff22c0SAndreas Gohr        if($key{0} == '_') continue;
248b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
2497bff22c0SAndreas Gohr
2502684e50aSAndreas Gohr        $url .= $key.'="';
2512684e50aSAndreas Gohr        $url .= htmlspecialchars ($val);
2522684e50aSAndreas Gohr        $url .= '" ';
2532684e50aSAndreas Gohr    }
2542684e50aSAndreas Gohr    return $url;
2552684e50aSAndreas Gohr}
2562684e50aSAndreas Gohr
2572684e50aSAndreas Gohr
2582684e50aSAndreas Gohr/**
25915fae107Sandi * This builds the breadcrumb trail and returns it as array
26015fae107Sandi *
26115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
262f3f0262cSandi */
263f3f0262cSandifunction breadcrumbs(){
2648746e727Sandi    // we prepare the breadcrumbs early for quick session closing
2658746e727Sandi    static $crumbs = null;
2668746e727Sandi    if($crumbs != null) return $crumbs;
2678746e727Sandi
268f3f0262cSandi    global $ID;
269f3f0262cSandi    global $ACT;
270f3f0262cSandi    global $conf;
271f3f0262cSandi
272f3f0262cSandi    //first visit?
273c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
274f3f0262cSandi    //we only save on show and existing wiki documents
275a77f5846Sjan    $file = wikiFN($ID);
276a77f5846Sjan    if($ACT != 'show' || !@file_exists($file)){
277e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
278f3f0262cSandi        return $crumbs;
279f3f0262cSandi    }
280a77f5846Sjan
281a77f5846Sjan    // page names
2821a84a0f3SAnika Henke    $name = noNSorNS($ID);
283fe9ec250SChris Smith    if (useHeading('navigation')) {
284a77f5846Sjan        // get page title
285955cd091SChris Smith        $title = p_get_first_heading($ID,true);
286a77f5846Sjan        if ($title) {
287a77f5846Sjan            $name = $title;
288a77f5846Sjan        }
289a77f5846Sjan    }
290a77f5846Sjan
291f3f0262cSandi    //remove ID from array
292a77f5846Sjan    if (isset($crumbs[$ID])) {
293a77f5846Sjan        unset($crumbs[$ID]);
294f3f0262cSandi    }
295f3f0262cSandi
296f3f0262cSandi    //add to array
297a77f5846Sjan    $crumbs[$ID] = $name;
298f3f0262cSandi    //reduce size
299f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']){
300f3f0262cSandi        array_shift($crumbs);
301f3f0262cSandi    }
302f3f0262cSandi    //save to session
303e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
304f3f0262cSandi    return $crumbs;
305f3f0262cSandi}
306f3f0262cSandi
307f3f0262cSandi/**
30815fae107Sandi * Filter for page IDs
30915fae107Sandi *
310f3f0262cSandi * This is run on a ID before it is outputted somewhere
311f3f0262cSandi * currently used to replace the colon with something else
312f3f0262cSandi * on Windows systems and to have proper URL encoding
31315fae107Sandi *
31449c713a3Sandi * Urlencoding is ommitted when the second parameter is false
31549c713a3Sandi *
31615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
317f3f0262cSandi */
31849c713a3Sandifunction idfilter($id,$ue=true){
319f3f0262cSandi    global $conf;
320f3f0262cSandi    if ($conf['useslash'] && $conf['userewrite']){
321f3f0262cSandi        $id = strtr($id,':','/');
322f3f0262cSandi    }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
323f3f0262cSandi            $conf['userewrite']) {
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 */
342b174aeaeSchrisfunction wl($id='',$more='',$abs=false,$sep='&amp;'){
343f3f0262cSandi    global $conf;
3446de3759aSAndreas Gohr    if(is_array($more)){
345b174aeaeSchris        $more = buildURLparams($more,$sep);
3466de3759aSAndreas Gohr    }else{
347b174aeaeSchris        $more = str_replace(',',$sep,$more);
3486de3759aSAndreas Gohr    }
349f3f0262cSandi
350f3f0262cSandi    $id    = idfilter($id);
351ed7b5f09Sandi    if($abs){
352ed7b5f09Sandi        $xlink = DOKU_URL;
353ed7b5f09Sandi    }else{
354ed7b5f09Sandi        $xlink = DOKU_BASE;
355ed7b5f09Sandi    }
356f3f0262cSandi
3576c7843b5Sandi    if($conf['userewrite'] == 2){
3586c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
3596c7843b5Sandi        if($more) $xlink .= '?'.$more;
3606c7843b5Sandi    }elseif($conf['userewrite']){
361f3f0262cSandi        $xlink .= $id;
362f3f0262cSandi        if($more) $xlink .= '?'.$more;
363bce3726dSAndreas Gohr    }elseif($id){
3646c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
365b174aeaeSchris        if($more) $xlink .= $sep.$more;
366bce3726dSAndreas Gohr    }else{
367bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
368bce3726dSAndreas Gohr        if($more) $xlink .= '?'.$more;
369f3f0262cSandi    }
370f3f0262cSandi
371f3f0262cSandi    return $xlink;
372f3f0262cSandi}
373f3f0262cSandi
374f3f0262cSandi/**
375f5c2808fSBen Coburn * This builds a link to an alternate page format
376f5c2808fSBen Coburn *
377f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
378f5c2808fSBen Coburn *
379f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
380f5c2808fSBen Coburn */
381f5c2808fSBen Coburnfunction exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
382f5c2808fSBen Coburn    global $conf;
383f5c2808fSBen Coburn    if(is_array($more)){
384f5c2808fSBen Coburn        $more = buildURLparams($more,$sep);
385f5c2808fSBen Coburn    }else{
386f5c2808fSBen Coburn        $more = str_replace(',',$sep,$more);
387f5c2808fSBen Coburn    }
388f5c2808fSBen Coburn
389f5c2808fSBen Coburn    $format = rawurlencode($format);
390f5c2808fSBen Coburn    $id = idfilter($id);
391f5c2808fSBen Coburn    if($abs){
392f5c2808fSBen Coburn        $xlink = DOKU_URL;
393f5c2808fSBen Coburn    }else{
394f5c2808fSBen Coburn        $xlink = DOKU_BASE;
395f5c2808fSBen Coburn    }
396f5c2808fSBen Coburn
397f5c2808fSBen Coburn    if($conf['userewrite'] == 2){
398f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
399f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
400f5c2808fSBen Coburn    }elseif($conf['userewrite'] == 1){
401f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
402f5c2808fSBen Coburn        if($more) $xlink .= '?'.$more;
403f5c2808fSBen Coburn    }else{
404f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
405f5c2808fSBen Coburn        if($more) $xlink .= $sep.$more;
406f5c2808fSBen Coburn    }
407f5c2808fSBen Coburn
408f5c2808fSBen Coburn    return $xlink;
409f5c2808fSBen Coburn}
410f5c2808fSBen Coburn
411f5c2808fSBen Coburn/**
4126de3759aSAndreas Gohr * Build a link to a media file
4136de3759aSAndreas Gohr *
4146de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4158c08db0aSAndreas Gohr *
4168c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4178c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4188c08db0aSAndreas Gohr *
4198c08db0aSAndreas Gohr * @param string  $id     - the media file id or URL
4208c08db0aSAndreas Gohr * @param mixed   $more   - string or array with additional parameters
4218c08db0aSAndreas Gohr * @param boolean $direct - link to detail page if false
4228c08db0aSAndreas Gohr * @param string  $sep    - URL parameter separator
4238c08db0aSAndreas Gohr * @param boolean $abs    - Create an absolute URL
4246de3759aSAndreas Gohr */
42555b2b31bSAndreas Gohrfunction ml($id='',$more='',$direct=true,$sep='&amp;',$abs=false){
4266de3759aSAndreas Gohr    global $conf;
4276de3759aSAndreas Gohr    if(is_array($more)){
4288c08db0aSAndreas Gohr        // strip defaults for shorter URLs
4298c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
4308c08db0aSAndreas Gohr        if(!$more['w']) unset($more['w']);
4318c08db0aSAndreas Gohr        if(!$more['h']) unset($more['h']);
4328c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
433b174aeaeSchris        $more = buildURLparams($more,$sep);
4346de3759aSAndreas Gohr    }else{
4358c08db0aSAndreas Gohr        $more = str_replace('cache=cache','',$more); //skip default
4368c08db0aSAndreas Gohr        $more = str_replace(',,',',',$more);
437b174aeaeSchris        $more = str_replace(',',$sep,$more);
4386de3759aSAndreas Gohr    }
4396de3759aSAndreas Gohr
44055b2b31bSAndreas Gohr    if($abs){
44155b2b31bSAndreas Gohr        $xlink = DOKU_URL;
44255b2b31bSAndreas Gohr    }else{
4436de3759aSAndreas Gohr        $xlink = DOKU_BASE;
44455b2b31bSAndreas Gohr    }
4456de3759aSAndreas Gohr
4466de3759aSAndreas Gohr    // external URLs are always direct without rewriting
4476de3759aSAndreas Gohr    if(preg_match('#^(https?|ftp)://#i',$id)){
4486de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
44969d17d94SAndreas Gohr        // add hash:
45069d17d94SAndreas Gohr        $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id),0,6);
4516de3759aSAndreas Gohr        if($more){
45269d17d94SAndreas Gohr            $xlink .= $sep.$more;
453b174aeaeSchris            $xlink .= $sep.'media='.rawurlencode($id);
4546de3759aSAndreas Gohr        }else{
45569d17d94SAndreas Gohr            $xlink .= $sep.'media='.rawurlencode($id);
4566de3759aSAndreas Gohr        }
4576de3759aSAndreas Gohr        return $xlink;
4586de3759aSAndreas Gohr    }
4596de3759aSAndreas Gohr
4606de3759aSAndreas Gohr    $id = idfilter($id);
4616de3759aSAndreas Gohr
4626de3759aSAndreas Gohr    // decide on scriptname
4636de3759aSAndreas Gohr    if($direct){
4646de3759aSAndreas Gohr        if($conf['userewrite'] == 1){
4656de3759aSAndreas Gohr            $script = '_media';
4666de3759aSAndreas Gohr        }else{
4676de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
4686de3759aSAndreas Gohr        }
4696de3759aSAndreas Gohr    }else{
4706de3759aSAndreas Gohr        if($conf['userewrite'] == 1){
4716de3759aSAndreas Gohr            $script = '_detail';
4726de3759aSAndreas Gohr        }else{
4736de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
4746de3759aSAndreas Gohr        }
4756de3759aSAndreas Gohr    }
4766de3759aSAndreas Gohr
4776de3759aSAndreas Gohr    // build URL based on rewrite mode
4786de3759aSAndreas Gohr    if($conf['userewrite']){
4796de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
4806de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
4816de3759aSAndreas Gohr    }else{
4826de3759aSAndreas Gohr        if($more){
483a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
484b174aeaeSchris            $xlink .= $sep.'media='.$id;
4856de3759aSAndreas Gohr        }else{
486a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
4876de3759aSAndreas Gohr        }
4886de3759aSAndreas Gohr    }
4896de3759aSAndreas Gohr
4906de3759aSAndreas Gohr    return $xlink;
4916de3759aSAndreas Gohr}
4926de3759aSAndreas Gohr
4936de3759aSAndreas Gohr
4946de3759aSAndreas Gohr
4956de3759aSAndreas Gohr/**
496f3f0262cSandi * Just builds a link to a script
49715fae107Sandi *
498ed7b5f09Sandi * @todo   maybe obsolete
49915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
500f3f0262cSandi */
501f3f0262cSandifunction script($script='doku.php'){
502ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
503f3f0262cSandi}
504f3f0262cSandi
505f3f0262cSandi/**
50615fae107Sandi * Spamcheck against wordlist
50715fae107Sandi *
508f3f0262cSandi * Checks the wikitext against a list of blocked expressions
509f3f0262cSandi * returns true if the text contains any bad words
51015fae107Sandi *
511e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
512e403cc58SMichael Klier *
513e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
514e403cc58SMichael Klier *  and gain information about the user who was blocked.
515e403cc58SMichael Klier *
516e403cc58SMichael Klier *  Event data:
517e403cc58SMichael Klier *    data['matches']  - array of matches
518e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
519e403cc58SMichael Klier *      [ip]           - ip address
520e403cc58SMichael Klier *      [user]         - username (if logged in)
521e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
522e403cc58SMichael Klier *      [name]         - real name (if logged in)
523e403cc58SMichael Klier *
52415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5256dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
5266dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
5276dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
528f3f0262cSandi */
5296dffa0e0SAndreas Gohrfunction checkwordblock($text=''){
530f3f0262cSandi    global $TEXT;
5316dffa0e0SAndreas Gohr    global $PRE;
5326dffa0e0SAndreas Gohr    global $SUF;
533f3f0262cSandi    global $conf;
534e403cc58SMichael Klier    global $INFO;
535f3f0262cSandi
536f3f0262cSandi    if(!$conf['usewordblock']) return false;
537f3f0262cSandi
5386dffa0e0SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF";
5396dffa0e0SAndreas Gohr
540041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
5416dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text);
542041d1964SAndreas Gohr
543b9ac8716Schris    $wordblocks = getWordblocks();
5443e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
5453e2965d7Sandi    if(version_compare(phpversion(),'4.3.0','<')){
5463e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
5473e2965d7Sandi        // backreferences are used - the maximum is 99
5483e2965d7Sandi        // this is very bad performancewise and may even be too high still
5493e2965d7Sandi        $chunksize = 40;
5503e2965d7Sandi    }else{
551a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
5523e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
553a51d08efSAndreas Gohr        $chunksize = 200;
5543e2965d7Sandi    }
555b9ac8716Schris    while($blocks = array_splice($wordblocks,0,$chunksize)){
556f3f0262cSandi        $re = array();
55749eb6e38SAndreas Gohr        // build regexp from blocks
558f3f0262cSandi        foreach($blocks as $block){
559f3f0262cSandi            $block = preg_replace('/#.*$/','',$block);
560f3f0262cSandi            $block = trim($block);
561f3f0262cSandi            if(empty($block)) continue;
562f3f0262cSandi            $re[]  = $block;
563f3f0262cSandi        }
564e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
565e403cc58SMichael Klier            // prepare event data
566e403cc58SMichael Klier            $data['matches'] = $matches;
567e403cc58SMichael Klier            $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
568e403cc58SMichael Klier            if($_SERVER['REMOTE_USER']) {
569e403cc58SMichael Klier                $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
570e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
571e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
572e403cc58SMichael Klier            }
573e403cc58SMichael Klier            $callback = create_function('', 'return true;');
574e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
575b9ac8716Schris        }
576703f6fdeSandi    }
577f3f0262cSandi    return false;
578f3f0262cSandi}
579f3f0262cSandi
580f3f0262cSandi/**
58115fae107Sandi * Return the IP of the client
58215fae107Sandi *
5836d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
58415fae107Sandi *
5856d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
5866d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
5876d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
5886d8affe6SAndreas Gohr * headers
5896d8affe6SAndreas Gohr *
5906d8affe6SAndreas Gohr * @param  boolean $single If set only a single IP is returned
59115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
592f3f0262cSandi */
5936d8affe6SAndreas Gohrfunction clientIP($single=false){
5946d8affe6SAndreas Gohr    $ip = array();
5956d8affe6SAndreas Gohr    $ip[] = $_SERVER['REMOTE_ADDR'];
596bb4866bdSchris    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
5976d8affe6SAndreas Gohr        $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']));
598bb4866bdSchris    if(!empty($_SERVER['HTTP_X_REAL_IP']))
5996d8affe6SAndreas Gohr        $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP']));
6006d8affe6SAndreas Gohr
601dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
602dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
603dc14c6d1SGuy Brand    $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
604dc14c6d1SGuy Brand    $hex_digit = '[A-Fa-f0-9]';
605dc14c6d1SGuy Brand    $h16 = "{$hex_digit}{1,4}";
606dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
607dc14c6d1SGuy Brand    $ls32 = "(?:$h16:$h16|$IPv4Address)";
608dc14c6d1SGuy Brand    $IPv6Address =
609dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
610dc14c6d1SGuy Brand        "(?:$h16:){6}$ls32" .
611dc14c6d1SGuy Brand        "|::(?:$h16:){5}$ls32" .
612dc14c6d1SGuy Brand        "|(?:$h16)?::(?:$h16:){4}$ls32" .
613dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
614dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
615dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
616dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
617dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,5}$h16)?::$h16" .
618dc14c6d1SGuy Brand        "|(?:(?:$h16:){0,6}$h16)?::" .
619dc14c6d1SGuy Brand        ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
620dc14c6d1SGuy Brand
6216d8affe6SAndreas Gohr    // remove any non-IP stuff
6226d8affe6SAndreas Gohr    $cnt = count($ip);
6234ff28443Schris    $match = array();
6246d8affe6SAndreas Gohr    for($i=0; $i<$cnt; $i++){
625dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
6264ff28443Schris            $ip[$i] = $match[0];
6274ff28443Schris        } else {
6284ff28443Schris            $ip[$i] = '';
6294ff28443Schris        }
6306d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
631f3f0262cSandi    }
6326d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
6336d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6346d8affe6SAndreas Gohr
6356d8affe6SAndreas Gohr    if(!$single) return join(',',$ip);
6366d8affe6SAndreas Gohr
6376d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
6386d8affe6SAndreas Gohr    $ip = array_reverse($ip);
6396d8affe6SAndreas Gohr    foreach($ip as $i){
6406d8affe6SAndreas Gohr        if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
6416d8affe6SAndreas Gohr            continue;
6426d8affe6SAndreas Gohr        }else{
6436d8affe6SAndreas Gohr            return $i;
6446d8affe6SAndreas Gohr        }
6456d8affe6SAndreas Gohr    }
6466d8affe6SAndreas Gohr    // still here? just use the first (last) address
6476d8affe6SAndreas Gohr    return $ip[0];
648f3f0262cSandi}
649f3f0262cSandi
650f3f0262cSandi/**
6511c548ebeSAndreas Gohr * Check if the browser is on a mobile device
6521c548ebeSAndreas Gohr *
6531c548ebeSAndreas Gohr * Adapted from the example code at url below
6541c548ebeSAndreas Gohr *
6551c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
6561c548ebeSAndreas Gohr */
6571c548ebeSAndreas Gohrfunction clientismobile(){
6581c548ebeSAndreas Gohr
6591c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
6601c548ebeSAndreas Gohr
6611c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
6621c548ebeSAndreas Gohr
6631c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
6641c548ebeSAndreas Gohr
6651c548ebeSAndreas 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';
6661c548ebeSAndreas Gohr
6671c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
6681c548ebeSAndreas Gohr
6691c548ebeSAndreas Gohr    return false;
6701c548ebeSAndreas Gohr}
6711c548ebeSAndreas Gohr
6721c548ebeSAndreas Gohr
6731c548ebeSAndreas Gohr/**
67463211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
67563211f61SGlen Harris *
67663211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
67763211f61SGlen Harris * @returns a comma separated list of hostnames
67863211f61SGlen Harris */
67963211f61SGlen Harrisfunction gethostsbyaddrs($ips){
68063211f61SGlen Harris    $hosts = array();
68163211f61SGlen Harris    $ips = explode(',',$ips);
682551a720fSMichael Klier
683551a720fSMichael Klier    if(is_array($ips)) {
6843886270dSAndreas Gohr        foreach($ips as $ip){
685551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
68663211f61SGlen Harris        }
687551a720fSMichael Klier        return join(',',$hosts);
688551a720fSMichael Klier    } else {
689551a720fSMichael Klier        return gethostbyaddr(trim($ips));
690551a720fSMichael Klier    }
69163211f61SGlen Harris}
69263211f61SGlen Harris
69363211f61SGlen Harris/**
69415fae107Sandi * Checks if a given page is currently locked.
69515fae107Sandi *
696f3f0262cSandi * removes stale lockfiles
69715fae107Sandi *
69815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
699f3f0262cSandi */
700f3f0262cSandifunction checklock($id){
701f3f0262cSandi    global $conf;
702c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
703f3f0262cSandi
704f3f0262cSandi    //no lockfile
705f3f0262cSandi    if(!@file_exists($lock)) return false;
706f3f0262cSandi
707f3f0262cSandi    //lockfile expired
708f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']){
709d8186216SBen Coburn        @unlink($lock);
710f3f0262cSandi        return false;
711f3f0262cSandi    }
712f3f0262cSandi
713f3f0262cSandi    //my own lock
714f3f0262cSandi    $ip = io_readFile($lock);
715f3f0262cSandi    if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
716f3f0262cSandi        return false;
717f3f0262cSandi    }
718f3f0262cSandi
719f3f0262cSandi    return $ip;
720f3f0262cSandi}
721f3f0262cSandi
722f3f0262cSandi/**
72315fae107Sandi * Lock a page for editing
72415fae107Sandi *
72515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
726f3f0262cSandi */
727f3f0262cSandifunction lock($id){
728544ed901SDaniel Calviño Sánchez    global $conf;
729544ed901SDaniel Calviño Sánchez
730544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0){
731544ed901SDaniel Calviño Sánchez        return;
732544ed901SDaniel Calviño Sánchez    }
733544ed901SDaniel Calviño Sánchez
734c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
735f3f0262cSandi    if($_SERVER['REMOTE_USER']){
736f3f0262cSandi        io_saveFile($lock,$_SERVER['REMOTE_USER']);
737f3f0262cSandi    }else{
738f3f0262cSandi        io_saveFile($lock,clientIP());
739f3f0262cSandi    }
740f3f0262cSandi}
741f3f0262cSandi
742f3f0262cSandi/**
74315fae107Sandi * Unlock a page if it was locked by the user
744f3f0262cSandi *
74515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
74615fae107Sandi * @return bool true if a lock was removed
747f3f0262cSandi */
748f3f0262cSandifunction unlock($id){
749c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
750f3f0262cSandi    if(@file_exists($lock)){
751f3f0262cSandi        $ip = io_readFile($lock);
752f3f0262cSandi        if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
753f3f0262cSandi            @unlink($lock);
754f3f0262cSandi            return true;
755f3f0262cSandi        }
756f3f0262cSandi    }
757f3f0262cSandi    return false;
758f3f0262cSandi}
759f3f0262cSandi
760f3f0262cSandi/**
761f3f0262cSandi * convert line ending to unix format
762f3f0262cSandi *
76315fae107Sandi * @see    formText() for 2crlf conversion
76415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
765f3f0262cSandi */
766f3f0262cSandifunction cleanText($text){
767f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
768f3f0262cSandi    return $text;
769f3f0262cSandi}
770f3f0262cSandi
771f3f0262cSandi/**
772f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
773f3f0262cSandi * It also converts line endings to Windows format which is
774f3f0262cSandi * pseudo standard for webforms.
775f3f0262cSandi *
77615fae107Sandi * @see    cleanText() for 2unix conversion
77715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
778f3f0262cSandi */
779f3f0262cSandifunction formText($text){
7805b7d45a5SAndreas Gohr    $text = str_replace("\012","\015\012",$text);
781f3f0262cSandi    return htmlspecialchars($text);
782f3f0262cSandi}
783f3f0262cSandi
784f3f0262cSandi/**
78515fae107Sandi * Returns the specified local text in raw format
78615fae107Sandi *
78715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
788f3f0262cSandi */
789f3f0262cSandifunction rawLocale($id){
790f3f0262cSandi    return io_readFile(localeFN($id));
791f3f0262cSandi}
792f3f0262cSandi
793f3f0262cSandi/**
794f3f0262cSandi * Returns the raw WikiText
79515fae107Sandi *
79615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
797f3f0262cSandi */
798f3f0262cSandifunction rawWiki($id,$rev=''){
799cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
800f3f0262cSandi}
801f3f0262cSandi
802f3f0262cSandi/**
8037146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
8047146cee2SAndreas Gohr *
805fe17917eSAdrian Lang * @triggers COMMON_PAGE_FROMTEMPLATE
8067146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8077146cee2SAndreas Gohr */
808fe17917eSAdrian Langfunction pageTemplate($id){
809a15ce62dSEsther Brunner    global $conf;
810e29549feSAndreas Gohr
811fe17917eSAdrian Lang    if (is_array($id)) $id = $id[0];
812e29549feSAndreas Gohr
813fe17917eSAdrian Lang    $path = dirname(wikiFN($id));
814fe17917eSAdrian Lang    $tpl = '';
815e29549feSAndreas Gohr    if(@file_exists($path.'/_template.txt')){
816e29549feSAndreas Gohr        $tpl = io_readFile($path.'/_template.txt');
817e29549feSAndreas Gohr    }else{
818e29549feSAndreas Gohr        // search upper namespaces for templates
819e29549feSAndreas Gohr        $len = strlen(rtrim($conf['datadir'],'/'));
820e29549feSAndreas Gohr        while (strlen($path) >= $len){
821e29549feSAndreas Gohr            if(@file_exists($path.'/__template.txt')){
822e29549feSAndreas Gohr                $tpl = io_readFile($path.'/__template.txt');
823e29549feSAndreas Gohr                break;
824e29549feSAndreas Gohr            }
825e29549feSAndreas Gohr            $path = substr($path, 0, strrpos($path, '/'));
826e29549feSAndreas Gohr        }
827e29549feSAndreas Gohr    }
828fe17917eSAdrian Lang    $data = compact('tpl', 'id');
829fe17917eSAdrian Lang    trigger_event('COMMON_PAGE_FROMTEMPLATE', $data, 'parsePageTemplate', true);
830fe17917eSAdrian Lang    return $data['tpl'];
8312b1223ecSAdrian Lang}
8322b1223ecSAdrian Lang
8332b1223ecSAdrian Lang/**
8342b1223ecSAdrian Lang * Performs common page template replacements
835fe17917eSAdrian Lang * This is the default action for COMMON_PAGE_FROMTEMPLATE
8362b1223ecSAdrian Lang *
8372b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
8382b1223ecSAdrian Lang */
839fe17917eSAdrian Langfunction parsePageTemplate($data) {
840fe17917eSAdrian Lang    extract($data);
841fe17917eSAdrian Lang
842b856f7dfSAdrian Lang    global $USERINFO;
843bce53b1fSAdrian Lang    global $conf;
844e29549feSAndreas Gohr
845e29549feSAndreas Gohr    // replace placeholders
84626ece5a7SAndreas Gohr    $file = noNS($id);
84726ece5a7SAndreas Gohr    $page = strtr($file,'_',' ');
84826ece5a7SAndreas Gohr
84926ece5a7SAndreas Gohr    $tpl = str_replace(array(
85026ece5a7SAndreas Gohr                '@ID@',
85126ece5a7SAndreas Gohr                '@NS@',
85226ece5a7SAndreas Gohr                '@FILE@',
85326ece5a7SAndreas Gohr                '@!FILE@',
85426ece5a7SAndreas Gohr                '@!FILE!@',
85526ece5a7SAndreas Gohr                '@PAGE@',
85626ece5a7SAndreas Gohr                '@!PAGE@',
85726ece5a7SAndreas Gohr                '@!!PAGE@',
85826ece5a7SAndreas Gohr                '@!PAGE!@',
85926ece5a7SAndreas Gohr                '@USER@',
86026ece5a7SAndreas Gohr                '@NAME@',
86126ece5a7SAndreas Gohr                '@MAIL@',
86226ece5a7SAndreas Gohr                '@DATE@',
86326ece5a7SAndreas Gohr                ),
86426ece5a7SAndreas Gohr            array(
86526ece5a7SAndreas Gohr                $id,
86626ece5a7SAndreas Gohr                getNS($id),
86726ece5a7SAndreas Gohr                $file,
86826ece5a7SAndreas Gohr                utf8_ucfirst($file),
86926ece5a7SAndreas Gohr                utf8_strtoupper($file),
87026ece5a7SAndreas Gohr                $page,
87126ece5a7SAndreas Gohr                utf8_ucfirst($page),
87226ece5a7SAndreas Gohr                utf8_ucwords($page),
87326ece5a7SAndreas Gohr                utf8_strtoupper($page),
87426ece5a7SAndreas Gohr                $_SERVER['REMOTE_USER'],
875b856f7dfSAdrian Lang                $USERINFO['name'],
876b856f7dfSAdrian Lang                $USERINFO['mail'],
87726ece5a7SAndreas Gohr                $conf['dformat'],
87826ece5a7SAndreas Gohr                ), $tpl);
87926ece5a7SAndreas Gohr
8807d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
8817d644fc8SAndreas Gohr    $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
8827d644fc8SAndreas Gohr
883a15ce62dSEsther Brunner    return $tpl;
8847146cee2SAndreas Gohr}
8857146cee2SAndreas Gohr
8867146cee2SAndreas Gohr/**
88715fae107Sandi * Returns the raw Wiki Text in three slices.
88815fae107Sandi *
88915fae107Sandi * The range parameter needs to have the form "from-to"
89015cfe303Sandi * and gives the range of the section in bytes - no
89115cfe303Sandi * UTF-8 awareness is needed.
892f3f0262cSandi * The returned order is prefix, section and suffix.
89315fae107Sandi *
89415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
895f3f0262cSandi */
896f3f0262cSandifunction rawWikiSlices($range,$id,$rev=''){
897cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
898f3f0262cSandi
899*80fcb268SAdrian Lang    // Parse range
900*80fcb268SAdrian Lang    list($from,$to) = explode('-',$range,2);
901*80fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
902*80fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
903*80fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
904*80fcb268SAdrian Lang
905*80fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
906*80fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to-$from);
90715cfe303Sandi    $slices[2] = substr($text, $to);
908f3f0262cSandi    return $slices;
909f3f0262cSandi}
910f3f0262cSandi
911f3f0262cSandi/**
91215fae107Sandi * Joins wiki text slices
91315fae107Sandi *
914*80fcb268SAdrian Lang * function to join the text slices.
915f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
916f3f0262cSandi * lines between sections if needed (used on saving).
91715fae107Sandi *
91815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
919f3f0262cSandi */
920f3f0262cSandifunction con($pre,$text,$suf,$pretty=false){
921f3f0262cSandi    if($pretty){
922*80fcb268SAdrian Lang        if ($pre !== '' && substr($pre, -1) !== "\n" &&
923*80fcb268SAdrian Lang            substr($text, 0, 1) !== "\n") {
924*80fcb268SAdrian Lang            $pre .= "\n";
925*80fcb268SAdrian Lang        }
926*80fcb268SAdrian Lang        if ($suf !== '' && substr($text, -1) !== "\n" &&
927*80fcb268SAdrian Lang            substr($suf, 0, 1) !== "\n") {
928*80fcb268SAdrian Lang            $text .= "\n";
929*80fcb268SAdrian Lang        }
930f3f0262cSandi    }
931f3f0262cSandi
932f3f0262cSandi    return $pre.$text.$suf;
933f3f0262cSandi}
934f3f0262cSandi
935f3f0262cSandi/**
936a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
937a701424fSBen Coburn * Also directs changelog and attic updates.
93815fae107Sandi *
93915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
94071726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
941f3f0262cSandi */
942b6912aeaSAndreas Gohrfunction saveWikiText($id,$text,$summary,$minor=false){
943a701424fSBen Coburn    /* Note to developers:
944a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
945a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
946a701424fSBen Coburn       after any changes. External edits change the wiki page
947a701424fSBen Coburn       directly without using php or dokuwiki.
948a701424fSBen Coburn     */
949f3f0262cSandi    global $conf;
950f3f0262cSandi    global $lang;
95171726d78SBen Coburn    global $REV;
952f3f0262cSandi    // ignore if no changes were made
953f3f0262cSandi    if($text == rawWiki($id,'')){
954f3f0262cSandi        return;
955f3f0262cSandi    }
956f3f0262cSandi
957f3f0262cSandi    $file = wikiFN($id);
958a701424fSBen Coburn    $old = @filemtime($file); // from page
95971726d78SBen Coburn    $wasRemoved = empty($text);
960d8186216SBen Coburn    $wasCreated = !@file_exists($file);
96171726d78SBen Coburn    $wasReverted = ($REV==true);
962e45b34cdSBen Coburn    $newRev = false;
963a701424fSBen Coburn    $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
964a701424fSBen Coburn    $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
965a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
96646844156SBen Coburn        // add old revision to the attic if missing
96746844156SBen Coburn        saveOldRevision($id);
96846844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
969a701424fSBen Coburn        if ($old>$oldRev) {
970ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
97146844156SBen Coburn            // remove soon to be stale instructions
97246844156SBen Coburn            $cache = new cache_instructions($id, $file);
97346844156SBen Coburn            $cache->removeCache();
97446844156SBen Coburn        }
97546844156SBen Coburn    }
976f3f0262cSandi
97771726d78SBen Coburn    if ($wasRemoved){
97830725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
97930725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
98030725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
981e45b34cdSBen Coburn        // pre-save deleted revision
982e45b34cdSBen Coburn        @touch($file);
98346844156SBen Coburn        clearstatcache();
984e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
985e1f3d9e1SEsther Brunner        // remove empty file
986f3f0262cSandi        @unlink($file);
98771726d78SBen Coburn        // remove old meta info...
988e1f3d9e1SEsther Brunner        $mfiles = metaFiles($id);
98971726d78SBen Coburn        $changelog = metaFN($id, '.changes');
9903d1f9ec3SMichael Klier        $metadata  = metaFN($id, '.meta');
991e1f3d9e1SEsther Brunner        foreach ($mfiles as $mfile) {
9923d1f9ec3SMichael Klier            // but keep per-page changelog to preserve page history and keep meta data
9933d1f9ec3SMichael Klier            if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink($mfile); }
994b158d625SSteven Danz        }
9953d1f9ec3SMichael Klier        // purge meta data
9963d1f9ec3SMichael Klier        p_purge_metadata($id);
997f3f0262cSandi        $del = true;
9983ce054b3Sandi        // autoset summary on deletion
9993ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
100053d6ccfeSandi        // remove empty namespaces
1001cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1002cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1003f3f0262cSandi    }else{
1004cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1005cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
100646844156SBen Coburn        // pre-save the revision, to keep the attic in sync
100746844156SBen Coburn        $newRev = saveOldRevision($id);
1008f3f0262cSandi        $del = false;
1009f3f0262cSandi    }
1010f3f0262cSandi
101171726d78SBen Coburn    // select changelog line type
101271726d78SBen Coburn    $extra = '';
1013ebf1501fSBen Coburn    $type = DOKU_CHANGE_TYPE_EDIT;
101471726d78SBen Coburn    if ($wasReverted) {
1015ebf1501fSBen Coburn        $type = DOKU_CHANGE_TYPE_REVERT;
101671726d78SBen Coburn        $extra = $REV;
101771726d78SBen Coburn    }
1018ebf1501fSBen Coburn    else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
1019ebf1501fSBen Coburn    else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
1020ebf1501fSBen Coburn    else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
102171726d78SBen Coburn
1022e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
102326a0801fSAndreas Gohr    // send notify mails
102490033e9dSAndreas Gohr    notify($id,'admin',$old,$summary,$minor);
102590033e9dSAndreas Gohr    notify($id,'subscribers',$old,$summary,$minor);
1026f3f0262cSandi
1027ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
102898407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile',time());
10292eccbdaaSGina Haeussge
10302eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1031fe9ec250SChris Smith    if(useHeading('content')){
10322eccbdaaSGina Haeussge        $pages = ft_backlinks($id);
10332eccbdaaSGina Haeussge        foreach ($pages as $page) {
10342eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
10352eccbdaaSGina Haeussge            $cache->removeCache();
10362eccbdaaSGina Haeussge        }
10372eccbdaaSGina Haeussge    }
1038f3f0262cSandi}
1039f3f0262cSandi
1040f3f0262cSandi/**
1041f3f0262cSandi * moves the current version to the attic and returns its
1042f3f0262cSandi * revision date
104315fae107Sandi *
104415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1045f3f0262cSandi */
1046f3f0262cSandifunction saveOldRevision($id){
1047f3f0262cSandi    global $conf;
1048f3f0262cSandi    $oldf = wikiFN($id);
1049f3f0262cSandi    if(!@file_exists($oldf)) return '';
1050f3f0262cSandi    $date = filemtime($oldf);
1051f3f0262cSandi    $newf = wikiFN($id,$date);
1052cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1053f3f0262cSandi    return $date;
1054f3f0262cSandi}
1055f3f0262cSandi
1056f3f0262cSandi/**
1057fde10de4SAdrian Lang * Sends a notify mail on page change or registration
105826a0801fSAndreas Gohr *
105926a0801fSAndreas Gohr * @param  string  $id       The changed page
1060fde10de4SAdrian Lang * @param  string  $who      Who to notify (admin|subscribers|register)
106126a0801fSAndreas Gohr * @param  int     $rev      Old page revision
106226a0801fSAndreas Gohr * @param  string  $summary  What changed
106390033e9dSAndreas Gohr * @param  boolean $minor    Is this a minor edit?
106402a498e7Schris * @param  array   $replace  Additional string substitutions, @KEY@ to be replaced by value
106515fae107Sandi *
106615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1067f3f0262cSandi */
106802a498e7Schrisfunction notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1069f3f0262cSandi    global $lang;
1070f3f0262cSandi    global $conf;
107130d7d718SMike Frysinger    global $INFO;
1072b158d625SSteven Danz
107326a0801fSAndreas Gohr    // decide if there is something to do
107426a0801fSAndreas Gohr    if($who == 'admin'){
107526a0801fSAndreas Gohr        if(empty($conf['notify'])) return; //notify enabled?
1076f3f0262cSandi        $text = rawLocale('mailtext');
107726a0801fSAndreas Gohr        $to   = $conf['notify'];
107826a0801fSAndreas Gohr        $bcc  = '';
107926a0801fSAndreas Gohr    }elseif($who == 'subscribers'){
108026a0801fSAndreas Gohr        if(!$conf['subscribers']) return; //subscribers enabled?
108190033e9dSAndreas Gohr        if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
10828881fcc9SAdrian Lang        $data = array('id' => $id, 'addresslist' => '', 'self' => false);
10838881fcc9SAdrian Lang        trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data,
10848881fcc9SAdrian Lang                      'subscription_addresslist');
10858881fcc9SAdrian Lang        $bcc = $data['addresslist'];
108626a0801fSAndreas Gohr        if(empty($bcc)) return;
108726a0801fSAndreas Gohr        $to   = '';
10885b75cd1fSAdrian Lang        $text = rawLocale('subscr_single');
1089a06e4bdbSSebastian Harl    }elseif($who == 'register'){
1090a06e4bdbSSebastian Harl        if(empty($conf['registernotify'])) return;
1091a06e4bdbSSebastian Harl        $text = rawLocale('registermail');
1092a06e4bdbSSebastian Harl        $to   = $conf['registernotify'];
1093a06e4bdbSSebastian Harl        $bcc  = '';
109426a0801fSAndreas Gohr    }else{
109526a0801fSAndreas Gohr        return; //just to be safe
109626a0801fSAndreas Gohr    }
109726a0801fSAndreas Gohr
109863211f61SGlen Harris    $ip   = clientIP();
1099f2263577SAndreas Gohr    $text = str_replace('@DATE@',dformat(),$text);
1100f3f0262cSandi    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
110163211f61SGlen Harris    $text = str_replace('@IPADDRESS@',$ip,$text);
110263211f61SGlen Harris    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1103c9321d91SAndreas Gohr    $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
110426a0801fSAndreas Gohr    $text = str_replace('@PAGE@',$id,$text);
110526a0801fSAndreas Gohr    $text = str_replace('@TITLE@',$conf['title'],$text);
1106ed7b5f09Sandi    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1107f3f0262cSandi    $text = str_replace('@SUMMARY@',$summary,$text);
11087a82afdcSandi    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1109f3f0262cSandi
111002a498e7Schris    foreach ($replace as $key => $substitution) {
111102a498e7Schris        $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
111202a498e7Schris    }
111302a498e7Schris
1114a06e4bdbSSebastian Harl    if($who == 'register'){
1115a06e4bdbSSebastian Harl        $subject = $lang['mail_new_user'].' '.$summary;
1116a06e4bdbSSebastian Harl    }elseif($rev){
1117f3f0262cSandi        $subject = $lang['mail_changed'].' '.$id;
1118c9321d91SAndreas Gohr        $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
11194b7f9e70STom N Harris        $df  = new Diff(explode("\n",rawWiki($id,$rev)),
11204b7f9e70STom N Harris                        explode("\n",rawWiki($id)));
1121f3f0262cSandi        $dformat = new UnifiedDiffFormatter();
1122f3f0262cSandi        $diff    = $dformat->format($df);
1123f3f0262cSandi    }else{
1124f3f0262cSandi        $subject=$lang['mail_newpage'].' '.$id;
1125f3f0262cSandi        $text = str_replace('@OLDPAGE@','none',$text);
1126f3f0262cSandi        $diff = rawWiki($id);
1127f3f0262cSandi    }
1128f3f0262cSandi    $text = str_replace('@DIFF@',$diff,$text);
1129241f3a36Sandi    $subject = '['.$conf['title'].'] '.$subject;
1130f3f0262cSandi
113130d7d718SMike Frysinger    $from = $conf['mailfrom'];
113230d7d718SMike Frysinger    $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
113330d7d718SMike Frysinger    $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
113430d7d718SMike Frysinger    $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
113530d7d718SMike Frysinger
113630d7d718SMike Frysinger    mail_send($to,$subject,$text,$from,'',$bcc);
1137f3f0262cSandi}
1138f3f0262cSandi
113915fae107Sandi/**
114071f7bde7SAndreas Gohr * extracts the query from a search engine referrer
114115fae107Sandi *
114215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
114371f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1144f3f0262cSandi */
1145f3f0262cSandifunction getGoogleQuery(){
1146c66972f2SAdrian Lang    if (!isset($_SERVER['HTTP_REFERER'])) {
1147c66972f2SAdrian Lang        return '';
1148c66972f2SAdrian Lang    }
1149f3f0262cSandi    $url = parse_url($_SERVER['HTTP_REFERER']);
1150f3f0262cSandi
1151f3f0262cSandi    $query = array();
1152e4d8a516SKazutaka Miyasaka
1153e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1154e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1155e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1156f3f0262cSandi    parse_str($url['query'],$query);
1157e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1158e4d8a516SKazutaka Miyasaka
1159c66972f2SAdrian Lang    $q = '';
116071f7bde7SAndreas Gohr    if(isset($query['q']))
1161f93b3b50SAndreas Gohr        $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
116271f7bde7SAndreas Gohr    elseif(isset($query['p']))
1163f93b3b50SAndreas Gohr        $q = $query['p'];        // yahoo
116471f7bde7SAndreas Gohr    elseif(isset($query['query']))
1165f93b3b50SAndreas Gohr        $q = $query['query'];    // lycos, netscape, clusty, hotbot
116671f7bde7SAndreas Gohr    elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1167f93b3b50SAndreas Gohr        $q = urldecode(ltrim($url['path'],'/'));
1168f3f0262cSandi
1169c66972f2SAdrian Lang    if($q === '') return '';
11706531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1171f93b3b50SAndreas Gohr    return $q;
1172f3f0262cSandi}
1173f3f0262cSandi
1174f3f0262cSandi/**
117515fae107Sandi * Try to set correct locale
117615fae107Sandi *
1177095bfd5cSandi * @deprecated No longer used
117815fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1179f3f0262cSandi */
1180f3f0262cSandifunction setCorrectLocale(){
1181f3f0262cSandi    global $conf;
1182f3f0262cSandi    global $lang;
1183f3f0262cSandi
1184f3f0262cSandi    $enc = strtoupper($lang['encoding']);
1185f3f0262cSandi    foreach ($lang['locales'] as $loc){
1186f3f0262cSandi        //try locale
1187f3f0262cSandi        if(@setlocale(LC_ALL,$loc)) return;
1188f3f0262cSandi        //try loceale with encoding
1189f3f0262cSandi        if(@setlocale(LC_ALL,"$loc.$enc")) return;
1190f3f0262cSandi    }
1191f3f0262cSandi    //still here? try to set from environment
1192f3f0262cSandi    @setlocale(LC_ALL,"");
1193f3f0262cSandi}
1194f3f0262cSandi
1195f3f0262cSandi/**
1196f3f0262cSandi * Return the human readable size of a file
1197f3f0262cSandi *
1198f3f0262cSandi * @param       int    $size   A file size
1199f3f0262cSandi * @param       int    $dec    A number of decimal places
1200f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1201f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1202f3f0262cSandi * @version     1.0.0
1203f3f0262cSandi */
1204f31d5b73Sandifunction filesize_h($size, $dec = 1){
1205f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1206f3f0262cSandi    $count = count($sizes);
1207f3f0262cSandi    $i = 0;
1208f3f0262cSandi
1209f3f0262cSandi    while ($size >= 1024 && ($i < $count - 1)) {
1210f3f0262cSandi        $size /= 1024;
1211f3f0262cSandi        $i++;
1212f3f0262cSandi    }
1213f3f0262cSandi
1214f3f0262cSandi    return round($size, $dec) . ' ' . $sizes[$i];
1215f3f0262cSandi}
1216f3f0262cSandi
121715fae107Sandi/**
1218c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1219c57e365eSAndreas Gohr *
1220c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1221c57e365eSAndreas Gohr */
1222c57e365eSAndreas Gohrfunction datetime_h($dt){
1223c57e365eSAndreas Gohr    global $lang;
1224c57e365eSAndreas Gohr
1225c57e365eSAndreas Gohr    $ago = time() - $dt;
1226c57e365eSAndreas Gohr    if($ago > 24*60*60*30*12*2){
1227c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1228c57e365eSAndreas Gohr    }
1229c57e365eSAndreas Gohr    if($ago > 24*60*60*30*2){
1230c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago/(24*60*60*30)));
1231c57e365eSAndreas Gohr    }
1232c57e365eSAndreas Gohr    if($ago > 24*60*60*7*2){
1233c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1234c57e365eSAndreas Gohr    }
1235c57e365eSAndreas Gohr    if($ago > 24*60*60*2){
1236c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago/(24*60*60)));
1237c57e365eSAndreas Gohr    }
1238c57e365eSAndreas Gohr    if($ago > 60*60*2){
1239c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago/(60*60)));
1240c57e365eSAndreas Gohr    }
1241c57e365eSAndreas Gohr    if($ago > 60*2){
1242c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago/(60)));
1243c57e365eSAndreas Gohr    }
1244c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1245c57e365eSAndreas Gohr}
1246c57e365eSAndreas Gohr
1247c57e365eSAndreas Gohr/**
1248f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1249f2263577SAndreas Gohr *
1250f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1251f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1252f2263577SAndreas Gohr *
1253f2263577SAndreas Gohr * @see datetime_h
1254f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1255f2263577SAndreas Gohr */
1256f2263577SAndreas Gohrfunction dformat($dt=null,$format=''){
1257f2263577SAndreas Gohr    global $conf;
1258f2263577SAndreas Gohr
1259f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1260f2263577SAndreas Gohr    $dt = (int) $dt;
1261f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1262f2263577SAndreas Gohr
1263f2263577SAndreas Gohr    $format = str_replace('%f',datetime_h($dt),$format);
1264f2263577SAndreas Gohr    return strftime($format,$dt);
1265f2263577SAndreas Gohr}
1266f2263577SAndreas Gohr
1267f2263577SAndreas Gohr/**
126800a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
126900a7b5adSEsther Brunner *
127000a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
127100a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
127200a7b5adSEsther Brunner */
127300a7b5adSEsther Brunnerfunction obfuscate($email) {
127400a7b5adSEsther Brunner    global $conf;
127500a7b5adSEsther Brunner
127600a7b5adSEsther Brunner    switch ($conf['mailguard']) {
127700a7b5adSEsther Brunner        case 'visible' :
127800a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
127900a7b5adSEsther Brunner            return strtr($email, $obfuscate);
128000a7b5adSEsther Brunner
128100a7b5adSEsther Brunner        case 'hex' :
128200a7b5adSEsther Brunner            $encode = '';
128349eb6e38SAndreas Gohr            $len = strlen($email);
128449eb6e38SAndreas Gohr            for ($x=0; $x < $len; $x++){
128549eb6e38SAndreas Gohr                $encode .= '&#x' . bin2hex($email{$x}).';';
128649eb6e38SAndreas Gohr            }
128700a7b5adSEsther Brunner            return $encode;
128800a7b5adSEsther Brunner
128900a7b5adSEsther Brunner        case 'none' :
129000a7b5adSEsther Brunner        default :
129100a7b5adSEsther Brunner            return $email;
129200a7b5adSEsther Brunner    }
129300a7b5adSEsther Brunner}
129400a7b5adSEsther Brunner
129500a7b5adSEsther Brunner/**
129689541d4bSAndreas Gohr * Removes quoting backslashes
129789541d4bSAndreas Gohr *
129889541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
129989541d4bSAndreas Gohr */
130089541d4bSAndreas Gohrfunction unslash($string,$char="'"){
130189541d4bSAndreas Gohr    return str_replace('\\'.$char,$char,$string);
130289541d4bSAndreas Gohr}
130389541d4bSAndreas Gohr
130473038c47SAndreas Gohr/**
130573038c47SAndreas Gohr * Convert php.ini shorthands to byte
130673038c47SAndreas Gohr *
130773038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
130873038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
130973038c47SAndreas Gohr */
131073038c47SAndreas Gohrfunction php_to_byte($v){
131173038c47SAndreas Gohr    $l = substr($v, -1);
131273038c47SAndreas Gohr    $ret = substr($v, 0, -1);
131373038c47SAndreas Gohr    switch(strtoupper($l)){
131473038c47SAndreas Gohr        case 'P':
131573038c47SAndreas Gohr            $ret *= 1024;
131673038c47SAndreas Gohr        case 'T':
131773038c47SAndreas Gohr            $ret *= 1024;
131873038c47SAndreas Gohr        case 'G':
131973038c47SAndreas Gohr            $ret *= 1024;
132073038c47SAndreas Gohr        case 'M':
132173038c47SAndreas Gohr            $ret *= 1024;
132273038c47SAndreas Gohr        case 'K':
132373038c47SAndreas Gohr            $ret *= 1024;
132473038c47SAndreas Gohr        break;
132573038c47SAndreas Gohr    }
132673038c47SAndreas Gohr    return $ret;
132773038c47SAndreas Gohr}
132873038c47SAndreas Gohr
1329546d3a99SAndreas Gohr/**
1330546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1331546d3a99SAndreas Gohr */
1332546d3a99SAndreas Gohrfunction preg_quote_cb($string){
1333546d3a99SAndreas Gohr    return preg_quote($string,'/');
1334546d3a99SAndreas Gohr}
133573038c47SAndreas Gohr
1336bd2f6c2fSAndreas Gohr/**
1337bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1338bd2f6c2fSAndreas Gohr *
1339c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1340bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1341bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1342bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1343bd2f6c2fSAndreas Gohr *
1344bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1345bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1346bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1347bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1348bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
1349bd2f6c2fSAndreas Gohr */
1350a5d27328SAndreas Gohrfunction shorten($keep,$short,$max,$min=9,$char='…'){
1351bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1352bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1353bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1354bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1355bd2f6c2fSAndreas Gohr    $half = floor($max/2);
1356bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1357bd2f6c2fSAndreas Gohr}
1358bd2f6c2fSAndreas Gohr
1359dc58b6f4SAndy Webber/**
1360dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1361dc58b6f4SAndy Webber * in page footer and recent changes pages
1362dc58b6f4SAndy Webber *
1363dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1364dc58b6f4SAndy Webber */
1365dc58b6f4SAndy Webberfunction editorinfo($username){
1366dc58b6f4SAndy Webber    global $conf;
1367dc58b6f4SAndy Webber    global $auth;
1368dc58b6f4SAndy Webber
1369dc58b6f4SAndy Webber    switch($conf['showuseras']){
1370dc58b6f4SAndy Webber        case 'username':
1371dc58b6f4SAndy Webber        case 'email':
1372dc58b6f4SAndy Webber        case 'email_link':
1373173d78c4SAndreas Gohr            if($auth) $info = $auth->getUserData($username);
1374dc58b6f4SAndy Webber            break;
1375dc58b6f4SAndy Webber        default:
1376dc58b6f4SAndy Webber            return hsc($username);
1377dc58b6f4SAndy Webber    }
1378dc58b6f4SAndy Webber
1379dc58b6f4SAndy Webber    if(isset($info) && $info) {
1380dc58b6f4SAndy Webber        switch($conf['showuseras']){
1381dc58b6f4SAndy Webber            case 'username':
1382dc58b6f4SAndy Webber                return hsc($info['name']);
1383dc58b6f4SAndy Webber            case 'email':
1384dc58b6f4SAndy Webber                return obfuscate($info['mail']);
1385dc58b6f4SAndy Webber            case 'email_link':
1386dc58b6f4SAndy Webber                $mail=obfuscate($info['mail']);
1387dc58b6f4SAndy Webber                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1388dc58b6f4SAndy Webber            default:
1389dc58b6f4SAndy Webber                return hsc($username);
1390dc58b6f4SAndy Webber        }
1391dc58b6f4SAndy Webber    } else {
1392dc58b6f4SAndy Webber        return hsc($username);
1393dc58b6f4SAndy Webber    }
1394066fee30SAndreas Gohr}
1395066fee30SAndreas Gohr
1396066fee30SAndreas Gohr/**
1397066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1398066fee30SAndreas Gohr * When no image exists, returns an empty string
1399066fee30SAndreas Gohr *
1400066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1401066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
1402066fee30SAndreas Gohr */
1403066fee30SAndreas Gohrfunction license_img($type){
1404066fee30SAndreas Gohr    global $license;
1405066fee30SAndreas Gohr    global $conf;
1406066fee30SAndreas Gohr    if(!$conf['license']) return '';
1407066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1408066fee30SAndreas Gohr    $lic = $license[$conf['license']];
1409066fee30SAndreas Gohr    $try = array();
1410066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1411066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1412066fee30SAndreas Gohr    if(substr($conf['license'],0,3) == 'cc-'){
1413066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1414066fee30SAndreas Gohr    }
1415066fee30SAndreas Gohr    foreach($try as $src){
1416066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1417066fee30SAndreas Gohr    }
1418066fee30SAndreas Gohr    return '';
1419dc58b6f4SAndy Webber}
1420dc58b6f4SAndy Webber
142113c08e2fSMichael Klier/**
142213c08e2fSMichael Klier * Checks if the given amount of memory is available
142313c08e2fSMichael Klier *
142413c08e2fSMichael Klier * If the memory_get_usage() function is not available the
142513c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
142613c08e2fSMichael Klier *
142713c08e2fSMichael Klier * @param  int $mem  Size of memory you want to allocate in bytes
142813c08e2fSMichael Klier * @param  int $used already allocated memory (see above)
142913c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
143013c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
143113c08e2fSMichael Klier */
143213c08e2fSMichael Klierfunction is_mem_available($mem,$bytes=1048576){
143313c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
143413c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
143513c08e2fSMichael Klier
143613c08e2fSMichael Klier    // parse limit to bytes
143713c08e2fSMichael Klier    $limit = php_to_byte($limit);
143813c08e2fSMichael Klier
143913c08e2fSMichael Klier    // get used memory if possible
144013c08e2fSMichael Klier    if(function_exists('memory_get_usage')){
144113c08e2fSMichael Klier        $used = memory_get_usage();
144249eb6e38SAndreas Gohr    }else{
144349eb6e38SAndreas Gohr        $used = $bytes;
144413c08e2fSMichael Klier    }
144513c08e2fSMichael Klier
144613c08e2fSMichael Klier    if($used+$mem > $limit){
144713c08e2fSMichael Klier        return false;
144813c08e2fSMichael Klier    }
144913c08e2fSMichael Klier
145013c08e2fSMichael Klier    return true;
145113c08e2fSMichael Klier}
145213c08e2fSMichael Klier
1453af2408d5SAndreas Gohr/**
1454af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1455af2408d5SAndreas Gohr *
1456af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1457af2408d5SAndreas Gohr *
1458af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1459af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1460af2408d5SAndreas Gohr */
1461af2408d5SAndreas Gohrfunction send_redirect($url){
1462d4869846SAndreas Gohr    // always close the session
1463d4869846SAndreas Gohr    session_write_close();
1464d4869846SAndreas Gohr
1465af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1466af2408d5SAndreas Gohr    if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1467af2408d5SAndreas Gohr        (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1468af2408d5SAndreas Gohr        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1469af2408d5SAndreas Gohr        $matches[1] < 6 ){
1470af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1471af2408d5SAndreas Gohr    }else{
1472af2408d5SAndreas Gohr        header('Location: '.$url);
1473af2408d5SAndreas Gohr    }
1474af2408d5SAndreas Gohr    exit;
1475af2408d5SAndreas Gohr}
1476af2408d5SAndreas Gohr
14775b75cd1fSAdrian Lang/**
14785b75cd1fSAdrian Lang * Validate a value using a set of valid values
14795b75cd1fSAdrian Lang *
14805b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
14815b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
14825b75cd1fSAdrian Lang * default is specified, throws an exception.
14835b75cd1fSAdrian Lang *
14845b75cd1fSAdrian Lang * @param string $param        The name of the parameter
14855b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
14865b75cd1fSAdrian Lang *                             be marked by the key “default”.
14875b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
14885b75cd1fSAdrian Lang *                             or $_GET)
14895b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
14905b75cd1fSAdrian Lang *
14915b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
14925b75cd1fSAdrian Lang */
14935b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
14945b75cd1fSAdrian Lang    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
14955b75cd1fSAdrian Lang        return $array[$param];
14965b75cd1fSAdrian Lang    } elseif (isset($valid_values['default'])) {
14975b75cd1fSAdrian Lang        return $valid_values['default'];
14985b75cd1fSAdrian Lang    } else {
14995b75cd1fSAdrian Lang        throw new Exception($exc);
15005b75cd1fSAdrian Lang    }
15015b75cd1fSAdrian Lang}
15025b75cd1fSAdrian Lang
15035b75cd1fSAdrian Lang//Setup VIM: ex: et ts=2 enc=utf-8 :
1504