]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/CreateToc.php
Merge OldTextFormattingRules into TextFormattingRules; rename underscore plugins
[SourceForge/phpwiki.git] / lib / plugin / CreateToc.php
1 <?php
2
3 /*
4  * Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5  * Copyright 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
6  *
7  * This file is part of PhpWiki.
8  *
9  * PhpWiki is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * PhpWiki is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 /**
25  * CreateToc:  Create a Table of Contents and automatically link to headers
26  *
27  * Usage:
28  *  <<CreateToc arguments>>
29  * @author:  Reini Urban, Marc-Etienne Vargenau
30  *
31  * Known problems:
32  * - Certain corner-edges will not work with TOC_FULL_SYNTAX.
33  *   I believe I fixed all of them now, but who knows?
34  * - bug #969495 "existing labels not honored" seems to be fixed.
35  */
36
37 if (!defined('TOC_FULL_SYNTAX'))
38     define('TOC_FULL_SYNTAX', 1);
39
40 class WikiPlugin_CreateToc
41     extends WikiPlugin
42 {
43     function getDescription()
44     {
45         return _("Create a Table of Contents and automatically link to headers.");
46     }
47
48     function getDefaultArguments()
49     {
50         return array('extracollapse' => 1, // provide an entry +/- link to collapse
51             'firstlevelstyle' => 'number', // 'number', 'letter' or 'roman'
52             'headers' => "1,2,3,4,5", // "!!!"=>h2, "!!"=>h3, "!"=>h4
53             // "1"=>h2, "2"=>h3, "3"=>h4, "4"=>h5, "5"=>h6
54             'indentstr' => '&nbsp;&nbsp;',
55             'jshide' => 0, // collapsed TOC as DHTML button
56             'liststyle' => 'dl', // 'dl' or 'ul' or 'ol'
57             'noheader' => 0, // omit "Table of Contents" header
58             'notoc' => 0, // do not display TOC, only number headers
59             'pagename' => '[pagename]', // TOC of another page here?
60             'position' => 'full', // full, right or left
61             'width' => '200px',
62             'with_counter' => 0,
63             'with_toclink' => 0, // link back to TOC
64             'version' => false,
65         );
66     }
67
68     // Initialisation of toc counter
69     private function initTocCounter()
70     {
71         $counter = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
72         return $counter;
73     }
74
75     // Update toc counter with a new title
76     private function tocCounter(&$counter, $level)
77     {
78         $counter[$level]++;
79         for ($i = $level + 1; $i <= 5; $i++) {
80             $counter[$i] = 0;
81         }
82     }
83
84     private function roman_counter($number)
85     {
86
87         $n = intval($number);
88         $result = '';
89
90         $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
91             'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
92
93         foreach ($lookup as $roman => $value) {
94             $matches = intval($n / $value);
95             $result .= str_repeat($roman, $matches);
96             $n = $n % $value;
97         }
98         return $result;
99     }
100
101     private function letter_counter($number)
102     {
103         if ($number <= 26) {
104             return chr(ord("A") + $number - 1);
105         } else {
106             return chr(ord("A") + ($number / 26) - 1) . chr(ord("A") + ($number % 26));
107         }
108     }
109
110     // Get string corresponding to the current title
111     private function getCounter(&$counter, $firstlevelstyle)
112     {
113         if ($firstlevelstyle == 'roman') {
114             $str = $this->roman_counter($counter[1]);
115         } elseif ($firstlevelstyle == 'letter') {
116             $str = $this->letter_counter($counter[1]);
117         } else {
118             $str = $counter[1];
119         }
120         for ($i = 2; $i <= 5; $i++) {
121             if ($counter[$i] != 0)
122                 $str .= '.' . $counter[$i];
123         }
124         return $str;
125     }
126
127     // Get HTML header corresponding to current level (level is set of ! or =)
128     private function getHeader($level)
129     {
130
131         $count = substr_count($level, '!');
132         switch ($count) {
133             case 3:
134                 return "h2";
135             case 2:
136                 return "h3";
137             case 1:
138                 return "h4";
139         }
140         $count = substr_count($level, '=');
141         switch ($count) {
142             case 2:
143                 return "h2";
144             case 3:
145                 return "h3";
146             case 4:
147                 return "h4";
148             case 5:
149                 return "h5";
150             case 6:
151                 return "h6";
152         }
153         return "";
154     }
155
156     private function quote($heading)
157     {
158         if (TOC_FULL_SYNTAX) {
159             $theading = TransformInline($heading);
160             if ($theading)
161                 return preg_quote($theading->asXML(), "/");
162             else
163                 return XmlContent::_quote(preg_quote($heading, "/"));
164         } else {
165             return XmlContent::_quote(preg_quote($heading, "/"));
166         }
167     }
168
169     /*
170      * @param $hstart id (in $content) of heading start
171      * @param $hend   id (in $content) of heading end
172      */
173     private function searchHeader($content, $start_index, $heading,
174                           $level, &$hstart, &$hend, $basepage = false)
175     {
176         $hstart = 0;
177         $hend = 0;
178         $h = $this->getHeader($level);
179         $qheading = $this->quote($heading);
180         for ($j = $start_index; $j < count($content); $j++) {
181             if (is_string($content[$j])) {
182                 if (preg_match("/<$h>$qheading<\/$h>/",
183                     $content[$j])
184                 )
185                     return $j;
186             } elseif (isa($content[$j], 'cached_link')) {
187                 if (method_exists($content[$j], 'asXML')) {
188                     $content[$j]->_basepage = $basepage;
189                     $content[$j] = $content[$j]->asXML();
190                 } else
191                     $content[$j] = $content[$j]->asString();
192                 // shortcut for single wikiword or link headers
193                 if ($content[$j] == $heading
194                     and substr($content[$j - 1], -4, 4) == "<$h>"
195                         and substr($content[$j + 1], 0, 5) == "</$h>"
196                 ) {
197                     $hstart = $j - 1;
198                     $hend = $j + 1;
199                     return $j; // single wikiword
200                 } elseif (TOC_FULL_SYNTAX) {
201                     //DONE: To allow "!! WikiWord link" or !! http://anylink/
202                     // Check against joined content (after cached_plugininvocation).
203                     // The first link is the anchor then.
204                     if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j - 1])) {
205                         $hstart = $j - 1;
206                         $joined = '';
207                         for ($k = max($j - 1, $start_index); $k < count($content); $k++) {
208                             if (is_string($content[$k]))
209                                 $joined .= $content[$k];
210                             elseif (method_exists($content[$k], 'asXML'))
211                                 $joined .= $content[$k]->asXML(); else
212                                 $joined .= $content[$k]->asString();
213                             if (preg_match("/<$h>$qheading<\/$h>/", $joined)) {
214                                 $hend = $k;
215                                 return $k;
216                             }
217                         }
218                     }
219                 }
220             }
221         }
222         // Do not trigger error, it happens e.g. for "<<CreateToc pagename=AnotherPage>>"
223         // trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
224
225         return 0;
226     }
227
228     /** prevent from duplicate anchors,
229      *  beautify spaces: " " => "_" and not "x20."
230      */
231     private function nextAnchor($s)
232     {
233         static $anchors = array();
234
235         $s = str_replace(' ', '_', $s);
236         $i = 1;
237         $anchor = $s;
238         while (!empty($anchors[$anchor])) {
239             $anchor = sprintf("%s_%d", $s, $i++);
240         }
241         $anchors[$anchor] = $i;
242         return $anchor;
243     }
244
245     // We have to find headers in both:
246     // - classic Phpwiki syntax (lines starting with "!", "!!" or "!!!")
247     // - Wikicreole syntax (lines starting with "==", "===", etc.)
248     // We must omit lines starting with "!" if inside a Mediawiki table
249     // (they represent a table header)
250     // Feature request: proper nesting; multiple levels (e.g. 1,3)
251     private function extractHeaders(&$content, &$markup, $backlink = 0,
252                             $counter = 0, $levels = false, $firstlevelstyle = 'number', $basepage = '')
253     {
254         if (!$levels) $levels = array(1, 2);
255         $tocCounter = $this->initTocCounter();
256         reset($levels);
257         sort($levels);
258         $headers = array();
259         $j = 0;
260         $insidetable = false;
261         $insideverbatim = false;
262         for ($i = 0; $i < count($content); $i++) {
263             if (preg_match('/^\s*{\|/', $content[$i])) {
264                 $insidetable = true;
265                 continue;
266             } elseif (preg_match('/^\s*{{{/', $content[$i])
267                 || preg_match('/^\s*<pre>/', $content[$i])
268                 || preg_match('/^\s*<verbatim>/', $content[$i])
269             ) {
270                 $insideverbatim = true;
271                 continue;
272             } elseif (preg_match('/^\s*\|}/', $content[$i])) {
273                 $insidetable = false;
274                 continue;
275             } elseif (preg_match('/^\s*}}}/', $content[$i])
276                 || preg_match('/^\s*<\/pre>/', $content[$i])
277                 || preg_match('/^\s*<\/verbatim>/', $content[$i])
278             ) {
279                 $insideverbatim = false;
280                 continue;
281             }
282             if (($insidetable) || ($insideverbatim)) {
283                 continue;
284             }
285             foreach ($levels as $level) {
286                 if ($level < 1 or $level > 5) continue;
287                 $phpwikiclassiclevel = 4 - $level;
288                 $wikicreolelevel = $level + 1;
289                 $trim = trim($content[$i]);
290
291                 if ((((strpos($trim, '=') === 0))
292                     && (preg_match('/^\s*(={' . $wikicreolelevel . ',' . $wikicreolelevel . '})([^=].*)$/', $content[$i], $match)))
293                     or (((strpos($trim, '!') === 0))
294                         && ((preg_match('/^\s*(!{' . $phpwikiclassiclevel . ',' . $phpwikiclassiclevel . '})([^!].*)$/', $content[$i], $match))))
295                 ) {
296                     $this->tocCounter($tocCounter, $level);
297                     if (!strstr($content[$i], '#[')) {
298                         $s = trim($match[2]);
299                         // If it is Wikicreole syntax, remove '='s at the end
300                         if (string_starts_with($match[1], "=")) {
301                             $s = trim($s, "=");
302                             $s = trim($s);
303                         }
304                         $anchor = $this->nextAnchor($s);
305                         $manchor = MangleXmlIdentifier($anchor);
306                         $texts = $s;
307                         if ($counter) {
308                             $texts = $this->getCounter($tocCounter, $firstlevelstyle) . ' ' . $s;
309                         }
310                         $headers[] = array('text' => $texts,
311                             'anchor' => $anchor,
312                             'level' => $level);
313                         // Change original wikitext, but that is useless art...
314                         $content[$i] = $match[1] . " #[|$manchor][$s|#TOC]";
315                         // And now change the to be printed markup (XmlTree):
316                         // Search <hn>$s</hn> line in markup
317                         /* Url for backlink */
318                         $url = WikiURL(new WikiPageName($basepage, false, "TOC"));
319
320                         $j = $this->searchHeader($markup->_content, $j, $s,
321                             $match[1], $hstart, $hend,
322                             $markup->_basepage);
323                         if ($j and isset($markup->_content[$j])) {
324                             $x = $markup->_content[$j];
325                             $qheading = $this->quote($s);
326                             if ($counter)
327                                 $counterString = $this->getCounter($tocCounter, $firstlevelstyle);
328                             if (($hstart === 0) && is_string($markup->_content[$j])) {
329                                 if ($backlink) {
330                                     if ($counter)
331                                         $anchorString = "<a href=\"$url\" id=\"$manchor\">$counterString</a> - \$2";
332                                     else
333                                         $anchorString = "<a href=\"$url\" id=\"$manchor\">\$2</a>";
334                                 } else {
335                                     $anchorString = "<a id=\"$manchor\"></a>";
336                                     if ($counter)
337                                         $anchorString .= "$counterString - ";
338                                 }
339                                 if ($x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
340                                     "\$1$anchorString\$2\$3", $x, 1)
341                                 ) {
342                                     if ($backlink) {
343                                         $x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
344                                             "\$1$anchorString\$3",
345                                             $markup->_content[$j], 1);
346                                     }
347                                     $markup->_content[$j] = $x;
348                                 }
349                             } else {
350                                 $x = $markup->_content[$hstart];
351                                 $h = $this->getHeader($match[1]);
352
353                                 if ($backlink) {
354                                     if ($counter) {
355                                         $anchorString = "\$1<a href=\"$url\" id=\"$manchor\">$counterString</a> - ";
356                                     } else {
357                                         /* Not possible to make a backlink on a
358                                          * title with a WikiWord */
359                                         $anchorString = "\$1<a id=\"$manchor\"></a>";
360                                     }
361                                 } else {
362                                     $anchorString = "\$1<a id=\"$manchor\"></a>";
363                                     if ($counter)
364                                         $anchorString .= "$counterString - ";
365                                 }
366                                 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
367                                     $anchorString, $x, 1);
368                                 if ($backlink) {
369                                     $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
370                                         $anchorString,
371                                         $markup->_content[$hstart], 1);
372                                 }
373                                 $markup->_content[$hstart] = $x;
374                             }
375                         }
376                     }
377                 }
378             }
379         }
380         return $headers;
381     }
382
383     function run($dbi, $argstr, &$request, $basepage)
384     {
385         global $WikiTheme;
386         extract($this->getArgs($argstr, $request));
387         if ($pagename) {
388             // Expand relative page names.
389             $page = new WikiPageName($pagename, $basepage);
390             $pagename = $page->name;
391         }
392         if (!$pagename) {
393             return $this->error(sprintf(_("A required argument ā€œ%sā€ is missing."), 'pagename'));
394         }
395         if (($notoc) or ($liststyle == 'ol')) {
396             $with_counter = 1;
397         }
398         if ($firstlevelstyle and ($firstlevelstyle != 'number')
399             and ($firstlevelstyle != 'letter')
400                 and ($firstlevelstyle != 'roman')
401         ) {
402             return $this->error(_("Error: firstlevelstyle must be 'number', 'letter' or 'roman'"));
403         }
404
405         // Check if page exists.
406         if (!($dbi->isWikiPage($pagename))) {
407             return $this->error(sprintf(_("Page ā€œ%sā€ does not exist."), $pagename));
408         }
409
410         // Check if user is allowed to get the page.
411         if (!mayAccessPage('view', $pagename)) {
412             return $this->error(sprintf(_("Illegal access to page %s: no read access"),
413                 $pagename));
414         }
415
416         $page = $dbi->getPage($pagename);
417
418         if ($version) {
419             if (!is_whole_number($version) or !($version > 0)) {
420                 return $this->error(_("Error: version must be a positive integer."));
421             }
422             $r = $page->getRevision($version);
423             if ((!$r) || ($r->hasDefaultContents())) {
424                 return $this->error(sprintf(_("%s: no such revision %d."),
425                     $pagename, $version));
426             }
427         } else {
428             $r = $page->getCurrentRevision();
429         }
430
431         $current = $page->getCurrentRevision();
432         $content = $r->getContent();
433
434         $html = HTML::div(array('class' => 'toc', 'id' => GenerateId("toc")));
435         if ($notoc) {
436             $html->setAttr('style', 'display:none;');
437         }
438         if (($position == "left") or ($position == "right")) {
439             $html->setAttr('style', 'float:' . $position . '; width:' . $width . ';');
440         }
441         $toclistid = GenerateId("toclist");
442         $list = HTML::div(array('id' => $toclistid, 'class' => 'toclist'));
443         if (!strstr($headers, ",")) {
444             $headers = array($headers);
445         } else {
446             $headers = explode(",", $headers);
447         }
448         $levels = array();
449         foreach ($headers as $h) {
450             //replace !!! with level 1, ...
451             if (strstr($h, "!")) {
452                 $hcount = substr_count($h, '!');
453                 $level = min(max(1, $hcount), 3);
454                 $levels[] = $level;
455             } else {
456                 $level = min(max(1, (int)$h), 5);
457                 $levels[] = $level;
458             }
459         }
460         if (TOC_FULL_SYNTAX)
461             require_once 'lib/InlineParser.php';
462         if ($headers = $this->extractHeaders($content, $dbi->_markup,
463             $with_toclink, $with_counter,
464             $levels, $firstlevelstyle, $basepage)
465         ) {
466             foreach ($headers as $h) {
467                 // proper heading indent
468                 $level = $h['level'];
469                 $indent = $level - 1;
470                 $link = new WikiPageName($pagename, $page, $h['anchor']);
471                 $li = WikiLink($link, 'known', $h['text']);
472                 // Hack to suppress pagename before #
473                 // $li->_attr["href"] = strstr($li->_attr["href"], '#');
474                 $list->pushContent(HTML::p(HTML::raw
475                 (str_repeat($indentstr, $indent)), $li));
476             }
477         }
478         $list->setAttr('style', 'display:' . ($jshide ? 'none;' : 'block;'));
479         $open = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowOpen.png");
480         $close = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowClosed.png");
481         if ($noheader) {
482         } else {
483             $toctoggleid = GenerateId("toctoggle");
484             if ($extracollapse)
485                 $toclink = HTML(_("Table of Contents"),
486                     " ",
487                     HTML::a(array('id' => 'TOC')),
488                     HTML::img(array(
489                         'id' => $toctoggleid,
490                         'class' => 'wikiaction',
491                         'title' => _("Click to display to TOC"),
492                         'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')",
493                         'alt' => 'toctoggle',
494                         'src' => $jshide ? $close : $open)));
495             else
496                 $toclink = HTML::a(array('id' => 'TOC',
497                         'class' => 'wikiaction',
498                         'title' => _("Click to display"),
499                         'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')"),
500                     _("Table of Contents"),
501                     HTML::span(array('style' => 'display:none',
502                         'id' => $toctoggleid), " "));
503             $html->pushContent(HTML::p(array('class' => 'toctitle'), $toclink));
504         }
505         $html->pushContent($list);
506         if (count($headers) == 0) {
507             // Do not display an empty TOC
508             $html->setAttr('style', 'display:none;');
509         }
510         return $html;
511     }
512 }
513
514 // Local Variables:
515 // mode: php
516 // tab-width: 8
517 // c-basic-offset: 4
518 // c-hanging-comment-ender-p: nil
519 // indent-tabs-mode: nil
520 // End: