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