xref: /plugin/siteexport/syntax/toc.php (revision bf835a8661b9b9fc0fe11523a2d8946bd0278297)
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                            case 'mergehint' : $renderer->meta['sitetoc']['mergehint'] = true; break;
144                        }
145                    }
146                }
147
148                $renderer->section_open("1 sitetoc");
149                if ($renderer->meta['sitetoc']['noTocHeader'] === false) {
150                    $renderer->header($lang['toc'], 1, $data['pos']);
151                }
152
153                return true;
154            } else
155
156            // All Output has been done
157            if (!is_array($data) && $data == 'save__meta') {
158
159                // Close TOC
160                $renderer->section_close();
161
162                if ($renderer->meta['sitetoc']['noTOC'] === true) {
163                    $renderer->doc = preg_replace("/<div.*?sitetoc.*?$/si", "", $renderer->doc);
164                }
165
166                // If this is not set, we may have it as Metadata
167                if (!$this->mergedPages && $renderer->meta['sitetoc']['mergeDoc']) {
168                    $toc = $renderer->meta['sitetoc']['siteexportTOC'];
169
170                    if (is_array($toc)) {
171                        foreach ($toc as $tocItem) {
172                            $this->mergedPages[] = array($tocItem['id'], $tocItem['depth']);
173                        }
174                    }
175
176                }
177
178                // If there is some data to be merged
179                if (count($this->mergedPages) > 0) {
180
181                    $renderer->doc = ''; // Start fresh!
182
183                    $renderer->section_open("1 mergedsite" . ($renderer->meta['sitetoc']['mergehint']?' mergehint':''));
184
185                    // Prepare lookup Array
186                    foreach ($this->mergedPages as $tocItem) {
187                        $this->includedPages[] = array_shift(explode('#', $tocItem[0]));
188                    }
189
190                    // Load the instructions
191                    $instr = array();
192                    $mergeHint = null;
193                    foreach ($this->mergedPages as $tocElement) {
194
195                        list($tocItem, $depth) = $tocElement;
196                        $file = wikiFN($tocItem);
197
198                        if (@file_exists($file)) {
199                            $instructions = p_cached_instructions($file, false, $tocItem);
200                        } else {
201                            $instructions = p_get_instructions(io_readWikiPage($file, $tocItem));
202                        }
203
204                        // Convert Link and header instructions
205                        $instructions = $this->_convertInstructions($instructions, $addID, $renderer, $depth);
206
207                        if ($renderer->meta['sitetoc']['mergeHeader'] && !empty($instr)) {
208                            // get a hint for merged pages
209                            if ( $renderer->meta['sitetoc']['mergehint'] && !empty( $instr ) ) {
210                                // only if the first section is already there
211                                $mergeHint = p_get_metadata( $tocItem, 'mergehint', METADATA_RENDER_USING_SIMPLE_CACHE );
212                                if ( empty( $mergeHint) ) { $mergeHint = p_get_metadata( $tocItem, 'thema', METADATA_RENDER_USING_SIMPLE_CACHE ); }
213                                if ( empty( $mergeHint) ) { $mergeHint = tpl_pagetitle( $tocItem, true ); }
214                            }
215
216                            // Merge
217                            $instr = $this->_mergeWithHeaders($instr, $instructions, 1, $mergeHint);
218                        } else
219                        if ($renderer->meta['sitetoc']['pagebreak']) {
220                            $sitepagebreak = array( array(
221                                'plugin',
222                                array(
223                                    'siteexport_toctools',
224                                    array(
225                                        'pagebreak',
226                                        null,
227                                        null
228                                    )
229                                )
230                            ));
231                            $instr = array_merge($instr, $instructions, $sitepagebreak);
232                        } else {
233                            // Concat
234                            $instr = array_merge($instr, $instructions);
235                        }
236                    }
237
238                    if (!empty($instr)) {
239                        $this->_cleanInstructions($instr, '/section_(close|open)/');
240                        $this->_cleanInstructions($instr, '/listu_(close|open)/');
241                        $this->_cleanInstructions($instr, '/listo_(close|open)/');
242
243                        //if its the document start, cut off the first element(document information)
244                        if ($instr[count($instr)-1][1][0] == 'siteexport_toctools') {
245                            $instr = array_slice($instr, 0, -1);
246                        }
247
248
249                        // print "<pre>"; print_r($instr); print "</pre>";
250                        $this->_render_output($renderer, $mode, $instr);
251                    }
252
253                    $renderer->section_close();
254                }
255                return true;
256            }
257
258            // Save the current ID
259            $LNID = $SID;
260
261            // Add ID to flags['mergeDoc']
262            if ($renderer->meta['sitetoc']['mergeDoc'] === true) { // || (count($renderer->meta['sitetoc']['siteexportTOC']) > 0 && $renderer->meta['sitetoc']['siteexportMergeDoc'] === true) ) {
263                $this->mergedPages[] = array($SID, $DEPTH);
264                $default = $renderer->_simpleTitle($SID); $isImage = false;
265                resolve_pageid(getNS($ID), $SID, $exists);
266
267                $NAME = empty($NAME) ? p_get_first_heading($SID, true) : $NAME;
268                $LNID = "$ID#" . sectionID($SID, $check);
269
270            } else {
271                // // print normal internal link (XHTML odt)
272                $renderer->internallink($LNID, $NAME, null);
273
274                // Display Description underneath
275                if ($renderer->meta['sitetoc']['showDescription'] === true) {
276                    // $renderer->p_open();
277                    $renderer->cdata(p_get_metadata($SID, 'description abstract', true));
278                    // $renderer->p_close();
279                }
280            }
281
282            // Render Metadata
283        } else if ($mode == 'metadata') {
284            if (!is_array($data) && $data == 'save__meta') {
285                $renderer->meta['sitetoc']['siteexportTOC'] = $this->savedToc;
286
287                foreach ($this->savedToc as $page) {
288                    $renderer->meta['relation']['references'][$page['id']] = $page['exists'];
289                }
290
291                $this->savedToc = array();
292            } else if (!isset($data['start']) && !isset($data['pos'])) {
293                $this->savedToc[] = $this->__addTocItem($SID, $NAME, $DEPTH, $renderer);
294            }
295        } else {
296            return false;
297        }
298
299        return true;
300    }
301
302    /*
303     * pull apart the ID and create an Entry for the TOC
304     */
305    function __addTocItem($id, $name, $depth, $renderer) {
306        global $conf;
307        global $ID;
308
309        // Render Title
310        $default = $renderer->_simpleTitle($id);
311        $exists = false; $isImage = false; $linktype = null;
312        resolve_pageid(getNS($ID), $id, $exists);
313        $name = $renderer->_getLinkTitle($name, $default, $isImage, $id, $linktype);
314
315        //keep hash anchor
316        list($id, $hash) = explode('#', $id, 2);
317        if (!empty($hash)) $hash = $renderer->_headerToLink($hash);
318
319        // Build Sitetoc Item
320        $item = array();
321        $item['id'] = $id;
322        $item['name'] = $name;
323        $item['anchor'] = $hash;
324        $item['depth'] = $depth;
325        $item['exists'] = $exists;
326        if (!$conf['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ) {
327            return false;
328        }
329
330        return $item;
331    }
332
333    /*
334     * Render the output of one page
335     */
336    function _render_output($renderer, $mode, $instr) {
337        global $ID;
338
339        // Section IDs
340        // $addID = sectionID($addID, $check);    //not possible to use a:b:c for id
341
342        if ($mode == 'xhtml') {
343
344            //--------RENDER
345            //renderer information(TOC build / Cache used)
346            $info = array();
347            $content = p_render($mode, $instr, $info);
348
349            //Remove TOC`s, section edit buttons and tags
350            $content = $this->_cleanXHTML($content);
351
352            // embed the included page
353            // $renderer->doc .= '<div class="include">';
354            //add an anchor to find start of a inserted page
355            // $renderer->doc .= "<a name='$addID' id='$addID'>";
356            $renderer->doc .= $content;
357            // $renderer->doc .= '</div>';
358        } else if ($mode == 'odt') {
359
360            // Loop through the instructions
361            foreach ($instr as $instruction) {
362                // Execute the callback against the Renderer
363                call_user_func_array(array($renderer, $instruction[0]), $instruction[1]);
364            }
365        }
366    }
367
368    /*
369     * Corrects relative internal links and media and
370     * converts headers of included pages to subheaders of the current page
371     */
372    function _convertInstructions($instr, $id, &$renderer, $depth = 1) {
373        global $ID;
374        global $conf;
375
376        $n = count($instr);
377
378        for ($i = 0; $i < $n; $i++) {
379            //internal links(links inside this wiki) an relative links
380            if ((substr($instr[$i][0], 0, 12) == 'internallink')) {
381                $this->_convert_link($renderer, $instr[$i], $id);
382            }
383            else if ((substr($instr[$i][0], 0, 13) == 'internalmedia')) {
384                $this->_convert_media($renderer, $instr[$i], $id);
385            }
386            else if ((substr($instr[$i][0], 0, 6) == 'header')) {
387                $this->_convert_header($renderer, $instr[$i], $depth-1); // -1 because the depth starts at 1
388            }
389            else if ((substr($instr[$i][0], 0, 12) == 'section_open')) {
390                $this->_convert_section($renderer, $instr[$i], $depth-1); // -1 because the depth starts at 1
391            }
392        }
393
394        //if its the document start, cut off the first element(document information)
395        if ($instr[0][0] == 'document_start')
396        return array_slice($instr, 1, -1);
397        else
398        return $instr;
399    }
400
401    /*
402     * Convert link of given instruction
403     */
404    function _convert_link(&$renderer, &$instr, $id) {
405        global $ID;
406
407        $exists = false;
408
409        resolve_pageid(getNS($id), $instr[1][0], $exists);
410        list($pageID, $pageReference) = explode("#", $instr[1][0], 2);
411
412        if (in_array($pageID, $this->includedPages)) {
413            // Crate new internal Links
414            $check = null;
415
416            // Either get existing reference or create from first heading. If still not there take the alternate ID
417            $pageNameLink = empty($pageReference) ? sectionID($pageID, $check) : $pageReference;
418
419            $instr[1][0] = $ID . "#" . $pageNameLink;
420
421        } else {
422            // Convert external Links to plain Text
423
424            $instr = array(
425                        "cdata",
426            array($instr[1][1]),
427            $instr[2]
428            );
429        }
430    }
431
432    /*
433     * Convert internalmedia of given instruction
434     */
435    function _convert_media(&$renderer, &$instr, $id) {
436        global $ID;
437
438        // Resolvemedia returns the absolute path to media by reference
439        $exists = false;
440        resolve_mediaid(getNS($id), $instr[1][0], $exists);
441    }
442
443    /**
444     * @param integer $depth
445     */
446    function _convert_header(&$renderer, &$instr, $depth) {
447        // More Depth!
448        $instr[1][1] += $depth;
449    }
450
451    /**
452     * @param integer $depth
453     */
454    function _convert_section(&$renderer, &$instr, $depth) {
455        // More Depth!
456        $instr[1][0] += $depth;
457    }
458
459    function _mergeWithHeaders($existing, $newInstructions, $level = 1, $mergeHint = array() ) {
460
461        $returnInstructions = array();
462        $preparedInstructions = array();
463        $existingStart = $existingEnd = 0;
464        $firstRun = true;
465
466        while ($this->_findNextHeaderSection($existing, $level, $existingStart, $existingEnd)) {
467
468            if ($firstRun) {
469                $returnInstructions = array_merge($returnInstructions, array_slice($existing, 0, $existingStart));
470                $firstRun = false;
471            }
472
473            $currentSlice = array_slice($existing, $existingStart, $existingEnd-$existingStart);
474
475            // Find matching part with headername
476            $newStart = $newEnd = 0;
477            if ($this->_findNextHeaderSection($newInstructions, $level, $newStart, $newEnd, $currentSlice[0][1][0])) {
478
479                $newSlice = array_slice($newInstructions, $newStart, $newEnd-$newStart);
480                if ($newSlice[0][0] == 'header')
481                    array_shift($newSlice); // Remove Heading
482
483                // merge found parts on next level.
484                $returnedInstructions = $this->_mergeWithHeaders($currentSlice, $newSlice, $level+1, $mergeHint);
485
486                // Put them at the end!
487                $preparedInstructions = array_merge($preparedInstructions, $returnedInstructions);
488
489                // Remove from input
490                array_splice($newInstructions, $newStart, $newEnd-$newStart);
491            } else {
492                // Nothing else found
493                $preparedInstructions = array_merge($preparedInstructions, $currentSlice);
494            }
495
496            $existingStart = $existingEnd;
497        }
498
499        // Append the rest
500        $returnInstructions = array_merge($returnInstructions, array_slice($existing, $existingStart));
501
502        // Check for section close inconsistencies and put one at the very end ...
503        $section_postpend = array();
504        if (
505            (
506            ($tmp = array_slice($newInstructions, -1))
507            && ($tmp[0][0] == 'section_close')
508            )
509            &&
510            (
511            ($tmp = array_slice($newInstructions, -2))
512            && ($tmp[0][0] == 'section_close')
513            )
514        ) {
515            $section_postpend = array_splice($newInstructions, -1);
516        }
517        if (
518            (
519            ($tmp = array_slice($returnInstructions, -1))
520            && ($tmp[0][0] == 'section_close')
521            )
522            &&
523            (
524            ($tmp = array_slice($returnInstructions, -2))
525            && ($tmp[0][0] == 'section_close')
526            )
527        ) {
528            $section_postpend = array_merge($section_postpend, array_splice($returnInstructions, -1));
529        }
530
531        // What if there are headings left inside the $newInstructions?????
532        // Find matching part with headername
533        $newStart = $newEnd = 0;
534        $section_prepend = array();
535        if ($this->_findNextHeaderSection($newInstructions, $level, $newStart, $newEnd)) {
536            // If there are header in here, build a prepend and have the rest at the end
537            $section_prepend = array_splice($newInstructions, 0, $newStart);
538        } else {
539            // If not, prepend all of it.
540            $section_prepend = $newInstructions;
541            $newInstructions = array();
542        }
543
544        $this->_insertMergeHint( $section_prepend, $mergeHint );
545
546        $returnInstructions = array_merge($returnInstructions, $section_prepend, $preparedInstructions, $newInstructions, $section_postpend);
547
548        return $returnInstructions;
549    }
550
551    /**
552     * @param integer $level
553     */
554    function _findNextHeaderSection($section, $level, &$start, &$end, $headerName = null) {
555
556        $inCount = count($section);
557        $currentSlice = -1;
558
559        // Find Level 1 Header that matches.
560        for ($i = $start; $i < $inCount; $i++) {
561
562            $instruction = $section[$i];
563            $end = $i; // Or it will be lost and a section close will be missing.
564
565            // First Level Header
566            if ($instruction[0] == 'header' && $instruction[1][1] == $level) {
567
568                if ($currentSlice > 0) {
569                    return true;
570                }
571
572                if ($headerName == null || ($headerName == $instruction[1][0])) {
573                    // Begin of new slice ...
574                    $start = $currentSlice = $i;
575                }
576            }
577        }
578
579        // Nothing found
580        $end = $i; // Or it will be lost and a section close will be missing.
581        return $currentSlice > 0;
582    }
583
584    /**
585     * @param string $tag
586     */
587    function _cleanInstructions(&$instructions, $tag) {
588
589        $inCount = count($instructions);
590        for ($i = 0; $i < $inCount; $i++) {
591
592            // Last instruction
593            if ($i == $inCount-1) {
594                break;
595            }
596
597            if (preg_match($tag, $instructions[$i][0]) && preg_match($tag, $instructions[$i+1][0]) && $instructions[$i][0] != $instructions[$i+1][0]) {
598
599                // found different tags, but both match the expression and follow each other - so they can be elliminated
600                array_splice($instructions, $i, 2);
601                $inCount -= 2;
602                $i--;
603            }
604
605        }
606    }
607
608    function _insertMergeHint( &$instructions, $mergeHint ) {
609
610        // Surround new slice with a mergehint
611        if ( empty( $mergeHint ) ) { return; }
612
613        // only section content should be surrounded.
614        if ( $instructions[0][0] != 'section_open' ) { return; }
615
616        // save for later use
617        $mergeHints = array();
618        $mergeHintId = sectionid( $mergeHint, $mergeHints );
619        $this->merghintIds[$mergeHintId] = $mergeHint;
620
621        $mergeHintPrepend = array( array(
622            'plugin',
623            array(
624                'siteexport_toctools',
625                array(
626                    'mergehint',
627                    'start',
628                    $mergeHint,
629                    $mergeHintId
630                )
631            )
632        ));
633
634        $mergeHintPostpend = array( array(
635            'plugin',
636            array(
637                'siteexport_toctools',
638                array(
639                    'mergehint',
640                    'end',
641                    $mergeHint
642                )
643            )
644        ));
645
646/*
647        print "\n\n#########\n";
648        print_r($instructions);
649        print "\nn#########\n\n";
650*/
651        $instructions = array_merge( $mergeHintPrepend, $instructions, $mergeHintPostpend );
652    }
653
654    /**
655     * Remove TOC, section edit buttons and tags
656     */
657    function _cleanXHTML($xhtml) {
658        $replace = array(
659            '!<div class="toc">.*?(</div>\n</div>)!s' => '', // remove TOCs
660            '#<!-- SECTION \[(\d*-\d*)\] -->#s'       => '', // remove section edit buttons
661            '!<div id="tags">.*?(</div>)!s'           => ''  // remove category tags
662        );
663        $xhtml = preg_replace(array_keys($replace), array_values($replace), $xhtml);
664        return $xhtml;
665    }
666
667    /**
668     * Allow the plugin to prevent DokuWiki creating a second instance of itself
669     *
670     * @return bool   true if the plugin can not be instantiated more than once
671     */
672    function isSingleton() {
673        return true;
674    }
675}
676// vim:ts=4:sw=4:et:enc=utf-8:
677