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