xref: /dokuwiki/inc/pageutils.php (revision 5a932e77b3c806514203323540cb30e5ab9c28cf)
1<?php
2/**
3 * Utilities for handling pagenames
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 * @todo       Combine similar functions like {wiki,media,meta}FN()
8 */
9
10/**
11 * Fetch the an ID from request
12 *
13 * Uses either standard $_REQUEST variable or extracts it from
14 * the full request URI when userewrite is set to 2
15 *
16 * For $param='id' $conf['start'] is returned if no id was found.
17 * If the second parameter is true (default) the ID is cleaned.
18 *
19 * @author Andreas Gohr <andi@splitbrain.org>
20 */
21function getID($param='id',$clean=true){
22    global $conf;
23
24    $id = isset($_REQUEST[$param]) ? $_REQUEST[$param] : null;
25
26    //construct page id from request URI
27    if(empty($id) && $conf['userewrite'] == 2){
28        $request = $_SERVER['REQUEST_URI'];
29        $script = '';
30
31        //get the script URL
32        if($conf['basedir']){
33            $relpath = '';
34            if($param != 'id') {
35                $relpath = 'lib/exe/';
36            }
37            $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']);
38
39        }elseif($_SERVER['PATH_INFO']){
40            $request = $_SERVER['PATH_INFO'];
41        }elseif($_SERVER['SCRIPT_NAME']){
42            $script = $_SERVER['SCRIPT_NAME'];
43        }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
44            $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
45                    $_SERVER['SCRIPT_FILENAME']);
46            $script = '/'.$script;
47        }
48
49        //clean script and request (fixes a windows problem)
50        $script  = preg_replace('/\/\/+/','/',$script);
51        $request = preg_replace('/\/\/+/','/',$request);
52
53        //remove script URL and Querystring to gain the id
54        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
55            $id = preg_replace ('/\?.*/','',$match[1]);
56        }
57        $id = urldecode($id);
58        //strip leading slashes
59        $id = preg_replace('!^/+!','',$id);
60    }
61
62    // Namespace autolinking from URL
63    if(substr($id,-1) == ':' || ($conf['useslash'] && substr($id,-1) == '/')){
64        if(page_exists($id.$conf['start'])){
65            // start page inside namespace
66            $id = $id.$conf['start'];
67        }elseif(page_exists($id.noNS(cleanID($id)))){
68            // page named like the NS inside the NS
69            $id = $id.noNS(cleanID($id));
70        }elseif(page_exists($id)){
71            // page like namespace exists
72            $id = substr($id,0,-1);
73        }else{
74            // fall back to default
75            $id = $id.$conf['start'];
76        }
77        send_redirect(wl($id,'',true));
78    }
79
80    if($clean) $id = cleanID($id);
81    if(empty($id) && $param=='id') $id = $conf['start'];
82
83    return $id;
84}
85
86/**
87 * Remove unwanted chars from ID
88 *
89 * Cleans a given ID to only use allowed characters. Accented characters are
90 * converted to unaccented ones
91 *
92 * @author Andreas Gohr <andi@splitbrain.org>
93 * @param  string  $raw_id    The pageid to clean
94 * @param  boolean $ascii     Force ASCII
95 * @param  boolean $media     Allow leading or trailing _ for media files
96 */
97function cleanID($raw_id,$ascii=false,$media=false){
98    global $conf;
99    global $lang;
100    static $sepcharpat = null;
101
102    global $cache_cleanid;
103    $cache = & $cache_cleanid;
104
105    // check if it's already in the memory cache
106    if (isset($cache[(string)$raw_id])) {
107        return $cache[(string)$raw_id];
108    }
109
110    $sepchar = $conf['sepchar'];
111    if($sepcharpat == null) // build string only once to save clock cycles
112        $sepcharpat = '#\\'.$sepchar.'+#';
113
114    $id = trim((string)$raw_id);
115    $id = utf8_strtolower($id);
116
117    //alternative namespace seperator
118    $id = strtr($id,';',':');
119    if($conf['useslash']){
120        $id = strtr($id,'/',':');
121    }else{
122        $id = strtr($id,'/',$sepchar);
123    }
124
125    if($conf['deaccent'] == 2 || $ascii) $id = utf8_romanize($id);
126    if($conf['deaccent'] || $ascii) $id = utf8_deaccent($id,-1);
127
128    //remove specials
129    $id = utf8_stripspecials($id,$sepchar,'\*');
130
131    if($ascii) $id = utf8_strip($id);
132
133    //clean up
134    $id = preg_replace($sepcharpat,$sepchar,$id);
135    $id = preg_replace('#:+#',':',$id);
136    $id = ($media ? trim($id,':.-') : trim($id,':._-'));
137    $id = preg_replace('#:[:\._\-]+#',':',$id);
138
139    $cache[(string)$raw_id] = $id;
140    return($id);
141}
142
143/**
144 * Return namespacepart of a wiki ID
145 *
146 * @author Andreas Gohr <andi@splitbrain.org>
147 */
148function getNS($id){
149    $pos = strrpos((string)$id,':');
150    if($pos!==false){
151        return substr((string)$id,0,$pos);
152    }
153    return false;
154}
155
156/**
157 * Returns the ID without the namespace
158 *
159 * @author Andreas Gohr <andi@splitbrain.org>
160 */
161function noNS($id) {
162    $pos = strrpos($id, ':');
163    if ($pos!==false) {
164        return substr($id, $pos+1);
165    } else {
166        return $id;
167    }
168}
169
170/**
171 * Returns the current namespace
172 *
173 * @author Nathan Fritz <fritzn@crown.edu>
174 */
175function curNS($id) {
176    return noNS(getNS($id));
177}
178
179/**
180 * Returns the ID without the namespace or current namespace for 'start' pages
181 *
182 * @author Nathan Fritz <fritzn@crown.edu>
183 */
184function noNSorNS($id) {
185    global $conf;
186
187    $p = noNS($id);
188    if ($p == $conf['start']) {
189        $p = curNS($id);
190        if ($p == false) {
191            return noNS($id);
192        }
193    }
194    return $p;
195}
196
197/**
198 * Creates a XHTML valid linkid from a given headline title
199 *
200 * @param string  $title   The headline title
201 * @param array   $check   Existing IDs (title => number)
202 * @author Andreas Gohr <andi@splitbrain.org>
203 */
204function sectionID($title,&$check) {
205    $title = str_replace(array(':','.'),'',cleanID($title));
206    $new = ltrim($title,'0123456789_-');
207    if(empty($new)){
208        $title = 'section'.preg_replace('/[^0-9]+/','',$title); //keep numbers from headline
209    }else{
210        $title = $new;
211    }
212
213    if(is_array($check)){
214        // make sure tiles are unique
215        if (!array_key_exists ($title,$check)) {
216           $check[$title] = 0;
217        } else {
218           $title .= ++ $check[$title];
219        }
220    }
221
222    return $title;
223}
224
225
226/**
227 * Wiki page existence check
228 *
229 * parameters as for wikiFN
230 *
231 * @author Chris Smith <chris@jalakai.co.uk>
232 */
233function page_exists($id,$rev='',$clean=true) {
234    return @file_exists(wikiFN($id,$rev,$clean));
235}
236
237/**
238 * returns the full path to the datafile specified by ID and optional revision
239 *
240 * The filename is URL encoded to protect Unicode chars
241 *
242 * @param  $raw_id  string   id of wikipage
243 * @param  $rev     string   page revision, empty string for current
244 * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
245 *                           when $id is guaranteed to have been cleaned already.
246 *
247 * @author Andreas Gohr <andi@splitbrain.org>
248 */
249function wikiFN($raw_id,$rev='',$clean=true){
250    global $conf;
251
252    global $cache_wikifn;
253    $cache = & $cache_wikifn;
254
255    if (isset($cache[$raw_id]) && isset($cache[$raw_id][$rev])) {
256        return $cache[$raw_id][$rev];
257    }
258
259    $id = $raw_id;
260
261    if ($clean) $id = cleanID($id);
262    $id = str_replace(':','/',$id);
263    if(empty($rev)){
264        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
265    }else{
266        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
267        if($conf['compression']){
268            //test for extensions here, we want to read both compressions
269            if (@file_exists($fn . '.gz')){
270                $fn .= '.gz';
271            }else if(@file_exists($fn . '.bz2')){
272                $fn .= '.bz2';
273            }else{
274                //file doesnt exist yet, so we take the configured extension
275                $fn .= '.' . $conf['compression'];
276            }
277        }
278    }
279
280    if (!isset($cache[$raw_id])) { $cache[$raw_id] = array(); }
281    $cache[$raw_id][$rev] = $fn;
282    return $fn;
283}
284
285/**
286 * Returns the full path to the file for locking the page while editing.
287 *
288 * @author Ben Coburn <btcoburn@silicodon.net>
289 */
290function wikiLockFN($id) {
291    global $conf;
292    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
293}
294
295
296/**
297 * returns the full path to the meta file specified by ID and extension
298 *
299 * The filename is URL encoded to protect Unicode chars
300 *
301 * @author Steven Danz <steven-danz@kc.rr.com>
302 */
303function metaFN($id,$ext){
304    global $conf;
305    $id = cleanID($id);
306    $id = str_replace(':','/',$id);
307    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
308    return $fn;
309}
310
311/**
312 * returns an array of full paths to all metafiles of a given ID
313 *
314 * @author Esther Brunner <esther@kaffeehaus.ch>
315 */
316function metaFiles($id){
317    $name   = noNS($id);
318    $ns     = getNS($id);
319    $dir    = ($ns) ? metaFN($ns,'').'/' : metaFN($ns,'');
320    $files  = array();
321
322    $dh = @opendir($dir);
323    if(!$dh) return $files;
324    while(($file = readdir($dh)) !== false){
325        if(strpos($file,$name.'.') === 0 && !is_dir($dir.$file))
326            $files[] = $dir.$file;
327    }
328    closedir($dh);
329
330    return $files;
331}
332
333/**
334 * returns the full path to the mediafile specified by ID
335 *
336 * The filename is URL encoded to protect Unicode chars
337 *
338 * @author Andreas Gohr <andi@splitbrain.org>
339 */
340function mediaFN($id){
341    global $conf;
342    $id = cleanID($id);
343    $id = str_replace(':','/',$id);
344    $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
345    return $fn;
346}
347
348/**
349 * Returns the full filepath to a localized textfile if local
350 * version isn't found the english one is returned
351 *
352 * @author Andreas Gohr <andi@splitbrain.org>
353 */
354function localeFN($id){
355    global $conf;
356    $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.txt';
357    if(!@file_exists($file)){
358        //fall back to english
359        $file = DOKU_INC.'inc/lang/en/'.$id.'.txt';
360    }
361    return $file;
362}
363
364/**
365 * Resolve relative paths in IDs
366 *
367 * Do not call directly use resolve_mediaid or resolve_pageid
368 * instead
369 *
370 * Partyly based on a cleanPath function found at
371 * http://www.php.net/manual/en/function.realpath.php#57016
372 *
373 * @author <bart at mediawave dot nl>
374 */
375function resolve_id($ns,$id,$clean=true){
376    global $conf;
377
378    // some pre cleaning for useslash:
379    if($conf['useslash']) $id = str_replace('/',':',$id);
380
381    // if the id starts with a dot we need to handle the
382    // relative stuff
383    if($id{0} == '.'){
384        // normalize initial dots without a colon
385        $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id);
386        // prepend the current namespace
387        $id = $ns.':'.$id;
388
389        // cleanup relatives
390        $result = array();
391        $pathA  = explode(':', $id);
392        if (!$pathA[0]) $result[] = '';
393        foreach ($pathA AS $key => $dir) {
394            if ($dir == '..') {
395                if (end($result) == '..') {
396                    $result[] = '..';
397                } elseif (!array_pop($result)) {
398                    $result[] = '..';
399                }
400            } elseif ($dir && $dir != '.') {
401                $result[] = $dir;
402            }
403        }
404        if (!end($pathA)) $result[] = '';
405        $id = implode(':', $result);
406    }elseif($ns !== false && strpos($id,':') === false){
407        //if link contains no namespace. add current namespace (if any)
408        $id = $ns.':'.$id;
409    }
410
411    if($clean) $id = cleanID($id);
412    return $id;
413}
414
415/**
416 * Returns a full media id
417 *
418 * @author Andreas Gohr <andi@splitbrain.org>
419 */
420function resolve_mediaid($ns,&$page,&$exists){
421    $page   = resolve_id($ns,$page);
422    $file   = mediaFN($page);
423    $exists = @file_exists($file);
424}
425
426/**
427 * Returns a full page id
428 *
429 * @author Andreas Gohr <andi@splitbrain.org>
430 */
431function resolve_pageid($ns,&$page,&$exists){
432    global $conf;
433    $exists = false;
434
435    //keep hashlink if exists then clean both parts
436    if (strpos($page,'#')) {
437        list($page,$hash) = explode('#',$page,2);
438    } else {
439        $hash = '';
440    }
441    $hash = cleanID($hash);
442    $page = resolve_id($ns,$page,false); // resolve but don't clean, yet
443
444    // get filename (calls clean itself)
445    $file = wikiFN($page);
446
447    // if ends with colon or slash we have a namespace link
448    if(substr($page,-1) == ':' || ($conf['useslash'] && substr($page,-1) == '/')){
449        if(page_exists($page.$conf['start'])){
450            // start page inside namespace
451            $page = $page.$conf['start'];
452            $exists = true;
453        }elseif(page_exists($page.noNS(cleanID($page)))){
454            // page named like the NS inside the NS
455            $page = $page.noNS(cleanID($page));
456            $exists = true;
457        }elseif(page_exists($page)){
458            // page like namespace exists
459            $page = $page;
460            $exists = true;
461        }else{
462            // fall back to default
463            $page = $page.$conf['start'];
464        }
465    }else{
466        //check alternative plural/nonplural form
467        if(!@file_exists($file)){
468            if( $conf['autoplural'] ){
469                if(substr($page,-1) == 's'){
470                    $try = substr($page,0,-1);
471                }else{
472                    $try = $page.'s';
473                }
474                if(page_exists($try)){
475                    $page   = $try;
476                    $exists = true;
477                }
478            }
479        }else{
480            $exists = true;
481        }
482    }
483
484    // now make sure we have a clean page
485    $page = cleanID($page);
486
487    //add hash if any
488    if(!empty($hash)) $page .= '#'.$hash;
489}
490
491/**
492 * Returns the name of a cachefile from given data
493 *
494 * The needed directory is created by this function!
495 *
496 * @author Andreas Gohr <andi@splitbrain.org>
497 *
498 * @param string $data  This data is used to create a unique md5 name
499 * @param string $ext   This is appended to the filename if given
500 * @return string       The filename of the cachefile
501 */
502function getCacheName($data,$ext=''){
503    global $conf;
504    $md5  = md5($data);
505    $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext;
506    io_makeFileDir($file);
507    return $file;
508}
509
510/**
511 * Checks a pageid against $conf['hidepages']
512 *
513 * @author Andreas Gohr <gohr@cosmocode.de>
514 */
515function isHiddenPage($id){
516    global $conf;
517    global $ACT;
518    if(empty($conf['hidepages'])) return false;
519    if($ACT == 'admin') return false;
520
521    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$id)){
522        return true;
523    }
524    return false;
525}
526
527/**
528 * Reverse of isHiddenPage
529 *
530 * @author Andreas Gohr <gohr@cosmocode.de>
531 */
532function isVisiblePage($id){
533    return !isHiddenPage($id);
534}
535
536/**
537 * Format an id for output to a user
538 *
539 * Namespaces are denoted by a trailing “:*”. The root namespace is
540 * “*”. Output is escaped.
541 *
542 * @author Adrian Lang <lang@cosmocode.de>
543 */
544
545function prettyprint_id($id) {
546    if (!$id || $id === ':') {
547        return '*';
548    }
549    if ((substr($id, -1, 1) === ':')) {
550        $id .= '*';
551    }
552    return hsc($id);
553}
554