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