1<?php
2/**
3 * Plugin nspages : Displays nicely a list of the pages of a namespace
4 *
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author  Guillaume Turri <guillaume.turri@gmail.com>
7 */
8if(!defined('DOKU_INC')) die();
9
10class namespaceFinder {
11    private $wantedNs;
12    private $isSafe;
13
14    function __construct($path){
15        $this->wantedNs = $this->computeWantedNs($path);
16        $this->sanitizeNs();
17    }
18
19    private function computeWantedNs($path){
20        global $ID;
21        $result = '';
22        $wantedNS = trim($path);
23        if($wantedNS == '') {
24            $wantedNS = $this->getCurrentNamespace();
25        }
26        if( $this->isRelativePath($wantedNS) ) {
27            $result = getNS($ID);
28        }
29        $result .= ':'.$wantedNS.':';
30        return $result;
31    }
32
33    private function getCurrentNamespace(){
34        return '.';
35    }
36
37    private function isRelativePath($path){
38        return $path[0] == '.';
39    }
40
41    /**
42     * Get rid of '..'.
43     * Therefore, provides a ns which passes the cleanid() function,
44     */
45    private function sanitizeNs(){
46        $ns = explode(':', $this->wantedNs);
47
48        for($i = 0; $i < count($ns); $i++) {
49            if($ns[$i] === '' || $ns[$i] === '.') {
50                array_splice($ns, $i, 1);
51                $i--;
52            } else if($ns[$i] == '..') {
53                if($i == 0) {
54                    //the first can't be '..', to stay inside 'data/pages'
55                    break;
56                } else {
57                    //simplify the path, getting rid of 'ns:..'
58                    array_splice($ns, $i - 1, 2);
59                    $i -= 2;
60                }
61            }
62        }
63
64        $this->isSafe = ($ns[0] != '..');
65        $this->wantedNs = implode(':', $ns);
66    }
67
68    function getWantedNs(){
69        return $this->wantedNs;
70    }
71
72    function isNsSafe(){
73        return $this->isSafe;
74    }
75
76    function getWantedDirectory(){
77        return utf8_encodeFN(str_replace(':', '/', $this->wantedNs));
78    }
79}
80