xref: /plugin/siteexport/inc/toc.php (revision 24b1b4bab190747775ee8cc91cdf199b497ec9c9)
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, true);
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']) ? noNS($elemToAdd['id']) : $elemToAdd['name'];
148            $DATA[$key] = $elemToAdd;
149            return;
150        }
151
152        $currentLevel = array_shift($currentNSArray);
153        $nextLevel = &$DATA[$currentLevel];
154        if (empty($nextLevel)) {
155            $nextLevel = array('pages' => array());
156        } else {
157            $nextLevel = &$DATA[$currentLevel]['pages'];
158        }
159
160        $this->__buildTOCTree($nextLevel, $currentNSArray, $elemToAdd);
161    }
162
163    /**
164     * Create a single TOC Item
165     **/
166    private function __TOCItem($item, $depth, $selfClosed = true)
167    {
168        $this->debug($item);
169        $targetID = $item['mapID'][0];
170        if (empty($targetID)) {
171            $targetID = strtolower($item['name']);
172        }
173        return "\n" . str_repeat("\t", max($depth, 0)+1) . "<tocitem target=\"$targetID\"" . (intval($item['exists']) == 1 ? " text=\"" . $item['name'] . "\"" : "") . ($selfClosed ? '/' : '') . ">";
174    }
175
176    /**
177     * Create a single TOC Item
178     **/
179    private function __TOCItemClose($depth)
180    {
181        return "\n" . str_repeat("\t", max($depth, 0)+1) . "</tocitem>";
182    }
183
184    /**
185     * Write the whole TOC TREE
186     **/
187    private function __writeTOCTree($CURRENTNODE, $CURRENTNODENAME = null, $DEPTH = 0) {
188        global $conf;
189
190        $XML = '';
191        $didOpenItem = false;
192        if (!is_array($CURRENTNODE) || empty($CURRENTNODE))
193        {
194            // errr … no.
195            return $XML;
196        }
197
198        // This is an element!
199        if (!empty($CURRENTNODE['id']) && empty($CURRENTNODE['pages']))
200        {
201            // This has to be an item - only -!
202            return $this->__TOCItem($CURRENTNODE, $DEPTH);
203        }
204
205        // Look for start page
206        if (!empty($CURRENTNODE[$conf['start']]))
207        {
208            // YAY! StartPage found.
209            $didOpenItem = !(count(empty($CURRENTNODE['pages']) ? $CURRENTNODE : $CURRENTNODE['pages']) == 0);
210            $XML .= $this->__TOCItem($CURRENTNODE[$conf['start']], $DEPTH, !$didOpenItem);
211            unset($CURRENTNODE[$conf['start']]);
212        } else if (!empty($CURRENTNODE['element'])) {
213            $didOpenItem = !(count($CURRENTNODE['pages']) == 0);
214            $XML .= $this->__TOCItem($CURRENTNODE['element'], $DEPTH, !$didOpenItem);
215            unset($CURRENTNODE['element']);
216        } else if ($CURRENTNODENAME != null) {
217            // We have a parent node for what is comming … lets honor that
218            $didOpenItem = !(count($CURRENTNODE) == 0);
219            $XML .= $this->__TOCItem(array('name' => ucwords($CURRENTNODENAME)), $DEPTH, !$didOpenItem);
220        } else {
221            // Woohoo … empty node? do not count up!
222            $DEPTH--;
223        }
224
225        // Circle through the entries
226        foreach (empty($CURRENTNODE['pages']) ? $CURRENTNODE : $CURRENTNODE['pages'] as $NODENAME => $ELEM)
227        {
228            // a node should have more than only one entry … otherwise we will not tell our name!
229            $XML .= $this->__writeTOCTree($ELEM, count($ELEM) >= 1 ? ( !empty($ELEM['name']) ? $ELEM['name'] : $NODENAME ) : null, $DEPTH+1);
230        }
231
232        // Close and return
233        return $XML . ($didOpenItem ? $this->__TOCItemClose($DEPTH) : '');
234    }
235
236
237    function post(&$value, $key, array $additional) {
238        $inner_glue = $additional[0];
239        $prefix = isset($additional[1]) ? $additional[1] : false;
240        if ($prefix === false) $prefix = $key;
241
242        $value = $value . $inner_glue . $prefix;
243    }
244
245    /**
246     * internal Sort function
247     * @param unknown_type $a
248     * @param unknown_type $b
249     */
250    private function sortFunction($a, $b)
251    {
252        $idA = $a['id'];
253        $idB = $b['id'];
254
255        $depthA = explode(':', getNS($idA));
256        $depthB = explode(':', getNS($idB));
257
258        for ($i = 0; $i < min(count($depthA), count($depthB)); $i++)
259        {
260            $NSCMP = strcmp($depthA[$i], $depthB[$i]);
261            if ($NSCMP != 0)
262            {
263                // Something is different!
264                return $NSCMP;
265            }
266        }
267
268        // There is mor in B, than in A!
269        if (count($depthA) < count($depthB))
270        {
271            return -1;
272        } else if (count($depthA) > count($depthB))
273        {
274            // there is more in A than in B
275            return 1;
276        }
277
278        if ($NSCMP == 0)
279        {
280            // Something is different!
281            return strcmp(noNS($idA), noNS($idB));
282        }
283
284        return 0;
285    }
286
287    /**
288     * Build the Eclipse Documentation TOC XML
289     **/
290    public function __getTOCXML($DATA, $XML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?NLS TYPE=\"org.eclipse.help.toc\"?>\n") {
291
292        $pagesArray = array();
293
294        // Go through the pages
295        foreach ($DATA as $elem) {
296
297            $site = $elem['id'];
298            $elems = explode('/', $this->functions->getSiteName($site));
299
300            // Strip Site
301            array_pop($elems);
302
303            // build the topic Tree
304            $this->__buildTopicTree($pagesArray, $elems, $site);
305        }
306
307        $XML .= $this->__addXMLTopic($pagesArray, 'toc');
308
309        return $XML;
310
311    }
312
313    /**
314     * Load the topic Tree for the TOC - recursive
315     **/
316    private function __buildTopicTree(&$PAGES, $DATA, $SITE, $INSERTDATA = null) {
317
318        if (empty($DATA) || !is_array($DATA)) {
319
320            if ($INSERTDATA == null)
321            {
322                $INSERTDATA = $SITE;
323            }
324
325            // This is already a namespace
326            if (is_array($PAGES[noNS($SITE)])) {
327                // The root already exists!
328                if (!empty($PAGES[noNS($SITE)][noNS($SITE)])) {
329                    if (strstr($PAGES[noNS($SITE)][noNS($SITE)], $SITE)) {
330                        // The SITE is in the parent Namespace, and the current Namespace has an index with same name
331                        $PAGES['__' . noNS($SITE)] = $INSERTDATA;
332                    } else {
333                        $PAGES['__' . noNS($SITE)] = $PAGES[noNS($SITE)][noNS($SITE)];
334                        $PAGES[noNS($SITE)][noNS($SITE)] = $INSERTDATA;
335                    }
336                } else {
337                    $PAGES[noNS($SITE)][noNS($SITE)] = $INSERTDATA;
338                }
339            } else {
340                // just a Page
341                $PAGES[noNS($SITE)] = $INSERTDATA;
342            }
343            return;
344        }
345
346        $NS = array_shift($DATA);
347        if (!is_array($PAGES[$NS])) $PAGES[$NS] = empty($PAGES[$NS]) ? array() : array($PAGES[$NS]);
348        $this->__buildTopicTree($PAGES[$NS], $DATA, $SITE, $INSERTDATA);
349
350        return;
351    }
352
353    /**
354     * Build the Topic Tree for TOC.xml
355     **/
356    private function __addXMLTopic($DATA, $ITEM = 'topic', $LEVEL = 0, $NODENAME = '') {
357        global $conf;
358
359        $DEPTH = str_repeat("\t", $LEVEL);
360
361        if (!is_array($DATA)) {
362            return $DEPTH . '<' . $ITEM . ' label="' . $this->functions->getSiteTitle($DATA) . '" ' . ($ITEM != 'topic' ? 'topic' : 'href') . '="' . $this->functions->getSiteName($DATA) . "\" />\n";
363        }
364        // Is array from this point on
365        list($indexTitle, $indexFile) = $this->__getIndexItem($DATA, $NODENAME);
366
367        if (empty($indexTitle)) $indexTitle = $this->functions->getSiteTitle($conf['start']);
368        if (!empty($indexFile)) $indexFile = ($ITEM != 'topic' ? 'topic' : 'href') . "=\"$indexFile\"";
369
370        $isEmptyNode = count($DATA) == 1 && empty($indexFile);
371
372        if (!$isEmptyNode && ($this->emptyNSToc || count($DATA) > 0))
373        $XML = "$DEPTH<$ITEM label=\"$indexTitle\" $indexFile>";
374
375        if (!$isEmptyNode && count($DATA) > 0) $XML .= "\n";
376
377        foreach ($DATA as $NODENAME => $NS) {
378
379            $XML .= $this->__addXMLTopic($NS, (!($this->emptyNSToc || count($DATA) > 1) && $ITEM != 'topic' ? $ITEM : 'topic'), $LEVEL+(!$isEmptyNode ? 1 : 0), $NODENAME);
380
381        }
382
383        if (!$isEmptyNode && count($DATA) > 0) $XML .= "$DEPTH";
384        if (!$isEmptyNode && ($this->emptyNSToc || count($DATA) > 0)) {
385            $XML .= "</$ITEM>\n";
386        }
387
388        return $XML;
389    }
390
391
392    /**
393     * Get the context XML
394     **/
395    public function __getContextXML($DATA) {
396
397        $XML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?NLS TYPE=\"org.eclipse.help.context\"?>\n<contexts>\n";
398
399        $check = array();
400        foreach ($DATA as $elem)
401        {
402            $ID = $elem['id'];
403            $meta = p_get_metadata($ID, 'context', true);
404            if (empty($meta['id'])) { continue; }
405
406            $TITLE = empty($meta['title']) ? $this->functions->getSiteTitle($ID) : $meta['title'];
407
408            // support more than one view IDs ... for more than one reference
409            $VIEWIDs = $this->functions->getMapID($elem['id'], $elem['anchor'], $check);
410
411            $DESCRIPTION = $this->functions->xmlEntities(p_get_metadata($ID, 'description abstract'));
412
413            // Build topic Links
414            $url = $this->functions->getSiteName($ID);
415            $this->shortenByTranslation($url);
416
417            $TOPICS = array($url => $TITLE . " (Details)");
418            $REFS = p_get_metadata($ID, 'relation references', true);
419            if (is_array($REFS))
420            foreach ($REFS as $REL => $EXISTS) {
421                if (!$EXISTS) { continue; }
422                $TOPICS[$this->functions->getSiteName($REL)] = $this->functions->getSiteTitle($REL);
423            }
424
425            // build XML - include multi view IDs
426            foreach ($VIEWIDs as $VIEWID) {
427                $XML .= "\t<context id=\"$VIEWID\" title=\"$TITLE\">\n";
428                $XML .= "\t\t<description>$DESCRIPTION</description>\n";
429
430                foreach ($TOPICS as $URL => $LABEL) {
431                    $XML .= "\t\t<topic label=\"$LABEL\" href=\"$URL\" />\n";
432                }
433
434                $XML .= "\t</context>\n";
435            }
436        }
437
438        $XML .= "</contexts>";
439        return $XML;
440
441    }
442
443    /**
444     * Determine if this is an index - and if so, find its Title
445     **/
446    private function __getIndexItem(&$DATA, $NODENAME = '') {
447        global $conf;
448
449        if (!is_array($DATA)) { return; }
450
451        $indexTitle = '';
452        $indexFile = '';
453        foreach ($DATA as $NODE => $indexSearch) {
454            // Skip next Namespaces
455            if (is_array($indexSearch)) { continue; }
456
457            // Skip if this is not a start
458            if ($NODE != $conf['start']) { continue; }
459
460            $indexTitle = $this->functions->getSiteTitle($indexSearch);
461            $indexFile = $indexSearch;
462            unset($DATA[$NODE]);
463            break;
464        }
465
466        if (empty($indexFile) && !empty($DATA[$NODENAME])) {
467            $indexTitle = $this->functions->getSiteTitle($DATA[$NODENAME]);
468            $indexFile = $DATA[$NODENAME];
469            unset($DATA[$NODENAME]);
470        }
471
472        return array($indexTitle, $this->functions->getSiteName($indexFile));
473    }
474
475    private $doDebug = false;
476    private static $didDebug = false;
477    private function debug($data, $final = false) {
478        if ( ! $this->doDebug ) { return; }
479
480        if ( !$this->didDebug ) {
481            print "<html><pre>";
482            $this->didDebug = true;
483        }
484
485        if ( is_array($data) ) {
486            print_r($data);
487        } else {
488            print str_replace("<", "&lt;", str_replace(">", "&gt;", $data));;
489        }
490
491        print "\n\n";
492
493        if ( $final ) {
494            print "</pre></html>";
495            exit;
496        }
497    }
498}
499