xref: /plugin/simplenavi/syntax.php (revision e75a33bf67169624ba61a7d08f13132b1856e309)
1<?php
2
3use dokuwiki\File\PageResolver;
4use dokuwiki\Utf8\Sort;
5
6/**
7 * DokuWiki Plugin simplenavi (Syntax Component)
8 *
9 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
10 * @author  Andreas Gohr <gohr@cosmocode.de>
11 */
12class syntax_plugin_simplenavi extends DokuWiki_Syntax_Plugin
13{
14    private $startpages = [];
15
16    /** @inheritdoc */
17    public function getType()
18    {
19        return 'substition';
20    }
21
22    /** @inheritdoc */
23    public function getPType()
24    {
25        return 'block';
26    }
27
28    /** @inheritdoc */
29    public function getSort()
30    {
31        return 155;
32    }
33
34    /** @inheritdoc */
35    public function connectTo($mode)
36    {
37        $this->Lexer->addSpecialPattern('{{simplenavi>[^}]*}}', $mode, 'plugin_simplenavi');
38    }
39
40    /** @inheritdoc */
41    public function handle($match, $state, $pos, Doku_Handler $handler)
42    {
43        return explode(' ', substr($match, 13, -2));
44    }
45
46    /** @inheritdoc */
47    public function render($format, Doku_Renderer $renderer, $data)
48    {
49        if ($format != 'xhtml') return false;
50
51        global $conf;
52        global $INFO;
53        $renderer->nocache();
54
55        // first data is namespace, rest is options
56        $ns = array_shift($data);
57        if ($ns && $ns[0] === '.') {
58            // resolve relative to current page
59            $ns = getNS((new PageResolver($INFO['id']))->resolveId("$ns:xxx"));
60        } else {
61            $ns = cleanID($ns);
62        }
63        // convert to path
64        $ns = utf8_encodeFN(str_replace(':', '/', $ns));
65
66        $items = $this->getSortedItems(
67            $ns,
68            $INFO['id'],
69            $this->getConf('usetitle'),
70            $this->getConf('natsort')
71        );
72
73        $class = 'plugin__simplenavi';
74        if (in_array('filter', $data)) $class .= ' plugin__simplenavi_filter';
75
76        $renderer->doc .= '<div class="' . $class . '">';
77        $renderer->doc .= html_buildlist($items, 'idx', [$this, 'cbList'], [$this, 'cbListItem']);
78        $renderer->doc .= '</div>';
79
80        return true;
81    }
82
83    /**
84     * Fetch the items to display
85     *
86     * This returns a flat list suitable for html_buildlist()
87     *
88     * @param string $ns the namespace to search in
89     * @param string $current the current page, the tree will be expanded to this
90     * @param bool $useTitle Sort by the title instead of the ID?
91     * @param bool $useNatSort Use natural sorting or just sort by ASCII?
92     * @return array
93     */
94    public function getSortedItems($ns, $current, $useTitle, $useNatSort)
95    {
96        global $conf;
97
98        // execute search using our own callback
99        $items = [];
100        search(
101            $items,
102            $conf['datadir'],
103            [$this, 'cbSearch'],
104            [
105                'currentID' => $current,
106                'usetitle' => $useTitle,
107            ],
108            $ns,
109            1,
110            '' // no sorting, we do ourselves
111        );
112
113        // split into separate levels
114        $current = 1;
115        $parents = [];
116        $levels = [];
117        foreach ($items as $idx => $item) {
118            if ($current < $item['level']) {
119                // previous item was the parent
120                $parents[] = array_key_last($levels[$current]);
121            }
122            $current = $item['level'];
123            $levels[$item['level']][$idx] = $item;
124        }
125
126        // sort each level separately
127        foreach ($levels as $level => $items) {
128            uasort($items, function ($a, $b) use ($useNatSort) {
129                return $this->itemComparator($a, $b, $useNatSort);
130            });
131            $levels[$level] = $items;
132        }
133
134        // merge levels into a flat list again
135        $levels = array_reverse($levels, true);
136        foreach ($levels as $level => $items) {
137            if ($level == 1) break;
138
139            $parent = array_pop($parents);
140            $pos = array_search($parent, array_keys($levels[$level - 1])) + 1;
141
142            $levels[$level - 1] = array_slice($levels[$level - 1], 0, $pos, true) +
143                $levels[$level] +
144                array_slice($levels[$level - 1], $pos, null, true);
145        }
146        $items = $levels[1];
147
148
149        return $items;
150    }
151
152    /**
153     * Compare two items
154     *
155     * @param array $a
156     * @param array $b
157     * @param bool $useNatSort
158     * @return int
159     */
160    public function itemComparator($a, $b, $useNatSort)
161    {
162        if ($useNatSort) {
163            return Sort::strcmp($a['title'], $b['title']);
164        } else {
165            return strcmp($a['title'], $b['title']);
166        }
167    }
168
169
170    /**
171     * Create a list openening
172     *
173     * @param array $item
174     * @return string
175     * @see html_buildlist()
176     */
177    public function cbList($item)
178    {
179        global $INFO;
180
181        if (($item['type'] == 'd' && $item['open']) || $INFO['id'] == $item['id']) {
182            return '<strong>' . html_wikilink(':' . $item['id'], $item['title']) . '</strong>';
183        } else {
184            return html_wikilink(':' . $item['id'], $item['title']);
185        }
186
187    }
188
189    /**
190     * Create a list item
191     *
192     * @param array $item
193     * @return string
194     * @see html_buildlist()
195     */
196    public function cbListItem($item)
197    {
198        if ($item['type'] == "f") {
199            return '<li class="level' . $item['level'] . '">';
200        } elseif ($item['open']) {
201            return '<li class="open">';
202        } else {
203            return '<li class="closed">';
204        }
205    }
206
207    /**
208     * Custom search callback
209     *
210     * @param $data
211     * @param $base
212     * @param $file
213     * @param $type
214     * @param $lvl
215     * @param array $opts - currentID is the currently shown page
216     * @return bool
217     */
218    public function cbSearch(&$data, $base, $file, $type, $lvl, $opts)
219    {
220        global $conf;
221        $return = true;
222
223        $id = pathID($file);
224
225        if ($type == 'd' && !(
226                preg_match('#^' . $id . '(:|$)#', $opts['currentID']) ||
227                preg_match('#^' . $id . '(:|$)#', getNS($opts['currentID']))
228
229            )) {
230            //add but don't recurse
231            $return = false;
232        } elseif ($type == 'f' && (!empty($opts['nofiles']) || substr($file, -4) != '.txt')) {
233            //don't add
234            return false;
235        }
236
237        // for sneaky index, check access to the namespace's start page
238        if ($type == 'd' && $conf['sneaky_index']) {
239            $sp = (new PageResolver(''))->resolveId($id . ':');
240            if (auth_quickaclcheck($sp) < AUTH_READ) {
241                return false;
242            }
243        }
244
245        if ($type == 'd') {
246            // link directories to their start pages
247            $original = $id;
248            $id = "$id:";
249            $id = (new PageResolver(''))->resolveId($id);
250            $this->startpages[$id] = 1;
251
252            // if the resolve id is in the same namespace as the original it's a start page named like the dir
253            if (getNS($original) == getNS($id)) {
254                $useNS = $original;
255            }
256
257        } elseif (!empty($this->startpages[$id])) {
258            // skip already shown start pages
259            return false;
260        } elseif (noNS($id) == $conf['start']) {
261            // skip the main start page
262            return false;
263        }
264
265        //check hidden
266        if (isHiddenPage($id)) {
267            return false;
268        }
269
270        //check ACL
271        if ($type == 'f' && auth_quickaclcheck($id) < AUTH_READ) {
272            return false;
273        }
274
275        $data[$id] = [
276            'id' => $id,
277            'type' => $type,
278            'level' => $lvl,
279            'open' => $return,
280            'title' => $this->getTitle($id, $opts['usetitle']),
281            'ns' => $useNS ?? (string)getNS($id),
282        ];
283
284        return $return;
285    }
286
287    /**
288     * Get the title for the given page ID
289     *
290     * @param string $id
291     * @param bool $usetitle - use the first heading as title
292     * @return string
293     */
294    protected function getTitle($id, $usetitle)
295    {
296        global $conf;
297
298        if ($usetitle) {
299            $p = p_get_first_heading($id);
300            if (!empty($p)) return $p;
301        }
302
303        $p = noNS($id);
304        if ($p == $conf['start'] || !$p) {
305            $p = noNS(getNS($id));
306            if (!$p) {
307                return $conf['start'];
308            }
309        }
310        return $p;
311    }
312}
313