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