xref: /plugin/siteexport/syntax/toc.php (revision 300ce4a20f600a2031826a8c1d16bf3aa359b53d)
1<?php
2/**
3 * Search with Scopes
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     i-net software <tools@inetsoftware.de>
7 * @author     Gerry Weissbach <gweissbach@inetsoftware.de>
8 */
9
10// must be run within Dokuwiki
11if (!defined('DOKU_INC')) die();
12if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
13
14require_once(DOKU_PLUGIN . 'syntax.php');
15
16class syntax_plugin_siteexport_toc extends DokuWiki_Syntax_Plugin {
17
18    private $insideToc = false;
19    private $savedToc = array();
20    private $options = array();
21
22    private $mergedPages = array();
23    private $includedPages = array();
24    private $merghintIds = array();
25
26    function getType() { return 'protected'; }
27    function getPType() { return 'block'; }
28    function getAllowedTypes() { return array('container'); }
29    function getSort() { return 100; }
30
31    /**
32     * Connect pattern to lexer
33     */
34    function connectTo($mode) {
35        $this->Lexer->addEntryPattern('<toc>(?=.*?</toc>)', $mode, 'plugin_siteexport_toc');
36        $this->Lexer->addEntryPattern('<toc .+?>(?=.*?</toc>)', $mode, 'plugin_siteexport_toc');
37        $this->Lexer->addSpecialPattern("\[\[.+?\]\]", $mode, 'plugin_siteexport_toc');
38    }
39
40    function postConnect() {
41        $this->Lexer->addExitPattern('</toc.*?>', 'plugin_siteexport_toc');
42    }
43
44    function handle($match, $state, $pos, Doku_Handler $handler) {
45        global $ID, $INFO;
46
47        switch ($state) {
48            case DOKU_LEXER_ENTER:
49
50                $this->insideToc = true;
51
52                $this->options = explode(' ', substr($match, 5, -1));
53
54                return array('start' => true, 'pos' => $pos, 'options' => $this->options);
55                break;
56
57            case DOKU_LEXER_SPECIAL:
58
59                if ($this->insideToc) {
60
61                    $link = preg_replace(array('/^\[\[/', '/\]\]$/u'), '', $match);
62                    // Split title from URL
63                    $link = explode('|', $link, 2);
64                    if (!isset($link[1])) {
65                        $link[1] = NULL;
66                    } else if (preg_match('/^\{\{[^\}]+\}\}$/', $link[1])) {
67                        // If the title is an image, convert it to an array containing the image details
68                        $link[1] = Doku_Handler_Parse_Media($link[1]);
69                    }
70                    $link[0] = trim($link[0]);
71
72                    if (!(preg_match('/^[a-zA-Z0-9\.]+>{1}.*$/u', $link[0]) ||
73                    preg_match('/^\\\\\\\\[\w.:?\-;,]+?\\\\/u', $link[0]) ||
74                    preg_match('#^([a-z0-9\-\.+]+?)://#i', $link[0]) ||
75                    preg_match('<' . PREG_PATTERN_VALID_EMAIL . '>', $link[0]) ||
76                    preg_match('!^#.+!', $link[0]))
77                    ) {
78
79                        // Get current depth from call stack
80                        $depth = 1;
81                        if ($handler->CallWriter instanceof Doku_Handler_List) {
82
83                            $calls = array_reverse($handler->CallWriter->calls);
84                            $call = $calls[0];
85                            foreach ($calls as $item) {
86                                if (in_array($item[0], array('list_item', 'list_open'))) { $call = $item; break; }
87                            }
88
89                            $depth = $handler->CallWriter->interpretSyntax($call[1][0], $listType)-1; // Minus one because of plus one inside the interpret function
90                        }
91
92                        if (empty($link[0])) { break; } // No empty elements. This would lead to problems
93                        return array($link[0], $link[1], $depth);
94                        break;
95                    } else {
96                        // use parser! - but with another p
97                        $handler->internallink($match, $state, $pos);
98                    }
99                } else {
100                    // use parser!
101                    $handler->internallink($match, $state, $pos);
102                }
103
104                return false;
105            case DOKU_LEXER_UNMATCHED:
106
107                $handler->_addCall('cdata', array($match), $pos);
108
109                return false;
110                break;
111            case DOKU_LEXER_EXIT:
112
113                $this->insideToc = false;
114                return 'save__meta';
115                break;
116        }
117        return false;
118    }
119
120    function render($mode, Doku_Renderer $renderer, $data) {
121        global $ID, $lang, $INFO;
122
123        list($SID, $NAME, $DEPTH) = $data;
124
125        resolve_pageid(getNS($ID), $SID, $exists);
126//        $SID = cleanID($SID); // hier kein cleanID, da sonst moeglicherweise der anker verloren geht
127
128        //    Render XHTML and ODT
129        if ($mode == 'xhtml' || $mode == 'odt') {
130
131            // TOC Title
132            if (is_array($data) && $data['start'] == true) {
133
134                if (is_Array($data['options'])) {
135                    foreach ($data['options'] as $opt) {
136                        switch ($opt) {
137                            case 'description' : $renderer->meta['sitetoc']['showDescription'] = true; break;
138                            case 'notoc' : $renderer->meta['sitetoc']['noTOC'] = true; break;
139                            case 'merge' : $renderer->meta['sitetoc']['mergeDoc'] = true; break;
140                            case 'nohead' : $renderer->meta['sitetoc']['noTocHeader'] = true; break;
141                            case 'mergeheader' : $renderer->meta['sitetoc']['mergeHeader'] = true; break;
142                            case 'pagebreak' : $renderer->meta['sitetoc']['pagebreak'] = true; break;
143                        }
144                    }
145                }
146
147                $renderer->section_open("1 sitetoc");
148                if ($renderer->meta['sitetoc']['noTocHeader'] === false) {
149                    $renderer->header($lang['toc'], 1, $data['pos']);
150                }
151
152                return true;
153            } else
154
155            // All Output has been done
156            if (!is_array($data) && $data == 'save__meta') {
157
158                // Close TOC
159                $renderer->section_close();
160
161                if ($renderer->meta['sitetoc']['noTOC'] === true) {
162                    $renderer->doc = preg_replace("/<div.*?sitetoc.*?$/si", "", $renderer->doc);
163                }
164
165                // If this is not set, we may have it as Metadata
166                if (!$this->mergedPages && $renderer->meta['sitetoc']['mergeDoc']) {
167                    $toc = $renderer->meta['sitetoc']['siteexportTOC'];
168
169                    if (is_array($toc)) {
170                        foreach ($toc as $tocItem) {
171                            $this->mergedPages[] = array($tocItem['id'], $tocItem['depth']);
172                        }
173                    }
174
175                }
176
177                // If there is some data to be merged
178                if (count($this->mergedPages) > 0) {
179
180                    $renderer->doc = ''; // Start fresh!
181
182                    $renderer->section_open("1 mergedsite");
183
184                    // Prepare lookup Array
185                    foreach ($this->mergedPages as $tocItem) {
186                        $this->includedPages[] = array_shift(explode('#', $tocItem[0]));
187                    }
188
189                    // Load the instructions
190                    $instr = array();
191                    $mergeHint = null;
192                    foreach ($this->mergedPages as $tocElement) {
193
194                        list($tocItem, $depth) = $tocElement;
195                        $file = wikiFN($tocItem);
196
197                        if (@file_exists($file)) {
198                            $instructions = p_cached_instructions($file, false, $tocItem);
199                        } else {
200                            $instructions = p_get_instructions(io_readWikiPage($file, $tocItem));
201                        }
202
203                        // Convert Link and header instructions
204                        $instructions = $this->_convertInstructions($instructions, $addID, $renderer, $depth);
205
206                        if ($renderer->meta['sitetoc']['mergeHeader'] && !empty($instr)) {
207                            // get a hint for merged pages
208                            if ( !empty( $instr ) ) {
209                                // only if the first section is already there
210                                $mergeHint = p_get_metadata( $tocItem, 'mergehint', METADATA_RENDER_USING_SIMPLE_CACHE );
211                                if ( empty( $mergeHint) ) { $mergeHint = p_get_metadata( $tocItem, 'thema', METADATA_RENDER_USING_SIMPLE_CACHE ); }
212                                if ( empty( $mergeHint) ) { $mergeHint = tpl_pagetitle( $tocItem, true ); }
213                            }
214
215                            // Merge
216                            $instr = $this->_mergeWithHeaders($instr, $instructions, 1, $mergeHint);
217                        } else
218                        if ($renderer->meta['sitetoc']['pagebreak']) {
219                            $sitepagebreak = array( array(
220                                'plugin',
221                                array(
222                                    'siteexport_toctools',
223                                    array(
224                                        'pagebreak',
225                                        null,
226                                        null
227                                    )
228                                )
229                            ));
230                            $instr = array_merge($instr, $instructions, $sitepagebreak);
231                        } else {
232                            // Concat
233                            $instr = array_merge($instr, $instructions);
234                        }
235                    }
236
237                    if (!empty($instr)) {
238                        $this->_cleanInstructions($instr, '/section_(close|open)/');
239                        $this->_cleanInstructions($instr, '/listu_(close|open)/');
240                        $this->_cleanInstructions($instr, '/listo_(close|open)/');
241
242                        //if its the document start, cut off the first element(document information)
243                        if ($instr[count($instr)-1][1][0] == 'siteexport_toctools') {
244                            $instr = array_slice($instr, 0, -1);
245                        }
246
247
248                        // print "<pre>"; print_r($instr); print "</pre>";
249                        $this->_render_output($renderer, $mode, $instr);
250                    }
251
252                    $renderer->section_close();
253                }
254                return true;
255            }
256
257            // Save the current ID
258            $LNID = $SID;
259
260            // Add ID to flags['mergeDoc']
261            if ($renderer->meta['sitetoc']['mergeDoc'] === true) { // || (count($renderer->meta['sitetoc']['siteexportTOC']) > 0 && $renderer->meta['sitetoc']['siteexportMergeDoc'] === true) ) {
262                $this->mergedPages[] = array($SID, $DEPTH);
263                $default = $renderer->_simpleTitle($SID); $isImage = false;
264                resolve_pageid(getNS($ID), $SID, $exists);
265
266                $NAME = empty($NAME) ? p_get_first_heading($SID, true) : $NAME;
267                $LNID = "$ID#" . sectionID($SID, $check);
268
269            } else {
270                // // print normal internal link (XHTML odt)
271                $renderer->internallink($LNID, $NAME, null);
272
273                // Display Description underneath
274                if ($renderer->meta['sitetoc']['showDescription'] === true) {
275                    // $renderer->p_open();
276                    $renderer->cdata(p_get_metadata($SID, 'description abstract', true));
277                    // $renderer->p_close();
278                }
279            }
280
281            // Render Metadata
282        } else if ($mode == 'metadata') {
283            if (!is_array($data) && $data == 'save__meta') {
284                $renderer->meta['sitetoc']['siteexportTOC'] = $this->savedToc;
285
286                foreach ($this->savedToc as $page) {
287                    $renderer->meta['relation']['references'][$page['id']] = $page['exists'];
288                }
289
290                $this->savedToc = array();
291            } else if (!isset($data['start']) && !isset($data['pos'])) {
292                $this->savedToc[] = $this->__addTocItem($SID, $NAME, $DEPTH, $renderer);
293            }
294        } else {
295            return false;
296        }
297
298        return true;
299    }
300
301    /*
302     * pull apart the ID and create an Entry for the TOC
303     */
304    function __addTocItem($id, $name, $depth, $renderer) {
305        global $conf;
306        global $ID;
307
308        // Render Title
309        $default = $renderer->_simpleTitle($id);
310        $exists = false; $isImage = false; $linktype = null;
311        resolve_pageid(getNS($ID), $id, $exists);
312        $name = $renderer->_getLinkTitle($name, $default, $isImage, $id, $linktype);
313
314        //keep hash anchor
315        list($id, $hash) = explode('#', $id, 2);
316        if (!empty($hash)) $hash = $renderer->_headerToLink($hash);
317
318        // Build Sitetoc Item
319        $item = array();
320        $item['id'] = $id;
321        $item['name'] = $name;
322        $item['anchor'] = $hash;
323        $item['depth'] = $depth;
324        $item['exists'] = $exists;
325        if (!$conf['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ) {
326            return false;
327        }
328
329        return $item;
330    }
331
332    /*
333     * Render the output of one page
334     */
335    function _render_output($renderer, $mode, $instr) {
336        global $ID;
337
338        // Section IDs
339        // $addID = sectionID($addID, $check);    //not possible to use a:b:c for id
340
341        if ($mode == 'xhtml') {
342
343            //--------RENDER
344            //renderer information(TOC build / Cache used)
345            $info = array();
346            $content = p_render($mode, $instr, $info);
347
348            //Remove TOC`s, section edit buttons and tags
349            $content = $this->_cleanXHTML($content);
350
351            // embed the included page
352            // $renderer->doc .= '<div class="include">';
353            //add an anchor to find start of a inserted page
354            // $renderer->doc .= "<a name='$addID' id='$addID'>";
355            $renderer->doc .= $content;
356            // $renderer->doc .= '</div>';
357        } else if ($mode == 'odt') {
358
359            // Loop through the instructions
360            foreach ($instr as $instruction) {
361                // Execute the callback against the Renderer
362                call_user_func_array(array($renderer, $instruction[0]), $instruction[1]);
363            }
364        }
365    }
366
367    /*
368     * Corrects relative internal links and media and
369     * converts headers of included pages to subheaders of the current page
370     */
371    function _convertInstructions($instr, $id, &$renderer, $depth = 1) {
372        global $ID;
373        global $conf;
374
375        $n = count($instr);
376
377        for ($i = 0; $i < $n; $i++) {
378            //internal links(links inside this wiki) an relative links
379            if ((substr($instr[$i][0], 0, 12) == 'internallink')) {
380                $this->_convert_link($renderer, $instr[$i], $id);
381            }
382            else if ((substr($instr[$i][0], 0, 13) == 'internalmedia')) {
383                $this->_convert_media($renderer, $instr[$i], $id);
384            }
385            else if ((substr($instr[$i][0], 0, 6) == 'header')) {
386                $this->_convert_header($renderer, $instr[$i], $depth-1); // -1 because the depth starts at 1
387            }
388            else if ((substr($instr[$i][0], 0, 12) == 'section_open')) {
389                $this->_convert_section($renderer, $instr[$i], $depth-1); // -1 because the depth starts at 1
390            }
391        }
392
393        //if its the document start, cut off the first element(document information)
394        if ($instr[0][0] == 'document_start')
395        return array_slice($instr, 1, -1);
396        else
397        return $instr;
398    }
399
400    /*
401     * Convert link of given instruction
402     */
403    function _convert_link(&$renderer, &$instr, $id) {
404        global $ID;
405
406        $exists = false;
407
408        resolve_pageid(getNS($id), $instr[1][0], $exists);
409        list($pageID, $pageReference) = explode("#", $instr[1][0], 2);
410
411        if (in_array($pageID, $this->includedPages)) {
412            // Crate new internal Links
413            $check = null;
414
415            // Either get existing reference or create from first heading. If still not there take the alternate ID
416            $pageNameLink = empty($pageReference) ? sectionID($pageID, $check) : $pageReference;
417
418            $instr[1][0] = $ID . "#" . $pageNameLink;
419
420        } else {
421            // Convert external Links to plain Text
422
423            $instr = array(
424                        "cdata",
425            array($instr[1][1]),
426            $instr[2]
427            );
428        }
429    }
430
431    /*
432     * Convert internalmedia of given instruction
433     */
434    function _convert_media(&$renderer, &$instr, $id) {
435        global $ID;
436
437        // Resolvemedia returns the absolute path to media by reference
438        $exists = false;
439        resolve_mediaid(getNS($id), $instr[1][0], $exists);
440    }
441
442    /**
443     * @param integer $depth
444     */
445    function _convert_header(&$renderer, &$instr, $depth) {
446        // More Depth!
447        $instr[1][1] += $depth;
448    }
449
450    /**
451     * @param integer $depth
452     */
453    function _convert_section(&$renderer, &$instr, $depth) {
454        // More Depth!
455        $instr[1][0] += $depth;
456    }
457
458    function _mergeWithHeaders($existing, $newInstructions, $level = 1, $mergeHint = array() ) {
459
460        $returnInstructions = array();
461        $preparedInstructions = array();
462        $existingStart = $existingEnd = 0;
463        $firstRun = true;
464
465        while ($this->_findNextHeaderSection($existing, $level, $existingStart, $existingEnd)) {
466
467            if ($firstRun) {
468                $returnInstructions = array_merge($returnInstructions, array_slice($existing, 0, $existingStart));
469                $firstRun = false;
470            }
471
472            $currentSlice = array_slice($existing, $existingStart, $existingEnd-$existingStart);
473
474            // Find matching part with headername
475            $newStart = $newEnd = 0;
476            if ($this->_findNextHeaderSection($newInstructions, $level, $newStart, $newEnd, $currentSlice[0][1][0])) {
477
478                $newSlice = array_slice($newInstructions, $newStart, $newEnd-$newStart);
479                if ($newSlice[0][0] == 'header')
480                    array_shift($newSlice); // Remove Heading
481
482                // merge found parts on next level.
483                $returnedInstructions = $this->_mergeWithHeaders($currentSlice, $newSlice, $level+1, $mergeHint);
484
485                // Put them at the end!
486                $preparedInstructions = array_merge($preparedInstructions, $returnedInstructions);
487
488                // Remove from input
489                array_splice($newInstructions, $newStart, $newEnd-$newStart);
490            } else {
491                // Nothing else found
492                $preparedInstructions = array_merge($preparedInstructions, $currentSlice);
493            }
494
495            $existingStart = $existingEnd;
496        }
497
498        // Append the rest
499        $returnInstructions = array_merge($returnInstructions, array_slice($existing, $existingStart));
500
501        // Check for section close inconsistencies and put one at the very end ...
502        $section_postpend = array();
503        if (
504            (
505            ($tmp = array_slice($newInstructions, -1))
506            && ($tmp[0][0] == 'section_close')
507            )
508            &&
509            (
510            ($tmp = array_slice($newInstructions, -2))
511            && ($tmp[0][0] == 'section_close')
512            )
513        ) {
514            $section_postpend = array_splice($newInstructions, -1);
515        }
516        if (
517            (
518            ($tmp = array_slice($returnInstructions, -1))
519            && ($tmp[0][0] == 'section_close')
520            )
521            &&
522            (
523            ($tmp = array_slice($returnInstructions, -2))
524            && ($tmp[0][0] == 'section_close')
525            )
526        ) {
527            $section_postpend = array_merge($section_postpend, array_splice($returnInstructions, -1));
528        }
529
530        // What if there are headings left inside the $newInstructions?????
531        // Find matching part with headername
532        $newStart = $newEnd = 0;
533        $section_prepend = array();
534        if ($this->_findNextHeaderSection($newInstructions, $level, $newStart, $newEnd)) {
535            // If there are header in here, build a prepend and have the rest at the end
536            $section_prepend = array_splice($newInstructions, 0, $newStart);
537        } else {
538            // If not, prepend all of it.
539            $section_prepend = $newInstructions;
540            $newInstructions = array();
541        }
542
543        $this->_insertMergeHint( $section_prepend, $mergeHint );
544
545        $returnInstructions = array_merge($returnInstructions, $section_prepend, $preparedInstructions, $newInstructions, $section_postpend);
546
547        return $returnInstructions;
548    }
549
550    /**
551     * @param integer $level
552     */
553    function _findNextHeaderSection($section, $level, &$start, &$end, $headerName = null) {
554
555        $inCount = count($section);
556        $currentSlice = -1;
557
558        // Find Level 1 Header that matches.
559        for ($i = $start; $i < $inCount; $i++) {
560
561            $instruction = $section[$i];
562            $end = $i; // Or it will be lost and a section close will be missing.
563
564            // First Level Header
565            if ($instruction[0] == 'header' && $instruction[1][1] == $level) {
566
567                if ($currentSlice > 0) {
568                    return true;
569                }
570
571                if ($headerName == null || ($headerName == $instruction[1][0])) {
572                    // Begin of new slice ...
573                    $start = $currentSlice = $i;
574                }
575            }
576        }
577
578        // Nothing found
579        $end = $i; // Or it will be lost and a section close will be missing.
580        return $currentSlice > 0;
581    }
582
583    /**
584     * @param string $tag
585     */
586    function _cleanInstructions(&$instructions, $tag) {
587
588        $inCount = count($instructions);
589        for ($i = 0; $i < $inCount; $i++) {
590
591            // Last instruction
592            if ($i == $inCount-1) {
593                break;
594            }
595
596            if (preg_match($tag, $instructions[$i][0]) && preg_match($tag, $instructions[$i+1][0]) && $instructions[$i][0] != $instructions[$i+1][0]) {
597
598                // found different tags, but both match the expression and follow each other - so they can be elliminated
599                array_splice($instructions, $i, 2);
600                $inCount -= 2;
601                $i--;
602            }
603
604        }
605    }
606
607    function _insertMergeHint( &$instructions, $mergeHint ) {
608
609        // Surround new slice with a mergehint
610        if ( empty( $mergeHint ) ) { return; }
611
612        // only section content should be surrounded.
613        if ( $instructions[0][0] != 'section_open' ) { return; }
614
615        // save for later use
616        $mergeHints = array();
617        $mergeHintId = sectionid( $mergeHint, $mergeHints );
618        $this->merghintIds[$mergeHintId] = $mergeHint;
619
620        $mergeHintPrepend = array( array(
621            'plugin',
622            array(
623                'siteexport_toctools',
624                array(
625                    'mergehint',
626                    'start',
627                    $mergeHint,
628                    $mergeHintId
629                )
630            )
631        ));
632
633        $mergeHintPostpend = array( array(
634            'plugin',
635            array(
636                'siteexport_toctools',
637                array(
638                    'mergehint',
639                    'end',
640                    $mergeHint
641                )
642            )
643        ));
644
645/*
646        print "\n\n#########\n";
647        print_r($instructions);
648        print "\nn#########\n\n";
649*/
650        $instructions = array_merge( $mergeHintPrepend, $instructions, $mergeHintPostpend );
651    }
652
653    /**
654     * Remove TOC, section edit buttons and tags
655     */
656    function _cleanXHTML($xhtml) {
657        $replace = array(
658            '!<div class="toc">.*?(</div>\n</div>)!s' => '', // remove TOCs
659            '#<!-- SECTION \[(\d*-\d*)\] -->#s'       => '', // remove section edit buttons
660            '!<div id="tags">.*?(</div>)!s'           => ''  // remove category tags
661        );
662        $xhtml = preg_replace(array_keys($replace), array_values($replace), $xhtml);
663        return $xhtml;
664    }
665
666    /**
667     * Allow the plugin to prevent DokuWiki creating a second instance of itself
668     *
669     * @return bool   true if the plugin can not be instantiated more than once
670     */
671    function isSingleton() {
672        return true;
673    }
674}
675// vim:ts=4:sw=4:et:enc=utf-8:
676