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
45 function getDescription()
47 return _("Create a Table of Contents and automatically link to headers.");
50 function getDefaultArguments()
52 return array('extracollapse' => 1, // provide an entry +/- link to collapse
53 'firstlevelstyle' => 'number', // 'number', 'letter' or 'roman'
54 'headers' => "1,2,3,4,5", // "!!!"=>h2, "!!"=>h3, "!"=>h4
55 // "1"=>h2, "2"=>h3, "3"=>h4, "4"=>h5, "5"=>h6
56 'indentstr' => ' ',
57 'jshide' => 0, // collapsed TOC as DHTML button
58 'liststyle' => 'dl', // 'dl' or 'ul' or 'ol'
59 'noheader' => 0, // omit "Table of Contents" header
60 'notoc' => 0, // do not display TOC, only number headers
61 'pagename' => '[pagename]', // TOC of another page here?
62 'position' => 'full', // full, right or left
65 'with_toclink' => 0, // link back to TOC
70 // Initialisation of toc counter
71 private function initTocCounter()
73 $counter = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
77 // Update toc counter with a new title
78 private function tocCounter(&$counter, $level)
81 for ($i = $level + 1; $i <= 5; $i++) {
86 private function roman_counter($number)
92 $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
93 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
95 foreach ($lookup as $roman => $value) {
96 $matches = intval($n / $value);
97 $result .= str_repeat($roman, $matches);
103 private function letter_counter($number)
106 return chr(ord("A") + $number - 1);
108 return chr(ord("A") + ($number / 26) - 1) . chr(ord("A") + ($number % 26));
112 // Get string corresponding to the current title
113 private function getCounter(&$counter, $firstlevelstyle)
115 if ($firstlevelstyle == 'roman') {
116 $str = $this->roman_counter($counter[1]);
117 } elseif ($firstlevelstyle == 'letter') {
118 $str = $this->letter_counter($counter[1]);
122 for ($i = 2; $i <= 5; $i++) {
123 if ($counter[$i] != 0)
124 $str .= '.' . $counter[$i];
129 // Get HTML header corresponding to current level (level is set of ! or =)
130 private function getHeader($level)
133 $count = substr_count($level, '!');
142 $count = substr_count($level, '=');
158 private function quote($heading)
160 if (TOC_FULL_SYNTAX) {
161 $theading = TransformInline($heading);
163 return preg_quote($theading->asXML(), "/");
165 return htmlspecialchars(preg_quote($heading, "/"), ENT_COMPAT, 'UTF-8');
167 return htmlspecialchars(preg_quote($heading, "/"), ENT_COMPAT, 'UTF-8');
172 * @param $hstart id (in $content) of heading start
173 * @param $hend id (in $content) of heading end
175 private function searchHeader($content, $start_index, $heading,
176 $level, &$hstart, &$hend, $basepage = false)
180 $h = $this->getHeader($level);
181 $qheading = $this->quote($heading);
182 for ($j = $start_index; $j < count($content); $j++) {
183 if (is_string($content[$j])) {
184 if (preg_match("/<$h>$qheading<\/$h>/",
188 } elseif (is_a($content[$j], 'cached_link')) {
189 if (method_exists($content[$j], 'asXML')) {
190 $content[$j]->_basepage = $basepage;
191 $content[$j] = $content[$j]->asXML();
193 $content[$j] = $content[$j]->asString();
194 // shortcut for single wikiword or link headers
195 if ($content[$j] == $heading
196 and substr($content[$j - 1], -4, 4) == "<$h>"
197 and substr($content[$j + 1], 0, 5) == "</$h>"
201 return $j; // single wikiword
202 } elseif (TOC_FULL_SYNTAX) {
203 //DONE: To allow "!! WikiWord link" or !! http://anylink/
204 // Check against joined content (after cached_plugininvocation).
205 // The first link is the anchor then.
206 if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j - 1])) {
209 for ($k = max($j - 1, $start_index); $k < count($content); $k++) {
210 if (is_string($content[$k]))
211 $joined .= $content[$k];
212 elseif (method_exists($content[$k], 'asXML'))
213 $joined .= $content[$k]->asXML(); else
214 $joined .= $content[$k]->asString();
215 if (preg_match("/<$h>$qheading<\/$h>/", $joined)) {
227 /** prevent from duplicate anchors,
228 * beautify spaces: " " => "_" and not "x20."
230 private function nextAnchor($s)
232 static $anchors = array();
234 $s = str_replace(' ', '_', $s);
237 while (!empty($anchors[$anchor])) {
238 $anchor = sprintf("%s_%d", $s, $i++);
240 $anchors[$anchor] = $i;
244 // We have to find headers in both:
245 // - classic Phpwiki syntax (lines starting with "!", "!!" or "!!!")
246 // - Wikicreole syntax (lines starting with "==", "===", etc.)
247 // We must omit lines starting with "!" if inside a Mediawiki table
248 // (they represent a table header)
249 // Feature request: proper nesting; multiple levels (e.g. 1,3)
250 private function extractHeaders(&$content, &$markup, $backlink,
251 $counter, $levels, $firstlevelstyle, $basepage)
253 if (!$levels) $levels = array(1, 2);
254 $tocCounter = $this->initTocCounter();
259 $insidetable = false;
260 $insideverbatim = false;
261 for ($i = 0; $i < count($content); $i++) {
262 if (preg_match('/^\s*{\|/', $content[$i])) {
265 } elseif (preg_match('/^\s*{{{/', $content[$i])
266 || preg_match('/^\s*<pre>/', $content[$i])
267 || preg_match('/^\s*<verbatim>/', $content[$i])
269 $insideverbatim = true;
271 } elseif (preg_match('/^\s*\|}/', $content[$i])) {
272 $insidetable = false;
274 } elseif (preg_match('/^\s*}}}/', $content[$i])
275 || preg_match('/^\s*<\/pre>/', $content[$i])
276 || preg_match('/^\s*<\/verbatim>/', $content[$i])
278 $insideverbatim = false;
281 if (($insidetable) || ($insideverbatim)) {
284 foreach ($levels as $level) {
285 if ($level < 1 or $level > 5) continue;
286 $phpwikiclassiclevel = 4 - $level;
287 $wikicreolelevel = $level + 1;
288 $trim = trim($content[$i]);
290 if ((((strpos($trim, '=') === 0))
291 && (preg_match('/^\s*(={' . $wikicreolelevel . ',' . $wikicreolelevel . '})([^=].*)$/', $content[$i], $match)))
292 or (((strpos($trim, '!') === 0))
293 && ((preg_match('/^\s*(!{' . $phpwikiclassiclevel . ',' . $phpwikiclassiclevel . '})([^!].*)$/', $content[$i], $match))))
295 $this->tocCounter($tocCounter, $level);
296 if (!strstr($content[$i], '#[')) {
297 $s = trim($match[2]);
298 // If it is Wikicreole syntax, remove '='s at the end
299 if (string_starts_with($match[1], "=")) {
303 $anchor = $this->nextAnchor($s);
304 $manchor = MangleXmlIdentifier($anchor);
307 $texts = $this->getCounter($tocCounter, $firstlevelstyle) . ' ' . $s;
309 $headers[] = array('text' => $texts,
312 // Change original wikitext, but that is useless art...
313 $content[$i] = $match[1] . " #[|$manchor][$s|#TOC]";
314 // And now change the to be printed markup (XmlTree):
315 // Search <hn>$s</hn> line in markup
316 /* Url for backlink */
317 $url = WikiURL(new WikiPageName($basepage, false, "TOC"));
319 $j = $this->searchHeader($markup->_content, $j, $s,
320 $match[1], $hstart, $hend,
322 if ($j and isset($markup->_content[$j])) {
323 $x = $markup->_content[$j];
324 $qheading = $this->quote($s);
326 $counterString = $this->getCounter($tocCounter, $firstlevelstyle);
327 if (($hstart === 0) && is_string($markup->_content[$j])) {
330 $anchorString = "<a href=\"$url\" id=\"$manchor\">$counterString</a> - \$2";
332 $anchorString = "<a href=\"$url\" id=\"$manchor\">\$2</a>";
334 $anchorString = "<a id=\"$manchor\"></a>";
336 $anchorString .= "$counterString - ";
338 if ($x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
339 "\$1$anchorString\$2\$3", $x, 1)
342 $x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
343 "\$1$anchorString\$3",
344 $markup->_content[$j], 1);
346 $markup->_content[$j] = $x;
349 $x = $markup->_content[$hstart];
350 $h = $this->getHeader($match[1]);
354 $anchorString = "\$1<a href=\"$url\" id=\"$manchor\">$counterString</a> - ";
356 /* Not possible to make a backlink on a
357 * title with a WikiWord */
358 $anchorString = "\$1<a id=\"$manchor\"></a>";
361 $anchorString = "\$1<a id=\"$manchor\"></a>";
363 $anchorString .= "$counterString - ";
365 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
366 $anchorString, $x, 1);
368 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
370 $markup->_content[$hstart], 1);
372 $markup->_content[$hstart] = $x;
384 * @param string $argstr
385 * @param WikiRequest $request
386 * @param string $basepage
389 function run($dbi, $argstr, &$request, $basepage)
392 extract($this->getArgs($argstr, $request));
394 // Expand relative page names.
395 $page = new WikiPageName($pagename, $basepage);
396 $pagename = $page->name;
399 return $this->error(sprintf(_("A required argument ā%sā is missing."), 'pagename'));
401 if (($notoc) or ($liststyle == 'ol')) {
404 if ($firstlevelstyle and ($firstlevelstyle != 'number')
405 and ($firstlevelstyle != 'letter')
406 and ($firstlevelstyle != 'roman')
408 return $this->error(_("Error: firstlevelstyle must be 'number', 'letter' or 'roman'"));
411 // Check if page exists.
412 if (!($dbi->isWikiPage($pagename))) {
413 return $this->error(sprintf(_("Page ā%sā does not exist."), $pagename));
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"),
422 $page = $dbi->getPage($pagename);
425 if (!is_whole_number($version) or !($version > 0)) {
426 return $this->error(_("Error: version must be a positive integer."));
428 $r = $page->getRevision($version);
429 if ((!$r) || ($r->hasDefaultContents())) {
430 return $this->error(sprintf(_("%s: no such revision %d."),
431 $pagename, $version));
434 $r = $page->getCurrentRevision();
437 $content = $r->getContent();
439 $html = HTML::div(array('class' => 'toc', 'id' => GenerateId("toc")));
441 $html->setAttr('style', 'display:none;');
443 if (($position == "left") or ($position == "right")) {
444 $html->setAttr('style', 'float:' . $position . '; width:' . $width . ';');
446 $toclistid = GenerateId("toclist");
447 $list = HTML::div(array('id' => $toclistid, 'class' => 'toclist'));
448 if (!strstr($headers, ",")) {
449 $headers = array($headers);
451 $headers = explode(",", $headers);
454 foreach ($headers as $h) {
455 //replace !!! with level 1, ...
456 if (strstr($h, "!")) {
457 $hcount = substr_count($h, '!');
458 $level = min(max(1, $hcount), 3);
461 $level = min(max(1, (int)$h), 5);
466 require_once 'lib/InlineParser.php';
467 if ($headers = $this->extractHeaders($content, $dbi->_markup,
468 $with_toclink, $with_counter,
469 $levels, $firstlevelstyle, $basepage)
471 foreach ($headers as $h) {
472 // proper heading indent
473 $level = $h['level'];
474 $indent = $level - 1;
475 $link = new WikiPageName($pagename, $page, $h['anchor']);
476 $li = WikiLink($link, 'known', $h['text']);
477 // Hack to suppress pagename before #
478 // $li->_attr["href"] = strstr($li->_attr["href"], '#');
479 $list->pushContent(HTML::p(HTML::raw
480 (str_repeat($indentstr, $indent)), $li));
483 $list->setAttr('style', 'display:' . ($jshide ? 'none;' : 'block;'));
484 $open = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowOpen.png");
485 $close = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowClosed.png");
488 $toctoggleid = GenerateId("toctoggle");
490 $toclink = HTML(_("Table of Contents"),
492 HTML::a(array('id' => 'TOC')),
494 'id' => $toctoggleid,
495 'class' => 'wikiaction',
496 'title' => _("Click to display the TOC"),
497 'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')",
498 'alt' => 'toctoggle',
499 'src' => $jshide ? $close : $open)));
501 $toclink = HTML::a(array('id' => 'TOC',
502 'class' => 'wikiaction',
503 'title' => _("Click to display"),
504 'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')"),
505 _("Table of Contents"),
506 HTML::span(array('style' => 'display:none',
507 'id' => $toctoggleid), " "));
508 $html->pushContent(HTML::p(array('class' => 'toctitle'), $toclink));
510 $html->pushContent($list);
511 if (count($headers) == 0) {
512 // Do not display an empty TOC
513 $html->setAttr('style', 'display:none;');
523 // c-hanging-comment-ender-p: nil
524 // indent-tabs-mode: nil