xref: /dokuwiki/inc/pageutils.php (revision 15851b98227ebf9671f8f7facd11426a72da6ea6)
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    /** @var Input $INPUT */
23    global $INPUT;
24    global $conf;
25    global $ACT;
26
27    $id = $INPUT->str($param);
28
29    //construct page id from request URI
30    if(empty($id) && $conf['userewrite'] == 2){
31        $request = $INPUT->server->str('REQUEST_URI');
32        $script = '';
33
34        //get the script URL
35        if($conf['basedir']){
36            $relpath = '';
37            if($param != 'id') {
38                $relpath = 'lib/exe/';
39            }
40            $script = $conf['basedir'].$relpath.utf8_basename($INPUT->server->str('SCRIPT_FILENAME'));
41
42        }elseif($INPUT->server->str('PATH_INFO')){
43            $request = $INPUT->server->str('PATH_INFO');
44        }elseif($INPUT->server->str('SCRIPT_NAME')){
45            $script = $INPUT->server->str('SCRIPT_NAME');
46        }elseif($INPUT->server->str('DOCUMENT_ROOT') && $INPUT->server->str('SCRIPT_FILENAME')){
47            $script = preg_replace ('/^'.preg_quote($INPUT->server->str('DOCUMENT_ROOT'),'/').'/','',
48                    $INPUT->server->str('SCRIPT_FILENAME'));
49            $script = '/'.$script;
50        }
51
52        //clean script and request (fixes a windows problem)
53        $script  = preg_replace('/\/\/+/','/',$script);
54        $request = preg_replace('/\/\/+/','/',$request);
55
56        //remove script URL and Querystring to gain the id
57        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
58            $id = preg_replace ('/\?.*/','',$match[1]);
59        }
60        $id = urldecode($id);
61        //strip leading slashes
62        $id = preg_replace('!^/+!','',$id);
63    }
64
65    // Namespace autolinking from URL
66    if(substr($id,-1) == ':' || ($conf['useslash'] && substr($id,-1) == '/')){
67        if(page_exists($id.$conf['start'])){
68            // start page inside namespace
69            $id = $id.$conf['start'];
70        }elseif(page_exists($id.noNS(cleanID($id)))){
71            // page named like the NS inside the NS
72            $id = $id.noNS(cleanID($id));
73        }elseif(page_exists($id)){
74            // page like namespace exists
75            $id = substr($id,0,-1);
76        }else{
77            // fall back to default
78            $id = $id.$conf['start'];
79        }
80        if (isset($ACT) && $ACT === 'show') send_redirect(wl($id,'',true));
81    }
82
83    if($clean) $id = cleanID($id);
84    if(empty($id) && $param=='id') $id = $conf['start'];
85
86    return $id;
87}
88
89/**
90 * Remove unwanted chars from ID
91 *
92 * Cleans a given ID to only use allowed characters. Accented characters are
93 * converted to unaccented ones
94 *
95 * @author Andreas Gohr <andi@splitbrain.org>
96 * @param  string  $raw_id    The pageid to clean
97 * @param  boolean $ascii     Force ASCII
98 * @return string cleaned id
99 */
100function cleanID($raw_id,$ascii=false){
101    global $conf;
102    static $sepcharpat = null;
103
104    global $cache_cleanid;
105    $cache = & $cache_cleanid;
106
107    // check if it's already in the memory cache
108    if (isset($cache[(string)$raw_id])) {
109        return $cache[(string)$raw_id];
110    }
111
112    $sepchar = $conf['sepchar'];
113    if($sepcharpat == null) // build string only once to save clock cycles
114        $sepcharpat = '#\\'.$sepchar.'+#';
115
116    $id = trim((string)$raw_id);
117    $id = utf8_strtolower($id);
118
119    //alternative namespace seperator
120    if($conf['useslash']){
121        $id = strtr($id,';/','::');
122    }else{
123        $id = strtr($id,';/',':'.$sepchar);
124    }
125
126    if($conf['deaccent'] == 2 || $ascii) $id = utf8_romanize($id);
127    if($conf['deaccent'] || $ascii) $id = utf8_deaccent($id,-1);
128
129    //remove specials
130    $id = utf8_stripspecials($id,$sepchar,'\*');
131
132    if($ascii) $id = utf8_strip($id);
133
134    //clean up
135    $id = preg_replace($sepcharpat,$sepchar,$id);
136    $id = preg_replace('#:+#',':',$id);
137    $id = trim($id,':._-');
138    $id = preg_replace('#:[:\._\-]+#',':',$id);
139    $id = preg_replace('#[:\._\-]+:#',':',$id);
140
141    $cache[(string)$raw_id] = $id;
142    return($id);
143}
144
145/**
146 * Return namespacepart of a wiki ID
147 *
148 * @author Andreas Gohr <andi@splitbrain.org>
149 *
150 * @param string $id
151 * @return string
152 */
153function getNS($id){
154    $pos = strrpos((string)$id,':');
155    if($pos!==false){
156        return substr((string)$id,0,$pos);
157    }
158    return '';
159}
160
161/**
162 * Returns the ID without the namespace
163 *
164 * @author Andreas Gohr <andi@splitbrain.org>
165 *
166 * @param string $id
167 * @return string
168 */
169function noNS($id) {
170    $pos = strrpos($id, ':');
171    if ($pos!==false) {
172        return substr($id, $pos+1);
173    } else {
174        return $id;
175    }
176}
177
178/**
179 * Returns the current namespace
180 *
181 * @author Nathan Fritz <fritzn@crown.edu>
182 */
183function curNS($id) {
184    return noNS(getNS($id));
185}
186
187/**
188 * Returns the ID without the namespace or current namespace for 'start' pages
189 *
190 * @author Nathan Fritz <fritzn@crown.edu>
191 */
192function noNSorNS($id) {
193    global $conf;
194
195    $p = noNS($id);
196    if ($p == $conf['start'] || $p == false) {
197        $p = curNS($id);
198        if ($p == false) {
199            return $conf['start'];
200        }
201    }
202    return $p;
203}
204
205/**
206 * Creates a XHTML valid linkid from a given headline title
207 *
208 * @param string  $title   The headline title
209 * @param array|bool   $check   Existing IDs (title => number)
210 * @return string the title
211 * @author Andreas Gohr <andi@splitbrain.org>
212 */
213function sectionID($title,&$check) {
214    $title = str_replace(array(':','.'),'',cleanID($title));
215    $new = ltrim($title,'0123456789_-');
216    if(empty($new)){
217        $title = 'section'.preg_replace('/[^0-9]+/','',$title); //keep numbers from headline
218    }else{
219        $title = $new;
220    }
221
222    if(is_array($check)){
223        // make sure tiles are unique
224        if (!array_key_exists ($title,$check)) {
225            $check[$title] = 0;
226        } else {
227            $title .= ++ $check[$title];
228        }
229    }
230
231    return $title;
232}
233
234
235/**
236 * Wiki page existence check
237 *
238 * parameters as for wikiFN
239 *
240 * @author Chris Smith <chris@jalakai.co.uk>
241 */
242function page_exists($id,$rev='',$clean=true) {
243    return @file_exists(wikiFN($id,$rev,$clean));
244}
245
246/**
247 * returns the full path to the datafile specified by ID and optional revision
248 *
249 * The filename is URL encoded to protect Unicode chars
250 *
251 * @param  $raw_id  string   id of wikipage
252 * @param  $rev     string   page revision, empty string for current
253 * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
254 *                           when $id is guaranteed to have been cleaned already.
255 * @return string full path
256 *
257 * @author Andreas Gohr <andi@splitbrain.org>
258 */
259function wikiFN($raw_id,$rev='',$clean=true){
260    global $conf;
261
262    global $cache_wikifn;
263    $cache = & $cache_wikifn;
264
265    if (isset($cache[$raw_id]) && isset($cache[$raw_id][$rev])) {
266        return $cache[$raw_id][$rev];
267    }
268
269    $id = $raw_id;
270
271    if ($clean) $id = cleanID($id);
272    $id = str_replace(':','/',$id);
273    if(empty($rev)){
274        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
275    }else{
276        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
277        if($conf['compression']){
278            //test for extensions here, we want to read both compressions
279            if (@file_exists($fn . '.gz')){
280                $fn .= '.gz';
281            }else if(@file_exists($fn . '.bz2')){
282                $fn .= '.bz2';
283            }else{
284                //file doesnt exist yet, so we take the configured extension
285                $fn .= '.' . $conf['compression'];
286            }
287        }
288    }
289
290    if (!isset($cache[$raw_id])) { $cache[$raw_id] = array(); }
291    $cache[$raw_id][$rev] = $fn;
292    return $fn;
293}
294
295/**
296 * Returns the full path to the file for locking the page while editing.
297 *
298 * @author Ben Coburn <btcoburn@silicodon.net>
299 */
300function wikiLockFN($id) {
301    global $conf;
302    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
303}
304
305
306/**
307 * returns the full path to the meta file specified by ID and extension
308 *
309 * @author Steven Danz <steven-danz@kc.rr.com>
310 */
311function metaFN($id,$ext){
312    global $conf;
313    $id = cleanID($id);
314    $id = str_replace(':','/',$id);
315    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
316    return $fn;
317}
318
319/**
320 * returns the full path to the media's meta file specified by ID and extension
321 *
322 * @author Kate Arzamastseva <pshns@ukr.net>
323 */
324function mediaMetaFN($id,$ext){
325    global $conf;
326    $id = cleanID($id);
327    $id = str_replace(':','/',$id);
328    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
329    return $fn;
330}
331
332/**
333 * returns an array of full paths to all metafiles of a given ID
334 *
335 * @author Esther Brunner <esther@kaffeehaus.ch>
336 * @author Michael Hamann <michael@content-space.de>
337 */
338function metaFiles($id){
339    $basename = metaFN($id, '');
340    $files    = glob($basename.'.*', GLOB_MARK);
341    // filter files like foo.bar.meta when $id == 'foo'
342    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
343}
344
345/**
346 * returns the full path to the mediafile specified by ID
347 *
348 * The filename is URL encoded to protect Unicode chars
349 *
350 * @author Andreas Gohr <andi@splitbrain.org>
351 * @author Kate Arzamastseva <pshns@ukr.net>
352 */
353function mediaFN($id, $rev=''){
354    global $conf;
355    $id = cleanID($id);
356    $id = str_replace(':','/',$id);
357    if(empty($rev)){
358        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
359    }else{
360        $ext = mimetype($id);
361        $name = substr($id,0, -1*strlen($ext[0])-1);
362        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
363    }
364    return $fn;
365}
366
367/**
368 * Returns the full filepath to a localized file if local
369 * version isn't found the english one is returned
370 *
371 * @param  string $id  The id of the local file
372 * @param  string $ext The file extension (usually txt)
373 * @return string full filepath to localized file
374 * @author Andreas Gohr <andi@splitbrain.org>
375 */
376function localeFN($id,$ext='txt'){
377    global $conf;
378    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
379    if(!@file_exists($file)){
380        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
381        if(!@file_exists($file)){
382            //fall back to english
383            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
384        }
385    }
386    return $file;
387}
388
389/**
390 * Resolve relative paths in IDs
391 *
392 * Do not call directly use resolve_mediaid or resolve_pageid
393 * instead
394 *
395 * Partyly based on a cleanPath function found at
396 * http://www.php.net/manual/en/function.realpath.php#57016
397 *
398 * @author <bart at mediawave dot nl>
399 */
400function resolve_id($ns,$id,$clean=true){
401    global $conf;
402
403    // some pre cleaning for useslash:
404    if($conf['useslash']) $id = str_replace('/',':',$id);
405
406    // if the id starts with a dot we need to handle the
407    // relative stuff
408    if($id && $id{0} == '.'){
409        // normalize initial dots without a colon
410        $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id);
411        // prepend the current namespace
412        $id = $ns.':'.$id;
413
414        // cleanup relatives
415        $result = array();
416        $pathA  = explode(':', $id);
417        if (!$pathA[0]) $result[] = '';
418        foreach ($pathA AS $key => $dir) {
419            if ($dir == '..') {
420                if (end($result) == '..') {
421                    $result[] = '..';
422                } elseif (!array_pop($result)) {
423                    $result[] = '..';
424                }
425            } elseif ($dir && $dir != '.') {
426                $result[] = $dir;
427            }
428        }
429        if (!end($pathA)) $result[] = '';
430        $id = implode(':', $result);
431    }elseif($ns !== false && strpos($id,':') === false){
432        //if link contains no namespace. add current namespace (if any)
433        $id = $ns.':'.$id;
434    }
435
436    if($clean) $id = cleanID($id);
437    return $id;
438}
439
440/**
441 * Returns a full media id
442 *
443 * @author Andreas Gohr <andi@splitbrain.org>
444 */
445function resolve_mediaid($ns,&$page,&$exists){
446    $page   = resolve_id($ns,$page);
447    $file   = mediaFN($page);
448    $exists = @file_exists($file);
449}
450
451/**
452 * Returns a full page id
453 *
454 * @author Andreas Gohr <andi@splitbrain.org>
455 */
456function resolve_pageid($ns,&$page,&$exists){
457    global $conf;
458    global $ID;
459    $exists = false;
460
461    //empty address should point to current page
462    if ($page === "") {
463        $page = $ID;
464    }
465
466    //keep hashlink if exists then clean both parts
467    if (strpos($page,'#')) {
468        list($page,$hash) = explode('#',$page,2);
469    } else {
470        $hash = '';
471    }
472    $hash = cleanID($hash);
473    $page = resolve_id($ns,$page,false); // resolve but don't clean, yet
474
475    // get filename (calls clean itself)
476    $file = wikiFN($page);
477
478    // if ends with colon or slash we have a namespace link
479    if(in_array(substr($page,-1), array(':', ';')) ||
480       ($conf['useslash'] && substr($page,-1) == '/')){
481        if(page_exists($page.$conf['start'])){
482            // start page inside namespace
483            $page = $page.$conf['start'];
484            $exists = true;
485        }elseif(page_exists($page.noNS(cleanID($page)))){
486            // page named like the NS inside the NS
487            $page = $page.noNS(cleanID($page));
488            $exists = true;
489        }elseif(page_exists($page)){
490            // page like namespace exists
491            $page = $page;
492            $exists = true;
493        }else{
494            // fall back to default
495            $page = $page.$conf['start'];
496        }
497    }else{
498        //check alternative plural/nonplural form
499        if(!@file_exists($file)){
500            if( $conf['autoplural'] ){
501                if(substr($page,-1) == 's'){
502                    $try = substr($page,0,-1);
503                }else{
504                    $try = $page.'s';
505                }
506                if(page_exists($try)){
507                    $page   = $try;
508                    $exists = true;
509                }
510            }
511        }else{
512            $exists = true;
513        }
514    }
515
516    // now make sure we have a clean page
517    $page = cleanID($page);
518
519    //add hash if any
520    if(!empty($hash)) $page .= '#'.$hash;
521}
522
523/**
524 * Returns the name of a cachefile from given data
525 *
526 * The needed directory is created by this function!
527 *
528 * @author Andreas Gohr <andi@splitbrain.org>
529 *
530 * @param string $data  This data is used to create a unique md5 name
531 * @param string $ext   This is appended to the filename if given
532 * @return string       The filename of the cachefile
533 */
534function getCacheName($data,$ext=''){
535    global $conf;
536    $md5  = md5($data);
537    $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext;
538    io_makeFileDir($file);
539    return $file;
540}
541
542/**
543 * Checks a pageid against $conf['hidepages']
544 *
545 * @author Andreas Gohr <gohr@cosmocode.de>
546 */
547function isHiddenPage($id){
548    $data = array(
549        'id' => $id,
550        'hidden' => false
551    );
552    trigger_event('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
553    return $data['hidden'];
554}
555
556/**
557 * callback checks if page is hidden
558 *
559 * @param array $data event data    see isHiddenPage()
560 */
561function _isHiddenPage(&$data) {
562    global $conf;
563    global $ACT;
564
565    if ($data['hidden']) return;
566    if(empty($conf['hidepages'])) return;
567    if($ACT == 'admin') return;
568
569    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$data['id'])){
570        $data['hidden'] = true;
571    }
572}
573
574/**
575 * Reverse of isHiddenPage
576 *
577 * @author Andreas Gohr <gohr@cosmocode.de>
578 */
579function isVisiblePage($id){
580    return !isHiddenPage($id);
581}
582
583/**
584 * Format an id for output to a user
585 *
586 * Namespaces are denoted by a trailing “:*”. The root namespace is
587 * “*”. Output is escaped.
588 *
589 * @author Adrian Lang <lang@cosmocode.de>
590 */
591
592function prettyprint_id($id) {
593    if (!$id || $id === ':') {
594        return '*';
595    }
596    if ((substr($id, -1, 1) === ':')) {
597        $id .= '*';
598    }
599    return hsc($id);
600}
601
602/**
603 * Encode a UTF-8 filename to use on any filesystem
604 *
605 * Uses the 'fnencode' option to determine encoding
606 *
607 * When the second parameter is true the string will
608 * be encoded only if non ASCII characters are detected -
609 * This makes it safe to run it multiple times on the
610 * same string (default is true)
611 *
612 * @author Andreas Gohr <andi@splitbrain.org>
613 * @see    urlencode
614 */
615function utf8_encodeFN($file,$safe=true){
616    global $conf;
617    if($conf['fnencode'] == 'utf-8') return $file;
618
619    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
620        return $file;
621    }
622
623    if($conf['fnencode'] == 'safe'){
624        return SafeFN::encode($file);
625    }
626
627    $file = urlencode($file);
628    $file = str_replace('%2F','/',$file);
629    return $file;
630}
631
632/**
633 * Decode a filename back to UTF-8
634 *
635 * Uses the 'fnencode' option to determine encoding
636 *
637 * @author Andreas Gohr <andi@splitbrain.org>
638 * @see    urldecode
639 */
640function utf8_decodeFN($file){
641    global $conf;
642    if($conf['fnencode'] == 'utf-8') return $file;
643
644    if($conf['fnencode'] == 'safe'){
645        return SafeFN::decode($file);
646    }
647
648    return urldecode($file);
649}
650
651/**
652 * Find a page in the current namespace (determined from $ID) or any
653 * higher namespace
654 *
655 * Used for sidebars, but can be used other stuff as well
656 *
657 * @todo   add event hook
658 * @param  string $page the pagename you're looking for
659 * @return string|false the full page id of the found page, false if any
660 */
661function page_findnearest($page){
662    if (!$page) return false;
663    global $ID;
664
665    $ns = $ID;
666    do {
667        $ns = getNS($ns);
668        $pageid = ltrim("$ns:$page",':');
669        if(page_exists($pageid)){
670            return $pageid;
671        }
672    } while($ns);
673
674    return false;
675}
676