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 htmlspecialchars(preg_quote($heading, "/"), ENT_COMPAT, 'UTF-8');
165 return htmlspecialchars(preg_quote($heading, "/"), ENT_COMPAT, 'UTF-8');
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)) {
225 /** prevent from duplicate anchors,
226 * beautify spaces: " " => "_" and not "x20."
228 private function nextAnchor($s)
230 static $anchors = array();
232 $s = str_replace(' ', '_', $s);
235 while (!empty($anchors[$anchor])) {
236 $anchor = sprintf("%s_%d", $s, $i++);
238 $anchors[$anchor] = $i;
242 // We have to find headers in both:
243 // - classic Phpwiki syntax (lines starting with "!", "!!" or "!!!")
244 // - Wikicreole syntax (lines starting with "==", "===", etc.)
245 // We must omit lines starting with "!" if inside a Mediawiki table
246 // (they represent a table header)
247 // Feature request: proper nesting; multiple levels (e.g. 1,3)
248 private function extractHeaders(&$content, &$markup, $backlink,
249 $counter, $levels, $firstlevelstyle, $basepage)
251 if (!$levels) $levels = array(1, 2);
252 $tocCounter = $this->initTocCounter();
257 $insidetable = false;
258 $insideverbatim = false;
259 for ($i = 0; $i < count($content); $i++) {
260 if (preg_match('/^\s*{\|/', $content[$i])) {
263 } elseif (preg_match('/^\s*{{{/', $content[$i])
264 || preg_match('/^\s*<pre>/', $content[$i])
265 || preg_match('/^\s*<verbatim>/', $content[$i])
267 $insideverbatim = true;
269 } elseif (preg_match('/^\s*\|}/', $content[$i])) {
270 $insidetable = false;
272 } elseif (preg_match('/^\s*}}}/', $content[$i])
273 || preg_match('/^\s*<\/pre>/', $content[$i])
274 || preg_match('/^\s*<\/verbatim>/', $content[$i])
276 $insideverbatim = false;
279 if (($insidetable) || ($insideverbatim)) {
282 foreach ($levels as $level) {
283 if ($level < 1 or $level > 5) continue;
284 $phpwikiclassiclevel = 4 - $level;
285 $wikicreolelevel = $level + 1;
286 $trim = trim($content[$i]);
288 if ((((strpos($trim, '=') === 0))
289 && (preg_match('/^\s*(={' . $wikicreolelevel . ',' . $wikicreolelevel . '})([^=].*)$/', $content[$i], $match)))
290 or (((strpos($trim, '!') === 0))
291 && ((preg_match('/^\s*(!{' . $phpwikiclassiclevel . ',' . $phpwikiclassiclevel . '})([^!].*)$/', $content[$i], $match))))
293 $this->tocCounter($tocCounter, $level);
294 if (!strstr($content[$i], '#[')) {
295 $s = trim($match[2]);
296 // If it is Wikicreole syntax, remove '='s at the end
297 if (string_starts_with($match[1], "=")) {
301 $anchor = $this->nextAnchor($s);
302 $manchor = MangleXmlIdentifier($anchor);
305 $texts = $this->getCounter($tocCounter, $firstlevelstyle) . ' ' . $s;
307 $headers[] = array('text' => $texts,
310 // Change original wikitext, but that is useless art...
311 $content[$i] = $match[1] . " #[|$manchor][$s|#TOC]";
312 // And now change the to be printed markup (XmlTree):
313 // Search <hn>$s</hn> line in markup
314 /* Url for backlink */
315 $url = WikiURL(new WikiPageName($basepage, false, "TOC"));
317 $j = $this->searchHeader($markup->_content, $j, $s,
318 $match[1], $hstart, $hend,
320 if ($j and isset($markup->_content[$j])) {
321 $x = $markup->_content[$j];
322 $qheading = $this->quote($s);
324 $counterString = $this->getCounter($tocCounter, $firstlevelstyle);
325 if (($hstart === 0) && is_string($markup->_content[$j])) {
328 $anchorString = "<a href=\"$url\" id=\"$manchor\">$counterString</a> - \$2";
330 $anchorString = "<a href=\"$url\" id=\"$manchor\">\$2</a>";
332 $anchorString = "<a id=\"$manchor\"></a>";
334 $anchorString .= "$counterString - ";
336 if ($x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
337 "\$1$anchorString\$2\$3", $x, 1)
340 $x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
341 "\$1$anchorString\$3",
342 $markup->_content[$j], 1);
344 $markup->_content[$j] = $x;
347 $x = $markup->_content[$hstart];
348 $h = $this->getHeader($match[1]);
352 $anchorString = "\$1<a href=\"$url\" id=\"$manchor\">$counterString</a> - ";
354 /* Not possible to make a backlink on a
355 * title with a WikiWord */
356 $anchorString = "\$1<a id=\"$manchor\"></a>";
359 $anchorString = "\$1<a id=\"$manchor\"></a>";
361 $anchorString .= "$counterString - ";
363 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
364 $anchorString, $x, 1);
366 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
368 $markup->_content[$hstart], 1);
370 $markup->_content[$hstart] = $x;
382 * @param string $argstr
383 * @param WikiRequest $request
384 * @param string $basepage
387 function run($dbi, $argstr, &$request, $basepage)
390 extract($this->getArgs($argstr, $request));
392 // Expand relative page names.
393 $page = new WikiPageName($pagename, $basepage);
394 $pagename = $page->name;
397 return $this->error(sprintf(_("A required argument ā%sā is missing."), 'pagename'));
399 if (($notoc) or ($liststyle == 'ol')) {
402 if ($firstlevelstyle and ($firstlevelstyle != 'number')
403 and ($firstlevelstyle != 'letter')
404 and ($firstlevelstyle != 'roman')
406 return $this->error(_("Error: firstlevelstyle must be 'number', 'letter' or 'roman'"));
409 // Check if page exists.
410 if (!($dbi->isWikiPage($pagename))) {
411 return $this->error(sprintf(_("Page ā%sā does not exist."), $pagename));
414 // Check if user is allowed to get the page.
415 if (!mayAccessPage('view', $pagename)) {
416 return $this->error(sprintf(_("Illegal access to page %s: no read access"),
420 $page = $dbi->getPage($pagename);
423 if (!is_whole_number($version) or !($version > 0)) {
424 return $this->error(_("Error: version must be a positive integer."));
426 $r = $page->getRevision($version);
427 if ((!$r) || ($r->hasDefaultContents())) {
428 return $this->error(sprintf(_("%s: no such revision %d."),
429 $pagename, $version));
432 $r = $page->getCurrentRevision();
435 $content = $r->getContent();
437 $html = HTML::div(array('class' => 'toc', 'id' => GenerateId("toc")));
439 $html->setAttr('style', 'display:none;');
441 if (($position == "left") or ($position == "right")) {
442 $html->setAttr('style', 'float:' . $position . '; width:' . $width . ';');
444 $toclistid = GenerateId("toclist");
445 $list = HTML::div(array('id' => $toclistid, 'class' => 'toclist'));
446 if (!strstr($headers, ",")) {
447 $headers = array($headers);
449 $headers = explode(",", $headers);
452 foreach ($headers as $h) {
453 //replace !!! with level 1, ...
454 if (strstr($h, "!")) {
455 $hcount = substr_count($h, '!');
456 $level = min(max(1, $hcount), 3);
459 $level = min(max(1, (int)$h), 5);
464 require_once 'lib/InlineParser.php';
465 if ($headers = $this->extractHeaders($content, $dbi->_markup,
466 $with_toclink, $with_counter,
467 $levels, $firstlevelstyle, $basepage)
469 foreach ($headers as $h) {
470 // proper heading indent
471 $level = $h['level'];
472 $indent = $level - 1;
473 $link = new WikiPageName($pagename, $page, $h['anchor']);
474 $li = WikiLink($link, 'known', $h['text']);
475 // Hack to suppress pagename before #
476 // $li->_attr["href"] = strstr($li->_attr["href"], '#');
477 $list->pushContent(HTML::p(HTML::raw
478 (str_repeat($indentstr, $indent)), $li));
481 $list->setAttr('style', 'display:' . ($jshide ? 'none;' : 'block;'));
482 $open = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowOpen.png");
483 $close = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowClosed.png");
486 $toctoggleid = GenerateId("toctoggle");
488 $toclink = HTML(_("Table of Contents"),
490 HTML::a(array('id' => 'TOC')),
492 'id' => $toctoggleid,
493 'class' => 'wikiaction',
494 'title' => _("Click to display to TOC"),
495 'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')",
496 'alt' => 'toctoggle',
497 'src' => $jshide ? $close : $open)));
499 $toclink = HTML::a(array('id' => 'TOC',
500 'class' => 'wikiaction',
501 'title' => _("Click to display"),
502 'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')"),
503 _("Table of Contents"),
504 HTML::span(array('style' => 'display:none',
505 'id' => $toctoggleid), " "));
506 $html->pushContent(HTML::p(array('class' => 'toctitle'), $toclink));
508 $html->pushContent($list);
509 if (count($headers) == 0) {
510 // Do not display an empty TOC
511 $html->setAttr('style', 'display:none;');
521 // c-hanging-comment-ender-p: nil
522 // indent-tabs-mode: nil