xref: /dokuwiki/inc/pageutils.php (revision e03f8da34f265d1085e18bec8aa6cd627179cbef)
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'] || $p == false) {
189        $p = curNS($id);
190        if ($p == false) {
191            return $conf['start'];
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    $files  = glob($dir.$name.'.*');
322    return $files;
323}
324
325/**
326 * returns the full path to the mediafile specified by ID
327 *
328 * The filename is URL encoded to protect Unicode chars
329 *
330 * @author Andreas Gohr <andi@splitbrain.org>
331 */
332function mediaFN($id){
333    global $conf;
334    $id = cleanID($id);
335    $id = str_replace(':','/',$id);
336    $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
337    return $fn;
338}
339
340/**
341 * Returns the full filepath to a localized textfile if local
342 * version isn't found the english one is returned
343 *
344 * @author Andreas Gohr <andi@splitbrain.org>
345 */
346function localeFN($id){
347    global $conf;
348    $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.txt';
349    if(!@file_exists($file)){
350        //fall back to english
351        $file = DOKU_INC.'inc/lang/en/'.$id.'.txt';
352    }
353    return $file;
354}
355
356/**
357 * Resolve relative paths in IDs
358 *
359 * Do not call directly use resolve_mediaid or resolve_pageid
360 * instead
361 *
362 * Partyly based on a cleanPath function found at
363 * http://www.php.net/manual/en/function.realpath.php#57016
364 *
365 * @author <bart at mediawave dot nl>
366 */
367function resolve_id($ns,$id,$clean=true){
368    global $conf;
369
370    // some pre cleaning for useslash:
371    if($conf['useslash']) $id = str_replace('/',':',$id);
372
373    // if the id starts with a dot we need to handle the
374    // relative stuff
375    if($id{0} == '.'){
376        // normalize initial dots without a colon
377        $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id);
378        // prepend the current namespace
379        $id = $ns.':'.$id;
380
381        // cleanup relatives
382        $result = array();
383        $pathA  = explode(':', $id);
384        if (!$pathA[0]) $result[] = '';
385        foreach ($pathA AS $key => $dir) {
386            if ($dir == '..') {
387                if (end($result) == '..') {
388                    $result[] = '..';
389                } elseif (!array_pop($result)) {
390                    $result[] = '..';
391                }
392            } elseif ($dir && $dir != '.') {
393                $result[] = $dir;
394            }
395        }
396        if (!end($pathA)) $result[] = '';
397        $id = implode(':', $result);
398    }elseif($ns !== false && strpos($id,':') === false){
399        //if link contains no namespace. add current namespace (if any)
400        $id = $ns.':'.$id;
401    }
402
403    if($clean) $id = cleanID($id);
404    return $id;
405}
406
407/**
408 * Returns a full media id
409 *
410 * @author Andreas Gohr <andi@splitbrain.org>
411 */
412function resolve_mediaid($ns,&$page,&$exists){
413    $page   = resolve_id($ns,$page);
414    $file   = mediaFN($page);
415    $exists = @file_exists($file);
416}
417
418/**
419 * Returns a full page id
420 *
421 * @author Andreas Gohr <andi@splitbrain.org>
422 */
423function resolve_pageid($ns,&$page,&$exists){
424    global $conf;
425    $exists = false;
426
427    //keep hashlink if exists then clean both parts
428    if (strpos($page,'#')) {
429        list($page,$hash) = explode('#',$page,2);
430    } else {
431        $hash = '';
432    }
433    $hash = cleanID($hash);
434    $page = resolve_id($ns,$page,false); // resolve but don't clean, yet
435
436    // get filename (calls clean itself)
437    $file = wikiFN($page);
438
439    // if ends with colon or slash we have a namespace link
440    if(in_array(substr($page,-1), array(':', ';')) ||
441       ($conf['useslash'] && substr($page,-1) == '/')){
442        if(page_exists($page.$conf['start'])){
443            // start page inside namespace
444            $page = $page.$conf['start'];
445            $exists = true;
446        }elseif(page_exists($page.noNS(cleanID($page)))){
447            // page named like the NS inside the NS
448            $page = $page.noNS(cleanID($page));
449            $exists = true;
450        }elseif(page_exists($page)){
451            // page like namespace exists
452            $page = $page;
453            $exists = true;
454        }else{
455            // fall back to default
456            $page = $page.$conf['start'];
457        }
458    }else{
459        //check alternative plural/nonplural form
460        if(!@file_exists($file)){
461            if( $conf['autoplural'] ){
462                if(substr($page,-1) == 's'){
463                    $try = substr($page,0,-1);
464                }else{
465                    $try = $page.'s';
466                }
467                if(page_exists($try)){
468                    $page   = $try;
469                    $exists = true;
470                }
471            }
472        }else{
473            $exists = true;
474        }
475    }
476
477    // now make sure we have a clean page
478    $page = cleanID($page);
479
480    //add hash if any
481    if(!empty($hash)) $page .= '#'.$hash;
482}
483
484/**
485 * Returns the name of a cachefile from given data
486 *
487 * The needed directory is created by this function!
488 *
489 * @author Andreas Gohr <andi@splitbrain.org>
490 *
491 * @param string $data  This data is used to create a unique md5 name
492 * @param string $ext   This is appended to the filename if given
493 * @return string       The filename of the cachefile
494 */
495function getCacheName($data,$ext=''){
496    global $conf;
497    $md5  = md5($data);
498    $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext;
499    io_makeFileDir($file);
500    return $file;
501}
502
503/**
504 * Checks a pageid against $conf['hidepages']
505 *
506 * @author Andreas Gohr <gohr@cosmocode.de>
507 */
508function isHiddenPage($id){
509    global $conf;
510    global $ACT;
511    if(empty($conf['hidepages'])) return false;
512    if($ACT == 'admin') return false;
513
514    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$id)){
515        return true;
516    }
517    return false;
518}
519
520/**
521 * Reverse of isHiddenPage
522 *
523 * @author Andreas Gohr <gohr@cosmocode.de>
524 */
525function isVisiblePage($id){
526    return !isHiddenPage($id);
527}
528
529/**
530 * Format an id for output to a user
531 *
532 * Namespaces are denoted by a trailing “:*”. The root namespace is
533 * “*”. Output is escaped.
534 *
535 * @author Adrian Lang <lang@cosmocode.de>
536 */
537
538function prettyprint_id($id) {
539    if (!$id || $id === ':') {
540        return '*';
541    }
542    if ((substr($id, -1, 1) === ':')) {
543        $id .= '*';
544    }
545    return hsc($id);
546}
547
548/**
549 * Encode a UTF-8 filename to use on any filesystem
550 *
551 * Uses the 'fnencode' option to determine encoding
552 *
553 * When the second parameter is true the string will
554 * be encoded only if non ASCII characters are detected -
555 * This makes it safe to run it multiple times on the
556 * same string (default is true)
557 *
558 * @author Andreas Gohr <andi@splitbrain.org>
559 * @see    urlencode
560 */
561function utf8_encodeFN($file,$safe=true){
562    global $conf;
563    if($conf['fnencode'] == 'utf-8') return $file;
564
565    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
566        return $file;
567    }
568
569    if($conf['fnencode'] == 'safe'){
570        return SafeFN::encode($file);
571    }
572
573    $file = urlencode($file);
574    $file = str_replace('%2F','/',$file);
575    return $file;
576}
577
578/**
579 * Decode a filename back to UTF-8
580 *
581 * Uses the 'fnencode' option to determine encoding
582 *
583 * @author Andreas Gohr <andi@splitbrain.org>
584 * @see    urldecode
585 */
586function utf8_decodeFN($file){
587    global $conf;
588    if($conf['fnencode'] == 'utf-8') return $file;
589
590    if($conf['fnencode'] == 'safe'){
591        return SafeFN::decode($file);
592    }
593
594    return urldecode($file);
595}
596
597