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 * - 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.
38 if (!defined('TOC_FULL_SYNTAX'))
39 define('TOC_FULL_SYNTAX', 1);
41 class WikiPlugin_CreateToc
46 return _("CreateToc");
49 function getDescription()
51 return _("Create a Table of Contents and automatically link to headers");
54 function getDefaultArguments()
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' => ' ',
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
69 'with_toclink' => 0, // link back to TOC
74 // Initialisation of toc counter
75 function _initTocCounter()
77 $counter = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
81 // Update toc counter with a new title
82 function _tocCounter(&$counter, $level)
85 for ($i = $level + 1; $i <= 5; $i++) {
90 function _roman_counter($number)
96 $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
97 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
99 foreach ($lookup as $roman => $value) {
100 $matches = intval($n / $value);
101 $result .= str_repeat($roman, $matches);
107 function _letter_counter($number)
110 return chr(ord("A") + $number - 1);
112 return chr(ord("A") + ($number / 26) - 1) . chr(ord("A") + ($number % 26));
116 // Get string corresponding to the current title
117 function _getCounter(&$counter, $level, $firstlevelstyle)
119 if ($firstlevelstyle == 'roman') {
120 $str = $this->_roman_counter($counter[1]);
121 } elseif ($firstlevelstyle == 'letter') {
122 $str = $this->_letter_counter($counter[1]);
126 for ($i = 2; $i <= 5; $i++) {
127 if ($counter[$i] != 0)
128 $str .= '.' . $counter[$i];
133 // Get HTML header corresponding to current level (level is set of ! or =)
134 function _getHeader($level)
137 $count = substr_count($level, '!');
146 $count = substr_count($level, '=');
162 function _quote($heading)
164 if (TOC_FULL_SYNTAX) {
165 $theading = TransformInline($heading);
167 return preg_quote($theading->asXML(), "/");
169 return XmlContent::_quote(preg_quote($heading, "/"));
171 return XmlContent::_quote(preg_quote($heading, "/"));
176 * @param $hstart id (in $content) of heading start
177 * @param $hend id (in $content) of heading end
179 function searchHeader($content, $start_index, $heading,
180 $level, &$hstart, &$hend, $basepage = false)
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>/",
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();
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>"
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])) {
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)) {
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);
234 /** prevent from duplicate anchors,
235 * beautify spaces: " " => "_" and not "x20."
237 function _nextAnchor($s)
239 static $anchors = array();
241 $s = str_replace(' ', '_', $s);
244 while (!empty($anchors[$anchor])) {
245 $anchor = sprintf("%s_%d", $s, $i++);
247 $anchors[$anchor] = $i;
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 function extractHeaders(&$content, &$markup, $backlink = 0,
258 $counter = 0, $levels = false, $firstlevelstyle = 'number', $basepage = '')
260 if (!$levels) $levels = array(1, 2);
261 $tocCounter = $this->_initTocCounter();
266 $insidetable = false;
267 $insideverbatim = false;
268 for ($i = 0; $i < count($content); $i++) {
269 if (preg_match('/^\s*{\|/', $content[$i])) {
272 } elseif (preg_match('/^\s*{{{/', $content[$i])
273 || preg_match('/^\s*<pre>/', $content[$i])
274 || preg_match('/^\s*<verbatim>/', $content[$i])
276 $insideverbatim = true;
278 } elseif (preg_match('/^\s*\|}/', $content[$i])) {
279 $insidetable = false;
281 } elseif (preg_match('/^\s*}}}/', $content[$i])
282 || preg_match('/^\s*<\/pre>/', $content[$i])
283 || preg_match('/^\s*<\/verbatim>/', $content[$i])
285 $insideverbatim = false;
288 if (($insidetable) || ($insideverbatim)) {
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]);
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))))
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], "=")) {
310 $anchor = $this->_nextAnchor($s);
311 $manchor = MangleXmlIdentifier($anchor);
314 $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle) . ' ' . $s;
316 $headers[] = array('text' => $texts,
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"));
326 $j = $this->searchHeader($markup->_content, $j, $s,
327 $match[1], $hstart, $hend,
329 if ($j and isset($markup->_content[$j])) {
330 $x = $markup->_content[$j];
331 $qheading = $this->_quote($s);
333 $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
334 if (($hstart === 0) && is_string($markup->_content[$j])) {
337 $anchorString = "<a href=\"$url\" id=\"$manchor\">$counterString</a> - \$2";
339 $anchorString = "<a href=\"$url\" id=\"$manchor\">\$2</a>";
341 $anchorString = "<a id=\"$manchor\"></a>";
343 $anchorString .= "$counterString - ";
345 if ($x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
346 "\$1$anchorString\$2\$3", $x, 1)
349 $x = preg_replace('/(<h\d>)(' . $qheading . ')(<\/h\d>)/',
350 "\$1$anchorString\$3",
351 $markup->_content[$j], 1);
353 $markup->_content[$j] = $x;
356 $x = $markup->_content[$hstart];
357 $h = $this->_getHeader($match[1]);
361 $anchorString = "\$1<a href=\"$url\" id=\"$manchor\">$counterString</a> - ";
363 /* Not possible to make a backlink on a
364 * title with a WikiWord */
365 $anchorString = "\$1<a id=\"$manchor\"></a>";
368 $anchorString = "\$1<a id=\"$manchor\"></a>";
370 $anchorString .= "$counterString - ";
372 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
373 $anchorString, $x, 1);
375 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
377 $markup->_content[$hstart], 1);
379 $markup->_content[$hstart] = $x;
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 $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."));
445 $content = $r->getContent();
447 $html = HTML::div(array('class' => 'toc', 'id' => GenerateId("toc")));
449 $html->setAttr('style', 'display:none;');
451 if (($position == "left") or ($position == "right")) {
452 $html->setAttr('style', 'float:' . $position . '; width:' . $width . ';');
454 $toclistid = GenerateId("toclist");
455 $list = HTML::div(array('id' => $toclistid, 'class' => 'toclist'));
456 if (!strstr($headers, ",")) {
457 $headers = array($headers);
459 $headers = explode(",", $headers);
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);
469 $level = min(max(1, (int)$h), 5);
474 require_once 'lib/InlineParser.php';
475 if ($headers = $this->extractHeaders($content, $dbi->_markup,
476 $with_toclink, $with_counter,
477 $levels, $firstlevelstyle, $basepage)
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));
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");
496 $toctoggleid = GenerateId("toctoggle");
498 $toclink = HTML(_("Table of Contents"),
500 HTML::a(array('id' => 'TOC')),
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)));
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));
518 $html->pushContent($list);
519 if (count($headers) == 0) {
520 // Do not display an empty TOC
521 $html->setAttr('style', 'display:none;');
531 // c-hanging-comment-ender-p: nil
532 // indent-tabs-mode: nil