4 * Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5 * Copyright 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
7 * This file is part of PhpWiki.
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.
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.
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.
25 * CreateToc: Create a Table of Contents and automatically link to headers
28 * <<CreateToc arguments>>
29 * @author: Reini Urban, Marc-Etienne Vargenau
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.
37 if (!defined('TOC_FULL_SYNTAX'))
38 define('TOC_FULL_SYNTAX', 1);
40 class WikiPlugin_CreateToc
43 function getDescription()
45 return _("Create a Table of Contents and automatically link to headers.");
48 function getDefaultArguments()
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' => ' ',
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
63 'with_toclink' => 0, // link back to TOC
68 // Initialisation of toc counter
69 private function initTocCounter()
71 $counter = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
75 // Update toc counter with a new title
76 private function tocCounter(&$counter, $level)
79 for ($i = $level + 1; $i <= 5; $i++) {
84 private function roman_counter($number)
90 $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
91 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
93 foreach ($lookup as $roman => $value) {
94 $matches = intval($n / $value);
95 $result .= str_repeat($roman, $matches);
101 private function letter_counter($number)
104 return chr(ord("A") + $number - 1);
106 return chr(ord("A") + ($number / 26) - 1) . chr(ord("A") + ($number % 26));
110 // Get string corresponding to the current title
111 private function getCounter(&$counter, $firstlevelstyle)
113 if ($firstlevelstyle == 'roman') {
114 $str = $this->roman_counter($counter[1]);
115 } elseif ($firstlevelstyle == 'letter') {
116 $str = $this->letter_counter($counter[1]);
120 for ($i = 2; $i <= 5; $i++) {
121 if ($counter[$i] != 0)
122 $str .= '.' . $counter[$i];
127 // Get HTML header corresponding to current level (level is set of ! or =)
128 private function getHeader($level)
131 $count = substr_count($level, '!');
140 $count = substr_count($level, '=');
156 private function quote($heading)
158 if (TOC_FULL_SYNTAX) {
159 $theading = TransformInline($heading);
161 return preg_quote($theading->asXML(), "/");
163 return XmlContent::_quote(preg_quote($heading, "/"));
165 return XmlContent::_quote(preg_quote($heading, "/"));
170 * @param $hstart id (in $content) of heading start
171 * @param $hend id (in $content) of heading end
173 private function searchHeader($content, $start_index, $heading,
174 $level, &$hstart, &$hend, $basepage = false)
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>/",
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();
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>"
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])) {
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)) {
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);
228 /** prevent from duplicate anchors,
229 * beautify spaces: " " => "_" and not "x20."
231 private function nextAnchor($s)
233 static $anchors = array();
235 $s = str_replace(' ', '_', $s);
238 while (!empty($anchors[$anchor])) {
239 $anchor = sprintf("%s_%d", $s, $i++);
241 $anchors[$anchor] = $i;
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 = '')
254 if (!$levels) $levels = array(1, 2);
255 $tocCounter = $this->initTocCounter();
260 $insidetable = false;
261 $insideverbatim = false;
262 for ($i = 0; $i < count($content); $i++) {
263 if (preg_match('/^\s*{\|/', $content[$i])) {
266 } elseif (preg_match('/^\s*{{{/', $content[$i])
267 || preg_match('/^\s*<pre>/', $content[$i])
268 || preg_match('/^\s*<verbatim>/', $content[$i])
270 $insideverbatim = true;
272 } elseif (preg_match('/^\s*\|}/', $content[$i])) {
273 $insidetable = false;
275 } elseif (preg_match('/^\s*}}}/', $content[$i])
276 || preg_match('/^\s*<\/pre>/', $content[$i])
277 || preg_match('/^\s*<\/verbatim>/', $content[$i])
279 $insideverbatim = false;
282 if (($insidetable) || ($insideverbatim)) {
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]);
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))))
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], "=")) {
304 $anchor = $this->nextAnchor($s);
305 $manchor = MangleXmlIdentifier($anchor);
308 $texts = $this->getCounter($tocCounter, $firstlevelstyle) . ' ' . $s;
310 $headers[] = array('text' => $texts,
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"));
320 $j = $this->searchHeader($markup->_content, $j, $s,
321 $match[1], $hstart, $hend,
323 if ($j and isset($markup->_content[$j])) {
324 $x = $markup->_content[$j];
325 $qheading = $this->quote($s);
327 $counterString = $this->getCounter($tocCounter, $firstlevelstyle);
328 if (($hstart === 0) && is_string($markup->_content[$j])) {
331 $anchorString = "<a href=\"$url\" id=\"$manchor\">$counterString</a> - \$2";
333 $anchorString = "<a href=\"$url\" id=\"$manchor\">\$2</a>";
335 $anchorString = "<a id=\"$manchor\"></a>";
337 $anchorString .= "$counterString - ";
339 if ($x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
340 "\$1$anchorString\$2\$3", $x, 1)
343 $x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
344 "\$1$anchorString\$3",
345 $markup->_content[$j], 1);
347 $markup->_content[$j] = $x;
350 $x = $markup->_content[$hstart];
351 $h = $this->getHeader($match[1]);
355 $anchorString = "\$1<a href=\"$url\" id=\"$manchor\">$counterString</a> - ";
357 /* Not possible to make a backlink on a
358 * title with a WikiWord */
359 $anchorString = "\$1<a id=\"$manchor\"></a>";
362 $anchorString = "\$1<a id=\"$manchor\"></a>";
364 $anchorString .= "$counterString - ";
366 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
367 $anchorString, $x, 1);
369 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
371 $markup->_content[$hstart], 1);
373 $markup->_content[$hstart] = $x;
383 function run($dbi, $argstr, &$request, $basepage)
386 extract($this->getArgs($argstr, $request));
388 // Expand relative page names.
389 $page = new WikiPageName($pagename, $basepage);
390 $pagename = $page->name;
393 return $this->error(sprintf(_("A required argument ā%sā is missing."), 'pagename'));
395 if (($notoc) or ($liststyle == 'ol')) {
398 if ($firstlevelstyle and ($firstlevelstyle != 'number')
399 and ($firstlevelstyle != 'letter')
400 and ($firstlevelstyle != 'roman')
402 return $this->error(_("Error: firstlevelstyle must be 'number', 'letter' or 'roman'"));
405 // Check if page exists.
406 if (!($dbi->isWikiPage($pagename))) {
407 return $this->error(sprintf(_("Page ā%sā does not exist."), $pagename));
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"),
416 $page = $dbi->getPage($pagename);
419 if (!is_whole_number($version) or !($version > 0)) {
420 return $this->error(_("Error: version must be a positive integer."));
422 $r = $page->getRevision($version);
423 if ((!$r) || ($r->hasDefaultContents())) {
424 return $this->error(sprintf(_("%s: no such revision %d."),
425 $pagename, $version));
428 $r = $page->getCurrentRevision();
431 $current = $page->getCurrentRevision();
432 $content = $r->getContent();
434 $html = HTML::div(array('class' => 'toc', 'id' => GenerateId("toc")));
436 $html->setAttr('style', 'display:none;');
438 if (($position == "left") or ($position == "right")) {
439 $html->setAttr('style', 'float:' . $position . '; width:' . $width . ';');
441 $toclistid = GenerateId("toclist");
442 $list = HTML::div(array('id' => $toclistid, 'class' => 'toclist'));
443 if (!strstr($headers, ",")) {
444 $headers = array($headers);
446 $headers = explode(",", $headers);
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);
456 $level = min(max(1, (int)$h), 5);
461 require_once 'lib/InlineParser.php';
462 if ($headers = $this->extractHeaders($content, $dbi->_markup,
463 $with_toclink, $with_counter,
464 $levels, $firstlevelstyle, $basepage)
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));
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");
483 $toctoggleid = GenerateId("toctoggle");
485 $toclink = HTML(_("Table of Contents"),
487 HTML::a(array('id' => 'TOC')),
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)));
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));
505 $html->pushContent($list);
506 if (count($headers) == 0) {
507 // Do not display an empty TOC
508 $html->setAttr('style', 'display:none;');
518 // c-hanging-comment-ender-p: nil
519 // indent-tabs-mode: nil