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
20 * along with PhpWiki; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 * CreateToc: Create a Table of Contents and automatically link to headers
28 * <<CreateToc arguments>>
29 * @author: Reini Urban, Marc-Etienne Vargenau
32 * - MacIE will not work with jshide.
33 * - it will crash with old markup and Apache2 (?)
34 * - Certain corner-edges will not work with TOC_FULL_SYNTAX.
35 * I believe I fixed all of them now, but who knows?
36 * - bug #969495 "existing labels not honored" seems to be fixed.
39 if (!defined('TOC_FULL_SYNTAX'))
40 define('TOC_FULL_SYNTAX', 1);
42 class WikiPlugin_CreateToc
46 return _("CreateToc");
49 function getDescription() {
50 return _("Create a Table of Contents and automatically link to headers");
53 function getDefaultArguments() {
54 return array('extracollapse' => 1, // provide an entry +/- link to collapse
55 'firstlevelstyle' => 'number', // 'number', 'letter' or 'roman'
56 'headers' => "1,2,3,4,5", // "!!!"=>h2, "!!"=>h3, "!"=>h4
57 // "1"=>h2, "2"=>h3, "3"=>h4, "4"=>h5, "5"=>h6
58 'indentstr' => ' ',
59 'jshide' => 0, // collapsed TOC as DHTML button
60 'liststyle' => 'dl', // 'dl' or 'ul' or 'ol'
61 'noheader' => 0, // omit "Table of Contents" header
62 'notoc' => 0, // do not display TOC, only number headers
63 'pagename' => '[pagename]', // TOC of another page here?
64 'position' => 'full', // full, right or left
67 'with_toclink' => 0, // link back to TOC
71 // Initialisation of toc counter
72 function _initTocCounter() {
73 $counter = array(1=>0, 2=>0, 3=>0, 4=>0, 5=>0);
77 // Update toc counter with a new title
78 function _tocCounter(&$counter, $level) {
80 for($i = $level+1; $i <= 5; $i++) {
85 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 function _letter_counter($number) {
103 return chr(ord("A") + $number - 1);
105 return chr(ord("A") + ($number/26) - 1) . chr(ord("A") + ($number%26));
109 // Get string corresponding to the current title
110 function _getCounter(&$counter, $level, $firstlevelstyle) {
111 if ($firstlevelstyle == 'roman') {
112 $str= $this->_roman_counter($counter[1]);
113 } else if ($firstlevelstyle == 'letter') {
114 $str= $this->_letter_counter($counter[1]);
118 for($i = 2; $i <= 5; $i++) {
119 if($counter[$i] != 0)
120 $str .= '.'.$counter[$i];
125 // Get HTML header corresponding to current level (level is set of ! or =)
126 function _getHeader($level) {
128 $count = substr_count($level,'!');
134 $count = substr_count($level,'=');
145 function _quote($heading) {
146 if (TOC_FULL_SYNTAX ) {
147 $theading = TransformInline($heading);
149 return preg_quote($theading->asXML(), "/");
151 return XmlContent::_quote(preg_quote($heading, "/"));
153 return XmlContent::_quote(preg_quote($heading, "/"));
158 * @param $hstart id (in $content) of heading start
159 * @param $hend id (in $content) of heading end
161 function searchHeader ($content, $start_index, $heading,
162 $level, &$hstart, &$hend, $basepage=false) {
165 $h = $this->_getHeader($level);
166 $qheading = $this->_quote($heading);
167 for ($j=$start_index; $j < count($content); $j++) {
168 if (is_string($content[$j])) {
169 if (preg_match("/<$h>$qheading<\/$h>/",
173 elseif (isa($content[$j], 'cached_link'))
175 if (method_exists($content[$j],'asXML')) {
176 $content[$j]->_basepage = $basepage;
177 $content[$j] = $content[$j]->asXML();
179 $content[$j] = $content[$j]->asString();
180 // shortcut for single wikiword or link headers
181 if ($content[$j] == $heading
182 and substr($content[$j-1],-4,4) == "<$h>"
183 and substr($content[$j+1],0,5) == "</$h>")
187 return $j; // single wikiword
189 elseif (TOC_FULL_SYNTAX) {
190 //DONE: To allow "!! WikiWord link" or !! http://anylink/
191 // Check against joined content (after cached_plugininvocation).
192 // The first link is the anchor then.
193 if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j-1])) {
196 for ($k=max($j-1,$start_index);$k<count($content);$k++) {
197 if (is_string($content[$k]))
198 $joined .= $content[$k];
199 elseif (method_exists($content[$k],'asXML'))
200 $joined .= $content[$k]->asXML();
202 $joined .= $content[$k]->asString();
203 if (preg_match("/<$h>$qheading<\/$h>/",$joined)) {
212 trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
216 /** prevent from duplicate anchors,
217 * beautify spaces: " " => "_" and not "x20."
219 function _nextAnchor($s) {
220 static $anchors = array();
222 $s = str_replace(' ','_',$s);
225 while (!empty($anchors[$anchor])) {
226 $anchor = sprintf("%s_%d",$s,$i++);
228 $anchors[$anchor] = $i;
232 // We have to find headers in both:
233 // - classic Phpwiki syntax (lines starting with "!", "!!" or "!!!")
234 // - Wikicreole syntax (lines starting with "==", "===", etc.)
235 // We must omit lines starting with "!" if inside a Mediawiki table
236 // (they represent a table header)
237 // Feature request: proper nesting; multiple levels (e.g. 1,3)
238 function extractHeaders (&$content, &$markup, $backlink=0,
239 $counter=0, $levels=false, $firstlevelstyle='number', $basepage='')
241 if (!$levels) $levels = array(1,2);
242 $tocCounter = $this->_initTocCounter();
247 $insidetable = false;
248 $insideverbatim = false;
249 for ($i=0; $i<count($content); $i++) {
250 if (preg_match('/^\s*{\|/', $content[$i])) {
253 } else if (preg_match('/^\s*{{{/', $content[$i])
254 || preg_match('/^\s*<pre>/', $content[$i])
255 || preg_match('/^\s*<verbatim>/', $content[$i])) {
256 $insideverbatim = true;
258 } else if (preg_match('/^\s*\|}/', $content[$i])) {
259 $insidetable = false;
261 } else if (preg_match('/^\s*}}}/', $content[$i])
262 || preg_match('/^\s*<\/pre>/', $content[$i])
263 || preg_match('/^\s*<\/verbatim>/', $content[$i])) {
264 $insideverbatim = false;
267 if (($insidetable) || ($insideverbatim)) {
270 foreach ($levels as $level) {
271 if ($level < 1 or $level > 5) continue;
272 $phpwikiclassiclevel = 4 -$level;
273 $wikicreolelevel = $level + 1;
274 $trim = trim($content[$i]);
276 if ((((strpos($trim, '=') === 0))
277 && (preg_match('/^\s*(={'.$wikicreolelevel.','.$wikicreolelevel.'})([^=].*)$/', $content[$i], $match)))
278 or (((strpos($trim, '!') === 0))
279 && ((preg_match('/^\s*(!{'.$phpwikiclassiclevel.','.$phpwikiclassiclevel.'})([^!].*)$/', $content[$i], $match))))) {
280 $this->_tocCounter($tocCounter, $level);
281 if (!strstr($content[$i],'#[')) {
282 $s = trim($match[2]);
283 // If it is Wikicreole syntax, remove '='s at the end
284 if (string_starts_with($match[1], "=")) {
288 $anchor = $this->_nextAnchor($s);
289 $manchor = MangleXmlIdentifier($anchor);
292 $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle).' '.$s;
294 $headers[] = array('text' => $texts,
297 // Change original wikitext, but that is useless art...
298 $content[$i] = $match[1]." #[|$manchor][$s|#TOC]";
299 // And now change the to be printed markup (XmlTree):
300 // Search <hn>$s</hn> line in markup
301 /* Url for backlink */
302 $url = WikiURL(new WikiPageName($basepage,false,"TOC"));
304 $j = $this->searchHeader($markup->_content, $j, $s,
305 $match[1], $hstart, $hend,
307 if ($j and isset($markup->_content[$j])) {
308 $x = $markup->_content[$j];
309 $qheading = $this->_quote($s);
311 $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
312 if (($hstart === 0) && is_string($markup->_content[$j])) {
315 $anchorString = "<a href=\"$url\" id=\"$manchor\">$counterString</a> - \$2";
317 $anchorString = "<a href=\"$url\" id=\"$manchor\">\$2</a>";
319 $anchorString = "<a id=\"$manchor\"></a>";
321 $anchorString .= "$counterString - ";
323 if ($x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
324 "\$1$anchorString\$2\$3",$x,1)) {
326 $x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
327 "\$1$anchorString\$3",
328 $markup->_content[$j],1);
330 $markup->_content[$j] = $x;
333 $x = $markup->_content[$hstart];
334 $h = $this->_getHeader($match[1]);
338 $anchorString = "\$1<a href=\"$url\" id=\"$manchor\">$counterString</a> - ";
340 /* Not possible to make a backlink on a
341 * title with a WikiWord */
342 $anchorString = "\$1<a id=\"$manchor\"></a>";
346 $anchorString = "\$1<a id=\"$manchor\"></a>";
348 $anchorString .= "$counterString - ";
350 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
351 $anchorString, $x, 1);
353 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
355 $markup->_content[$hstart],1);
357 $markup->_content[$hstart] = $x;
367 function run($dbi, $argstr, &$request, $basepage) {
369 extract($this->getArgs($argstr, $request));
371 // Expand relative page names.
372 $page = new WikiPageName($pagename, $basepage);
373 $pagename = $page->name;
376 return $this->error(_("No page specified."));
378 if (isBrowserIE() and browserDetect("Mac")) {
381 if (($notoc) or ($liststyle == 'ol')) {
385 // Check if page exists.
386 if (!($dbi->isWikiPage($pagename))) {
387 return $this->error(sprintf(_("Page '%s' does not exist."), $pagename));
390 // Check if user is allowed to get the page.
391 if (!mayAccessPage ('view', $pagename)) {
392 return $this->error(sprintf(_("Illegal access to page %s: no read access"),
396 $page = $dbi->getPage($pagename);
399 $r = $page->getRevision($version);
400 if ((!$r) || ($r->hasDefaultContents())) {
401 return $this->error(sprintf(_("%s: no such revision %d."),
402 $pagename, $version));
405 $r = $page->getCurrentRevision();
408 $current = $page->getCurrentRevision();
409 //FIXME: I suspect this only to crash with Apache2
410 if (!$current->get('markup') or $current->get('markup') < 2) {
411 if (in_array(php_sapi_name(),array('apache2handler','apache2filter'))) {
412 return $this->error(_("CreateToc disabled for old markup."));
416 $content = $r->getContent();
418 $html = HTML::div(array('class' => 'toc', 'id'=> GenerateId("toc")));
420 $html->setAttr('style','display:none;');
422 if (($position == "left") or ($position == "right")) {
423 $html->setAttr('style','float:'.$position.'; width:'.$width.';');
425 $toclistid = GenerateId("toclist");
426 $list = HTML::div(array('id'=>$toclistid, 'class'=>'toclist'));
427 if (!strstr($headers,",")) {
428 $headers = array($headers);
430 $headers = explode(",",$headers);
433 foreach ($headers as $h) {
434 //replace !!! with level 1, ...
435 if (strstr($h,"!")) {
436 $hcount = substr_count($h,'!');
437 $level = min(max(1, $hcount),3);
440 $level = min(max(1, (int) $h), 5);
445 require_once("lib/InlineParser.php");
446 if ($headers = $this->extractHeaders($content, $dbi->_markup,
447 $with_toclink, $with_counter,
448 $levels, $firstlevelstyle, $basepage))
450 foreach ($headers as $h) {
451 // proper heading indent
452 $level = $h['level'];
453 $indent = $level - 1;
454 $link = new WikiPageName($pagename,$page,$h['anchor']);
455 $li = WikiLink($link,'known',$h['text']);
456 // Hack to suppress pagename before #
457 // $li->_attr["href"] = strstr($li->_attr["href"], '#');
458 $list->pushContent(HTML::p(HTML::raw
459 (str_repeat($indentstr,$indent)),$li));
462 $list->setAttr('style','display:'.($jshide?'none;':'block;'));
463 $open = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowOpen.png");
464 $close = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowClosed.png");
467 $toctoggleid = GenerateId("toctoggle");
469 $toclink = HTML(_("Table of Contents"),
471 HTML::a(array('id'=>'TOC')),
474 'class'=>'wikiaction',
475 'title'=>_("Click to display to TOC"),
476 'onclick'=>"toggletoc(this, '".$open."', '".$close."', '".$toclistid."')",
477 'alt' => 'toctoggle',
478 'src' => $jshide ? $close : $open )));
480 $toclink = HTML::a(array('id'=>'TOC',
481 'class'=>'wikiaction',
482 'title'=>_("Click to display"),
483 'onclick'=>"toggletoc(this, '".$open."', '".$close."', '".$toclistid."')"),
484 _("Table of Contents"),
485 HTML::span(array('style'=>'display:none',
486 'id'=>$toctoggleid)," "));
487 $html->pushContent(HTML::p(array('class'=>'toctitle'), $toclink));
489 $html->pushContent($list);
490 if (count($headers) == 0) {
491 // Do not display an empty TOC
492 $html->setAttr('style','display:none;');
502 // c-hanging-comment-ender-p: nil
503 // indent-tabs-mode: nil