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
71 'with_toclink' => 0, // link back to TOC
74 // Initialisation of toc counter
75 function _initTocCounter() {
76 $counter = array(1=>0, 2=>0, 3=>0, 4=>0, 5=>0);
80 // Update toc counter with a new title
81 function _tocCounter(&$counter, $level) {
83 for($i = $level+1; $i <= 5; $i++) {
88 function _roman_counter($number) {
93 $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
94 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
96 foreach ($lookup as $roman => $value) {
97 $matches = intval($n / $value);
98 $result .= str_repeat($roman, $matches);
104 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 function _getCounter(&$counter, $level, $firstlevelstyle) {
114 if ($firstlevelstyle == 'roman') {
115 $str= $this->_roman_counter($counter[1]);
116 } else if ($firstlevelstyle == 'letter') {
117 $str= $this->_letter_counter($counter[1]);
121 for($i = 2; $i <= 5; $i++) {
122 if($counter[$i] != 0)
123 $str .= '.'.$counter[$i];
128 function preg_quote ($heading) {
129 return str_replace(array("/",".","?","*"),
130 array('\/','\.','\?','\*'), $heading);
133 // Get HTML header corresponding to current level (level is set of ! or =)
134 function _getHeader($level) {
136 $count = substr_count($level,'!');
142 $count = substr_count($level,'=');
153 function _quote($heading) {
154 if (TOC_FULL_SYNTAX ) {
155 $theading = TransformInline($heading);
157 return preg_quote($theading->asXML(), "/");
159 return XmlContent::_quote(preg_quote($heading, "/"));
161 return XmlContent::_quote(preg_quote($heading, "/"));
166 * @param $hstart id (in $content) of heading start
167 * @param $hend id (in $content) of heading end
169 function searchHeader ($content, $start_index, $heading,
170 $level, &$hstart, &$hend, $basepage=false) {
173 $h = $this->_getHeader($level);
174 $qheading = $this->_quote($heading);
175 for ($j=$start_index; $j < count($content); $j++) {
176 if (is_string($content[$j])) {
177 if (preg_match("/<$h>$qheading<\/$h>/",
181 elseif (isa($content[$j], 'cached_link'))
183 if (method_exists($content[$j],'asXML')) {
184 $content[$j]->_basepage = $basepage;
185 $content[$j] = $content[$j]->asXML();
187 $content[$j] = $content[$j]->asString();
188 // shortcut for single wikiword or link headers
189 if ($content[$j] == $heading
190 and substr($content[$j-1],-4,4) == "<$h>"
191 and substr($content[$j+1],0,5) == "</$h>")
195 return $j; // single wikiword
197 elseif (TOC_FULL_SYNTAX) {
198 //DONE: To allow "!! WikiWord link" or !! http://anylink/
199 // Check against joined content (after cached_plugininvocation).
200 // The first link is the anchor then.
201 if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j-1])) {
204 for ($k=max($j-1,$start_index);$k<count($content);$k++) {
205 if (is_string($content[$k]))
206 $joined .= $content[$k];
207 elseif (method_exists($content[$k],'asXML'))
208 $joined .= $content[$k]->asXML();
210 $joined .= $content[$k]->asString();
211 if (preg_match("/<$h>$qheading<\/$h>/",$joined)) {
220 trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
224 /** prevent from duplicate anchors,
225 * beautify spaces: " " => "_" and not "x20."
227 function _nextAnchor($s) {
228 static $anchors = array();
230 $s = str_replace(' ','_',$s);
233 while (!empty($anchors[$anchor])) {
234 $anchor = sprintf("%s_%d",$s,$i++);
236 $anchors[$anchor] = $i;
240 // Feature request: proper nesting; multiple levels (e.g. 1,3)
241 function extractHeaders (&$content, &$markup, $backlink=0,
242 $counter=0, $levels=false, $firstlevelstyle='number', $basepage='')
244 if (!$levels) $levels = array(1,2);
245 $tocCounter = $this->_initTocCounter();
250 for ($i=0; $i<count($content); $i++) {
251 foreach ($levels as $level) {
252 if ($level < 1 or $level > 5) continue;
253 $phpwikiclassiclevel = 4 -$level;
254 $wikicreolelevel = $level + 1;
255 if ($phpwikiclassiclevel < 1 or $phpwikiclassiclevel > 3) continue;
256 if ((preg_match('/^\s*(!{'.$phpwikiclassiclevel.','.$phpwikiclassiclevel.'})([^!].*)$/', $content[$i], $match))
257 or (preg_match('/^\s*(={'.$wikicreolelevel.','.$wikicreolelevel.'})([^=].*)$/', $content[$i], $match)) )
259 $this->_tocCounter($tocCounter, $level);
260 if (!strstr($content[$i],'#[')) {
261 $s = trim($match[2]);
262 // If it is Wikicreole syntax, remove '='s at the end
263 if (string_starts_with($match[1], "=")) {
267 $anchor = $this->_nextAnchor($s);
268 $manchor = MangleXmlIdentifier($anchor);
271 $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle).' '.$s;
273 $headers[] = array('text' => $texts,
276 // Change original wikitext, but that is useless art...
277 $content[$i] = $match[1]." #[|$manchor][$s|#TOC]";
278 // And now change the to be printed markup (XmlTree):
279 // Search <hn>$s</hn> line in markup
280 /* Url for backlink */
281 $url = WikiURL(new WikiPageName($basepage,false,"TOC"));
282 $j = $this->searchHeader($markup->_content, $j, $s,
283 $match[1], $hstart, $hend,
285 if ($j and isset($markup->_content[$j])) {
286 $x = $markup->_content[$j];
287 $qheading = $this->_quote($s);
289 $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
290 if (($hstart === 0) && is_string($markup->_content[$j])) {
293 $anchorString = "<a href=\"$url\" name=\"$manchor\">$counterString</a> - \$2";
295 $anchorString = "<a href=\"$url\" name=\"$manchor\">\$2</a>";
297 $anchorString = "<a name=\"$manchor\"></a>";
299 $anchorString .= "$counterString - ";
301 if ($x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
302 "\$1$anchorString\$2\$3",$x,1)) {
304 $x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
305 "\$1$anchorString\$3",
306 $markup->_content[$j],1);
308 $markup->_content[$j] = $x;
311 $x = $markup->_content[$hstart];
312 $h = $this->_getHeader($match[1]);
316 $anchorString = "\$1<a href=\"$url\" name=\"$manchor\">$counterString</a> - ";
318 /* Not possible to make a backlink on a
319 * title with a WikiWord */
320 $anchorString = "\$1<a name=\"$manchor\"></a>";
324 $anchorString = "\$1<a name=\"$manchor\"></a>";
326 $anchorString .= "$counterString - ";
328 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
329 $anchorString, $x, 1);
331 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
333 $markup->_content[$hstart],1);
335 $markup->_content[$hstart] = $x;
345 function run($dbi, $argstr, &$request, $basepage) {
347 extract($this->getArgs($argstr, $request));
349 // Expand relative page names.
350 $page = new WikiPageName($pagename, $basepage);
351 $pagename = $page->name;
354 return $this->error(_("no page specified"));
356 if ($jshide and isBrowserIE() and browserDetect("Mac")) {
357 //trigger_error(_("jshide set to 0 on Mac IE"), E_USER_NOTICE);
360 if (($notoc) or ($liststyle == 'ol')) {
363 $page = $dbi->getPage($pagename);
364 $current = $page->getCurrentRevision();
365 //FIXME: I suspect this only to crash with Apache2
366 if (!$current->get('markup') or $current->get('markup') < 2) {
367 if (in_array(php_sapi_name(),array('apache2handler','apache2filter'))) {
368 trigger_error(_("CreateToc disabled for old markup"), E_USER_WARNING);
372 $content = $current->getContent();
373 $html = HTML::div(array('class' => 'toc', 'id'=>'toc'));
375 $html->setAttr('style','display:none;');
377 if (($position == "left") or ($position == "right")) {
378 $html->setAttr('style','float:'.$position.'; width:'.$width.';');
380 $list = HTML::div(array('id'=>'toclist'));
381 if (!strstr($headers,",")) {
382 $headers = array($headers);
384 $headers = explode(",",$headers);
387 foreach ($headers as $h) {
388 //replace !!! with level 1, ...
389 if (strstr($h,"!")) {
390 $hcount = substr_count($h,'!');
391 $level = min(max(1, $hcount),3);
394 $level = min(max(1, (int) $h), 5);
399 require_once("lib/InlineParser.php");
400 if ($headers = $this->extractHeaders($content, $dbi->_markup,
401 $with_toclink, $with_counter,
402 $levels, $firstlevelstyle, $basepage))
404 foreach ($headers as $h) {
405 // proper heading indent
406 $level = $h['level'];
407 $indent = $level - 1;
408 $link = new WikiPageName($pagename,$page,$h['anchor']);
409 $li = WikiLink($link,'known',$h['text']);
410 $list->pushContent(HTML::p(HTML::raw
411 (str_repeat($indentstr,$indent)),$li));
414 $list->setAttr('style','display:'.($jshide?'none;':'block;'));
415 $open = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowOpen.png");
416 $close = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowClosed.png");
417 $html->pushContent(Javascript("
418 function toggletoc(a) {
419 var toc=document.getElementById('toclist')
420 //toctoggle=document.getElementById('toctoggle')
422 var close='".$close."'
423 if (toc.style.display=='none') {
424 toc.style.display='block'
425 a.title='"._("Click to hide the TOC")."'
428 toc.style.display='none';
429 a.title='"._("Click to display")."'
436 $toclink = HTML(_("Table of Contents"),
438 HTML::a(array('name'=>'TOC')),
441 'class'=>'wikiaction',
442 'title'=>_("Click to display to TOC"),
443 'onclick'=>"toggletoc(this)",
445 'alt' => 'toctoggle',
446 'src' => $jshide ? $close : $open )));
448 $toclink = HTML::a(array('name'=>'TOC',
449 'class'=>'wikiaction',
450 'title'=>_("Click to display"),
451 'onclick'=>"toggletoc(this)"),
452 _("Table of Contents"),
453 HTML::span(array('style'=>'display:none',
454 'id'=>'toctoggle')," "));
455 $html->pushContent(HTML::p(array('id'=>'toctitle'), $toclink));
457 $html->pushContent($list);
458 if (count($headers) == 0) {
459 // Do not display an empty TOC
460 $html->setAttr('style','display:none;');
471 // c-hanging-comment-ender-p: nil
472 // indent-tabs-mode: nil