1<?php
2
3if (!defined('DOKU_PLUGIN')) die('meh');
4
5use dokuwiki\File\PageResolver;
6
7class siteexport_toc
8{
9    private $emptyNSToc = true;
10    private $functions = null;
11    private $NS = null;
12    public $translation = null;
13
14    public function __construct($functions, $NS)
15    {
16        $this->doDebug = !empty($_REQUEST['tocDebug']);
17        $this->emptyNSToc = !empty($_REQUEST['emptyTocElem']);
18        $this->functions = $functions;
19        $this->NS = $NS;
20    }
21
22    private function isNotEmpty( $val ) {
23        return !empty($val);
24    }
25
26    private function shortenByTranslation(&$inputURL, $deepSearch = false)
27    {
28        // Mandatory: we allways want '/' insteadf of ':' here
29        $inputURL = str_replace(':', '/', $inputURL);
30
31        $checkArray = $this->translation ? $this->translation->translations : array(noNS($this->NS));
32
33        $url = explode('/', $inputURL);
34
35        $URLcount = count($url);
36        for ($i = 0; $i < $URLcount ; $i++)
37        {
38            if (in_array($url[$i], $checkArray))
39            {
40                // Rauswerfen und weg
41                $url[$i] = '';
42                break;
43            }
44
45            if (!$deepSearch)
46            {
47                break;
48            }
49
50            // Ok, remove anyway
51            $url[$i] = '';
52        }
53
54        $inputURL = implode('/', $url);
55        $inputURL = preg_replace("$\/+$", "/", $inputURL);
56
57        if (strlen($inputURL) > 0 && substr($inputURL, 0, 1) == '/')
58        {
59            $inputURL = substr($inputURL, 1);
60        }
61
62        return $inputURL;
63    }
64
65    /**
66     * Build the Java Documentation TOC XML
67     **/
68    public function __getJavaHelpTOCXML($DATA) {
69
70        if (count($DATA) == 0) {
71            return false;
72        }
73
74        $this->debug("#### STARTING ####");
75        $TOCXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<toc>";
76        $MAPXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<map version=\"1.0\">";
77
78        // Go through the pages
79        $CHECKDATA = array();
80        $nData = $DATA;
81        $DATA = array();
82        $check = array();
83        $startPageID = null;
84
85        foreach ( $nData as $elem )
86        {
87            // Check if available
88            $anchor = ( !empty($elem['anchor']) ? '#' . $elem['anchor'] : '' );
89            $elem['url'] = $this->functions->getSiteName($elem['id'], true); // Override - we need a clean name
90            $elem['mapURL'] = $elem['url'];
91            $this->shortenByTranslation($elem['url']);
92
93            // only add an url once
94            if ( in_array($elem['url'], $CHECKDATA) ) { continue; }
95
96            if ( !isset($elem['exists']) ) {
97                $elem['exists'] = page_exists( (new PageResolver( $elem['id'] ))->resolveId($elem['id']) );
98                $this->functions->debug->message("EXISTS previously not set.", $elem, 1);
99            }
100
101            // if not there, no map ids will be generated
102            $elem['mapID'] = intval($elem['exists']) == 1 ? $this->functions->getMapID($elem['id'], $elem['anchor'], $check) : array();
103            $elem['tags'] = explode(' ', p_get_metadata($elem['id'], 'context tags', true)); // thats from the tag plugin
104            $elem['tags'] = array_filter($elem['tags'], array($this, 'isNotEmpty'));
105            $elem['tags'] = array_map(array($this->functions, 'cleanId'), $elem['tags']);
106
107            if ( empty($elem['depth']) ) {
108                $elem['depth'] = count(explode('/', $elem['url']));
109            }
110            $CHECKDATA[] = $elem['url'];
111
112            if ( $startPageID == null )
113            {
114                $startPageID = $elem['mapID'][0];
115            }
116
117            if ( empty( $elem['name'] ) || $elem['name'] == noNs($elem['id']) ) {
118                $elem['name'] = $this->functions->getSiteTitle($elem['id']);
119
120                if ( is_array($elem['mapID']) && empty( $elem['mapID'] ) ) {
121                    array_push($elem['mapID'], noNs($elem['id']));
122                }
123
124                $this->debug("no name, get site title " . $elem['name']);
125                $this->debug($elem);
126            }
127
128            // Go on building mapXML
129            $this->shortenByTranslation($elem['mapURL'], true); // true to already remove all language stuff - false if not
130            foreach ( $elem['mapID'] as $VIEWID ) {
131                $MAPXML .= "\n\t<mapID target=\"" . $VIEWID . "\" url=\"" . $elem['mapURL'] . $anchor . "\"/>";
132            }
133
134            $elem['tocNS'] = getNS(cleanID($elem['url']));
135            $elem['tocNS'] = $this->shortenByTranslation($elem['tocNS'], true);
136            $elem['tocNS'] = strlen($elem['tocNS']) > 0 ? explode('/', $elem['tocNS']) : array();
137            $this->functions->debug->message("This will be the TOC elements data:", $elem, 1);
138
139            $this->__buildTOCTree($DATA, $elem['tocNS'], $elem);
140        }
141
142        $this->debug("#### Writing TOC Tree ####");
143        $TOCXML .= $this->__writeTOCTree($DATA) . "\n</toc>";
144        $this->debug("#### DONE: Writing TOC Tree ####");
145        $MAPXML .= "\n</map>";
146
147        $this->debug($DATA);
148        $this->debug($TOCXML);
149        $this->debug($MAPXML);
150
151        return array($TOCXML, $MAPXML, $startPageID);
152    }
153
154    /**
155     * Prepare the TOC Tree
156     **/
157    private function __buildTOCTree(&$DATA, $currentNSArray, $elemToAdd)
158    {
159        global $conf;
160
161        // Actual level
162        if (empty($currentNSArray)) {
163            $elemToAdd['isStartPage'] = noNS($elemToAdd['id']) == $conf['start'];
164            // $key = empty($elemToAdd['name']) || 1==1 ? noNS($elemToAdd['id']) : $elemToAdd['name'];
165            $key = noNS($elemToAdd['id']);
166            $DATA[$key] = $elemToAdd;
167            return;
168        }
169
170        $currentLevel = array_shift($currentNSArray);
171        $nextLevel = &$DATA[$currentLevel];
172        if (empty($nextLevel)) {
173            $nextLevel = array('pages' => array());
174        } else {
175            $nextLevel = &$DATA[$currentLevel]['pages'];
176        }
177
178        $this->__buildTOCTree($nextLevel, $currentNSArray, $elemToAdd);
179    }
180
181    /**
182     * Create a single TOC Item
183     **/
184    private function __TOCItem($item, $depth, $selfClosed = true)
185    {
186        $this->debug("creating toc item");
187        $this->debug($item);
188        $targetID = $item['mapID'][0] ?? '';
189        if (empty($targetID)) {
190            $targetID = $this->functions->cleanID($item['name']);
191            $this->debug("no map ID, using: " . $targetID);
192        }
193        return "\n" . str_repeat("\t", max($depth, 0)+1) . "<tocitem target=\"" . $targetID . "\"" . (intval($item['exists']) == 1 ? " text=\"" . $item['name'] . "\"" : "") . ( array_key_exists('tags', $item) && !empty($item['tags']) ? " tags=\"" . implode(' ', $item['tags']) . "\"": "")  . ($selfClosed ? '/' : '') . ">";
194    }
195
196    /**
197     * Create a single TOC Item
198     **/
199    private function __TOCItemClose($depth)
200    {
201        return "\n" . str_repeat("\t", max($depth, 0)+1) . "</tocitem>";
202    }
203
204    /**
205     * Write the whole TOC TREE
206     **/
207    private function __writeTOCTree($CURRENTNODE, $CURRENTNODENAME = null, $DEPTH = 0) {
208        global $conf;
209
210        $XML = '';
211        $didOpenItem = false;
212        if (!is_array($CURRENTNODE) || empty($CURRENTNODE))
213        {
214            // errr … no.
215            return $XML;
216        }
217
218        // This is an element!
219        if (!empty($CURRENTNODE['id']) && empty($CURRENTNODE['pages']))
220        {
221            // This has to be an item - only -!
222            return $this->__TOCItem($CURRENTNODE, $DEPTH);
223        }
224
225        // Look for start page
226        if (!empty($CURRENTNODE[$conf['start']]))
227        {
228            // YAY! StartPage found.
229            $didOpenItem = !(count(empty($CURRENTNODE['pages']) ? $CURRENTNODE : $CURRENTNODE['pages']) == 0);
230            $XML .= $this->__TOCItem($CURRENTNODE[$conf['start']], $DEPTH, !$didOpenItem);
231            unset($CURRENTNODE[$conf['start']]);
232        } else if (!empty($CURRENTNODE['element'])) {
233            $didOpenItem = !(count($CURRENTNODE['pages']) == 0);
234            $XML .= $this->__TOCItem($CURRENTNODE['element'], $DEPTH, !$didOpenItem);
235            unset($CURRENTNODE['element']);
236        } else if ($CURRENTNODENAME != null) {
237            // We have a parent node for what is comming … lets honor that
238            $didOpenItem = !(count($CURRENTNODE) == 0);
239            $XML .= $this->__TOCItem(array('name' => $CURRENTNODENAME), $DEPTH, !$didOpenItem);
240        } else {
241            // Woohoo … empty node? do not count up!
242            $DEPTH--;
243        }
244
245        $this->debug("-- This is the current node --");
246        $this->debug($CURRENTNODE);
247
248        // Circle through the entries
249        foreach (empty($CURRENTNODE['pages']) ? $CURRENTNODE : $CURRENTNODE['pages'] as $NODENAME => $ELEM)
250        {
251            // a node should have more than only one entry … otherwise we will not tell our name!
252            $XML .= $this->__writeTOCTree($ELEM, count($ELEM) >= 1 ? ( !empty($ELEM['name']) ? $ELEM['name'] : $NODENAME ) : null, $DEPTH+1);
253        }
254
255        // Close and return
256        return $XML . ($didOpenItem ? $this->__TOCItemClose($DEPTH) : '');
257    }
258
259    /**
260     * Build the Eclipse Documentation TOC XML
261     **/
262    public function __getTOCXML($DATA, $XML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?NLS TYPE=\"org.eclipse.help.toc\"?>\n") {
263
264        $pagesArray = array();
265
266        // Go through the pages
267        foreach ($DATA as $elem) {
268
269            $site = $elem['id'];
270            $elems = explode('/', $this->functions->getSiteName($site));
271
272            // Strip Site
273            array_pop($elems);
274
275            // build the topic Tree
276            $this->__buildTopicTree($pagesArray, $elems, $site);
277        }
278
279        $XML .= $this->__addXMLTopic($pagesArray, 'toc');
280
281        return $XML;
282
283    }
284
285    /**
286     * Load the topic Tree for the TOC - recursive
287     **/
288    private function __buildTopicTree(&$PAGES, $DATA, $SITE, $INSERTDATA = null) {
289
290        if (empty($DATA) || !is_array($DATA)) {
291
292            if ($INSERTDATA == null)
293            {
294                $INSERTDATA = $SITE;
295            }
296
297            // This is already a namespace
298            if (is_array($PAGES[noNS($SITE)])) {
299                // The root already exists!
300                if (!empty($PAGES[noNS($SITE)][noNS($SITE)])) {
301                    if (strstr($PAGES[noNS($SITE)][noNS($SITE)], $SITE)) {
302                        // The SITE is in the parent Namespace, and the current Namespace has an index with same name
303                        $PAGES['__' . noNS($SITE)] = $INSERTDATA;
304                    } else {
305                        $PAGES['__' . noNS($SITE)] = $PAGES[noNS($SITE)][noNS($SITE)];
306                        $PAGES[noNS($SITE)][noNS($SITE)] = $INSERTDATA;
307                    }
308                } else {
309                    $PAGES[noNS($SITE)][noNS($SITE)] = $INSERTDATA;
310                }
311            } else {
312                // just a Page
313                $PAGES[noNS($SITE)] = $INSERTDATA;
314            }
315            return;
316        }
317
318        $NS = array_shift($DATA);
319        if (!is_array($PAGES[$NS])) $PAGES[$NS] = empty($PAGES[$NS]) ? array() : array($PAGES[$NS]);
320        $this->__buildTopicTree($PAGES[$NS], $DATA, $SITE, $INSERTDATA);
321
322        return;
323    }
324
325    /**
326     * Build the Topic Tree for TOC.xml
327     **/
328    private function __addXMLTopic($DATA, $ITEM = 'topic', $LEVEL = 0, $NODENAME = '') {
329        global $conf;
330
331        $DEPTH = str_repeat("\t", $LEVEL);
332
333        if (!is_array($DATA)) {
334            return $DEPTH . '<' . $ITEM . ' label="' . $this->functions->getSiteTitle($DATA) . '" ' . ($ITEM != 'topic' ? 'topic' : 'href') . '="' . $this->functions->getSiteName($DATA) . "\" />\n";
335        }
336        // Is array from this point on
337        list($indexTitle, $indexFile) = $this->__getIndexItem($DATA, $NODENAME);
338
339        if (empty($indexTitle)) $indexTitle = $this->functions->getSiteTitle($conf['start']);
340        if (!empty($indexFile)) $indexFile = ($ITEM != 'topic' ? 'topic' : 'href') . "=\"$indexFile\"";
341
342        $isEmptyNode = count($DATA) == 1 && empty($indexFile);
343
344        if (!$isEmptyNode && ($this->emptyNSToc || count($DATA) > 0)) {
345            $XML = "$DEPTH<$ITEM label=\"$indexTitle\" $indexFile>";
346        } else {
347            $XML = "";
348        }
349
350        if (!$isEmptyNode && count($DATA) > 0) $XML .= "\n";
351
352        foreach ($DATA as $NODENAME => $NS) {
353            $XML .= $this->__addXMLTopic($NS, (!($this->emptyNSToc || count($DATA) > 1) && $ITEM != 'topic' ? $ITEM : 'topic'), $LEVEL+(!$isEmptyNode ? 1 : 0), $NODENAME);
354        }
355
356        if (!$isEmptyNode && count($DATA) > 0) $XML .= "$DEPTH";
357        if (!$isEmptyNode && ($this->emptyNSToc || count($DATA) > 0)) {
358            $XML .= "</$ITEM>\n";
359        }
360
361        return $XML;
362    }
363
364
365    /**
366     * Get the context XML
367     **/
368    public function __getContextXML($DATA) {
369
370        $XML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?NLS TYPE=\"org.eclipse.help.context\"?>\n<contexts>\n";
371
372        $check = array();
373        foreach ($DATA as $elem)
374        {
375            $ID = $elem['id'];
376            $meta = p_get_metadata($ID, 'context', true);
377            if (empty($meta['id'])) { continue; }
378
379            $TITLE = empty($meta['title']) ? $this->functions->getSiteTitle($ID) : $meta['title'];
380
381            // support more than one view IDs ... for more than one reference
382            $VIEWIDs = $this->functions->getMapID($elem['id'], $elem['anchor'], $check);
383
384            $DESCRIPTION = $this->functions->xmlEntities(p_get_metadata($ID, 'description abstract'));
385
386            // Build topic Links
387            $url = $this->functions->getSiteName($ID);
388            $this->shortenByTranslation($url);
389
390            $TOPICS = array($url => $TITLE . " (Details)");
391            $REFS = p_get_metadata($ID, 'relation references', true);
392            if (is_array($REFS))
393            foreach ($REFS as $REL => $EXISTS) {
394                if (!$EXISTS) { continue; }
395                $TOPICS[$this->functions->getSiteName($REL)] = $this->functions->getSiteTitle($REL);
396            }
397
398            // build XML - include multi view IDs
399            foreach ($VIEWIDs as $VIEWID) {
400                $XML .= "\t<context id=\"$VIEWID\" title=\"$TITLE\">\n";
401                $XML .= "\t\t<description>$DESCRIPTION</description>\n";
402
403                foreach ($TOPICS as $URL => $LABEL) {
404                    $XML .= "\t\t<topic label=\"$LABEL\" href=\"$URL\" />\n";
405                }
406
407                $XML .= "\t</context>\n";
408            }
409        }
410
411        $XML .= "</contexts>";
412        return $XML;
413
414    }
415
416    /**
417     * Determine if this is an index - and if so, find its Title
418     **/
419    private function __getIndexItem(&$DATA, $NODENAME = '') {
420        global $conf;
421
422        if (!is_array($DATA)) { return; }
423
424        $indexTitle = '';
425        $indexFile = '';
426        foreach ($DATA as $NODE => $indexSearch) {
427            // Skip next Namespaces
428            if (is_array($indexSearch)) { continue; }
429
430            // Skip if this is not a start
431            if ($NODE != $conf['start']) { continue; }
432
433            $indexTitle = $this->functions->getSiteTitle($indexSearch);
434            $indexFile = $indexSearch;
435            unset($DATA[$NODE]);
436            break;
437        }
438
439        if (empty($indexFile) && !empty($DATA[$NODENAME])) {
440            $indexTitle = $this->functions->getSiteTitle($DATA[$NODENAME]);
441            $indexFile = $DATA[$NODENAME];
442            unset($DATA[$NODENAME]);
443        }
444
445        return array($indexTitle, $this->functions->getSiteName($indexFile));
446    }
447
448    private $doDebug = false;
449    private static $didDebug = false;
450    public function debug($data, $final = false) {
451        if ( ! $this->doDebug ) { return; }
452
453        if ( !$this->didDebug ) {
454            print "<html><pre>";
455            $this->didDebug = true;
456        }
457
458        if ( is_array($data) ) {
459            print_r($data);
460        } else {
461            print str_replace("<", "&lt;", str_replace(">", "&gt;", $data));;
462        }
463
464        print "\n\n";
465
466        if ( $final ) {
467            print "</pre></html>";
468            exit;
469        }
470    }
471}
472