4 Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5 Copyright 2008 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 * <?plugin 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 getVersion() {
54 return preg_replace("/[Revision: $]/", '',
58 function getDefaultArguments() {
59 return array('extracollapse' => 1, // provide an entry +/- link to collapse
60 'firstlevelstyle' => 'number', // 'number', 'letter' or 'roman'
61 'headers' => "1,2,3,4,5", // "!!!"=>h2, "!!"=>h3, "!"=>h4
62 // "1"=>h2, "2"=>h3, "3"=>h4, "4"=>h5, "5"=>h6
63 'indentstr' => ' ',
64 'jshide' => 0, // collapsed TOC as DHTML button
65 'liststyle' => 'dl', // 'dl' or 'ul' or 'ol'
66 'noheader' => 0, // omit "Table of Contents" header
67 'notoc' => 0, // do not display TOC, only number headers
68 'pagename' => '[pagename]', // TOC of another page here?
69 'position' => 'full', // full, right or left
72 'with_toclink' => 0, // link back to TOC
75 // Initialisation of toc counter
76 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) {
84 for($i = $level+1; $i <= 5; $i++) {
89 function _roman_counter($number) {
94 $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
95 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
97 foreach ($lookup as $roman => $value) {
98 $matches = intval($n / $value);
99 $result .= str_repeat($roman, $matches);
105 function _letter_counter($number) {
107 return chr(ord("A") + $number - 1);
109 return chr(ord("A") + ($number/26) - 1) . chr(ord("A") + ($number%26));
113 // Get string corresponding to the current title
114 function _getCounter(&$counter, $level, $firstlevelstyle) {
115 if ($firstlevelstyle == 'roman') {
116 $str= $this->_roman_counter($counter[1]);
117 } else if ($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 function preg_quote ($heading) {
130 return str_replace(array("/",".","?","*"),
131 array('\/','\.','\?','\*'), $heading);
134 // Get HTML header corresponding to current level (level is set of ! or =)
135 function _getHeader($level) {
137 $count = substr_count($level,'!');
143 $count = substr_count($level,'=');
154 function _quote($heading) {
155 if (TOC_FULL_SYNTAX ) {
156 $theading = TransformInline($heading);
158 return preg_quote($theading->asXML(), "/");
160 return XmlContent::_quote(preg_quote($heading, "/"));
162 return XmlContent::_quote(preg_quote($heading, "/"));
167 * @param $hstart id (in $content) of heading start
168 * @param $hend id (in $content) of heading end
170 function searchHeader ($content, $start_index, $heading,
171 $level, &$hstart, &$hend, $basepage=false) {
174 $h = $this->_getHeader($level);
175 $qheading = $this->_quote($heading);
176 for ($j=$start_index; $j < count($content); $j++) {
177 if (is_string($content[$j])) {
178 if (preg_match("/<$h>$qheading<\/$h>/",
182 elseif (isa($content[$j], 'cached_link'))
184 if (method_exists($content[$j],'asXML')) {
185 $content[$j]->_basepage = $basepage;
186 $content[$j] = $content[$j]->asXML();
188 $content[$j] = $content[$j]->asString();
189 // shortcut for single wikiword or link headers
190 if ($content[$j] == $heading
191 and substr($content[$j-1],-4,4) == "<$h>"
192 and substr($content[$j+1],0,5) == "</$h>")
196 return $j; // single wikiword
198 elseif (TOC_FULL_SYNTAX) {
199 //DONE: To allow "!! WikiWord link" or !! http://anylink/
200 // Check against joined content (after cached_plugininvocation).
201 // The first link is the anchor then.
202 if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j-1])) {
205 for ($k=max($j-1,$start_index);$k<count($content);$k++) {
206 if (is_string($content[$k]))
207 $joined .= $content[$k];
208 elseif (method_exists($content[$k],'asXML'))
209 $joined .= $content[$k]->asXML();
211 $joined .= $content[$k]->asString();
212 if (preg_match("/<$h>$qheading<\/$h>/",$joined)) {
221 trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
225 /** prevent from duplicate anchors,
226 * beautify spaces: " " => "_" and not "x20."
228 function _nextAnchor($s) {
229 static $anchors = array();
231 $s = str_replace(' ','_',$s);
234 while (!empty($anchors[$anchor])) {
235 $anchor = sprintf("%s_%d",$s,$i++);
237 $anchors[$anchor] = $i;
241 // Feature request: proper nesting; multiple levels (e.g. 1,3)
242 function extractHeaders (&$content, &$markup, $backlink=0,
243 $counter=0, $levels=false, $firstlevelstyle='number', $basepage='')
245 if (!$levels) $levels = array(1,2);
246 $tocCounter = $this->_initTocCounter();
251 for ($i=0; $i<count($content); $i++) {
252 foreach ($levels as $level) {
253 if ($level < 1 or $level > 5) continue;
254 $phpwikiclassiclevel = 4 -$level;
255 $wikicreolelevel = $level + 1;
256 if ($phpwikiclassiclevel < 1 or $phpwikiclassiclevel > 3) continue;
257 if ((preg_match('/^\s*(!{'.$phpwikiclassiclevel.','.$phpwikiclassiclevel.'})([^!].*)$/', $content[$i], $match))
258 or (preg_match('/^\s*(={'.$wikicreolelevel.','.$wikicreolelevel.'})([^=].*)$/', $content[$i], $match)) )
260 $this->_tocCounter($tocCounter, $level);
261 if (!strstr($content[$i],'#[')) {
262 $s = trim($match[2]);
263 // If it is Wikicreole syntax, remove '='s at the end
264 if (string_starts_with($match[1], "=")) {
268 $anchor = $this->_nextAnchor($s);
269 $manchor = MangleXmlIdentifier($anchor);
272 $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle).' '.$s;
274 $headers[] = array('text' => $texts,
277 // Change original wikitext, but that is useless art...
278 $content[$i] = $match[1]." #[|$manchor][$s|#TOC]";
279 // And now change the to be printed markup (XmlTree):
280 // Search <hn>$s</hn> line in markup
281 /* Url for backlink */
282 $url = WikiURL(new WikiPageName($basepage,false,"TOC"));
283 $j = $this->searchHeader($markup->_content, $j, $s,
284 $match[1], $hstart, $hend,
286 if ($j and isset($markup->_content[$j])) {
287 $x = $markup->_content[$j];
288 $qheading = $this->_quote($s);
290 $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
291 if (($hstart === 0) && is_string($markup->_content[$j])) {
294 $anchorString = "<a href=\"$url\" name=\"$manchor\">$counterString</a> - \$2";
296 $anchorString = "<a href=\"$url\" name=\"$manchor\">\$2</a>";
298 $anchorString = "<a name=\"$manchor\"></a>";
300 $anchorString .= "$counterString - ";
302 if ($x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
303 "\$1$anchorString\$2\$3",$x,1)) {
305 $x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
306 "\$1$anchorString\$3",
307 $markup->_content[$j],1);
309 $markup->_content[$j] = $x;
312 $x = $markup->_content[$hstart];
313 $h = $this->_getHeader($match[1]);
317 $anchorString = "\$1<a href=\"$url\" name=\"$manchor\">$counterString</a> - ";
319 /* Not possible to make a backlink on a
320 * title with a WikiWord */
321 $anchorString = "\$1<a name=\"$manchor\"></a>";
325 $anchorString = "\$1<a name=\"$manchor\"></a>";
327 $anchorString .= "$counterString - ";
329 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
330 $anchorString, $x, 1);
332 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
334 $markup->_content[$hstart],1);
336 $markup->_content[$hstart] = $x;
346 function run($dbi, $argstr, &$request, $basepage) {
348 extract($this->getArgs($argstr, $request));
350 // Expand relative page names.
351 $page = new WikiPageName($pagename, $basepage);
352 $pagename = $page->name;
355 return $this->error(_("no page specified"));
357 if ($jshide and isBrowserIE() and browserDetect("Mac")) {
358 //trigger_error(_("jshide set to 0 on Mac IE"), E_USER_NOTICE);
361 if (($notoc) or ($liststyle == 'ol')) {
364 $page = $dbi->getPage($pagename);
365 $current = $page->getCurrentRevision();
366 //FIXME: I suspect this only to crash with Apache2
367 if (!$current->get('markup') or $current->get('markup') < 2) {
368 if (in_array(php_sapi_name(),array('apache2handler','apache2filter'))) {
369 trigger_error(_("CreateToc disabled for old markup"), E_USER_WARNING);
373 $content = $current->getContent();
374 $html = HTML::div(array('class' => 'toc', 'id'=>'toc'));
376 $html->setAttr('style','display:none;');
378 if (($position == "left") or ($position == "right")) {
379 $html->setAttr('style','float:'.$position.'; width:'.$width.';');
381 $list = HTML::div(array('id'=>'toclist'));
382 if (!strstr($headers,",")) {
383 $headers = array($headers);
385 $headers = explode(",",$headers);
388 foreach ($headers as $h) {
389 //replace !!! with level 1, ...
390 if (strstr($h,"!")) {
391 $hcount = substr_count($h,'!');
392 $level = min(max(1, $hcount),3);
395 $level = min(max(1, (int) $h), 5);
400 require_once("lib/InlineParser.php");
401 if ($headers = $this->extractHeaders($content, $dbi->_markup,
402 $with_toclink, $with_counter,
403 $levels, $firstlevelstyle, $basepage))
405 foreach ($headers as $h) {
406 // proper heading indent
407 $level = $h['level'];
408 $indent = $level - 1;
409 $link = new WikiPageName($pagename,$page,$h['anchor']);
410 $li = WikiLink($link,'known',$h['text']);
411 $list->pushContent(HTML::p(HTML::raw
412 (str_repeat($indentstr,$indent)),$li));
415 $list->setAttr('style','display:'.($jshide?'none;':'block;'));
416 $open = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowOpen.png");
417 $close = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowClosed.png");
418 $html->pushContent(Javascript("
419 function toggletoc(a) {
420 var toc=document.getElementById('toclist')
421 //toctoggle=document.getElementById('toctoggle')
423 var close='".$close."'
424 if (toc.style.display=='none') {
425 toc.style.display='block'
426 a.title='"._("Click to hide the TOC")."'
429 toc.style.display='none';
430 a.title='"._("Click to display")."'
437 $toclink = HTML(_("Table of Contents"),
439 HTML::a(array('name'=>'TOC')),
442 'class'=>'wikiaction',
443 'title'=>_("Click to display to TOC"),
444 'onclick'=>"toggletoc(this)",
446 'alt' => 'toctoggle',
447 'src' => $jshide ? $close : $open )));
449 $toclink = HTML::a(array('name'=>'TOC',
450 'class'=>'wikiaction',
451 'title'=>_("Click to display"),
452 'onclick'=>"toggletoc(this)"),
453 _("Table of Contents"),
454 HTML::span(array('style'=>'display:none',
455 'id'=>'toctoggle')," "));
456 $html->pushContent(HTML::p(array('id'=>'toctitle'), $toclink));
458 $html->pushContent($list);
459 if (count($headers) == 0) {
460 // Do not display an empty TOC
461 $html->setAttr('style','display:none;');
472 // c-hanging-comment-ender-p: nil
473 // indent-tabs-mode: nil