2 rcs_id('$Id: CreateToc.php,v 1.32 2007-01-20 11:25:30 rurban Exp $');
4 Copyright 2004,2005 $ThePhpWikiProgrammingTeam
6 This file is part of PhpWiki.
8 PhpWiki is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 PhpWiki is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with PhpWiki; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 * CreateToc: Automatically link to headers
27 * <?plugin CreateToc headers=!!!,!! with_toclink||=1
29 * @author: Reini Urban
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 _("Automatically link headers at the top");
53 function getVersion() {
54 return preg_replace("/[Revision: $]/", '',
55 "\$Revision: 1.32 $");
58 function getDefaultArguments() {
59 return array( 'pagename' => '[pagename]', // TOC of another page here?
60 // or headers=1,2,3 is also possible.
61 'headers' => "!!!,!!,!", // "!!!"=>h1, "!!"=>h2, "!"=>h3
62 'noheader' => 0, // omit <h1>Table of Contents</h1>
63 'position' => 'right', // or left
64 'with_toclink' => 0, // link back to TOC
65 'jshide' => 0, // collapsed TOC as DHTML button
66 'extracollapse' => 1, // provide an entry +/- link to collapse
67 'liststyle' => 'dl', // 'dl' or 'ul' or 'ol'
68 'indentstr' => ' ',
72 // Initialisation of toc counter
73 function _initTocCounter() {
74 $counter = array(1=>1, 2=>0, 3=>0);
78 // Update toc counter with a new title
79 function _tocCounter(&$counter, $level) {
82 for($i = $level; $i > 0; $i--) {
87 // Get string corresponding to the current title
88 function _getCounter(&$counter, $level) {
90 for($i = 2; $i > 0; $i--) {
92 $str .= '.'.$counter[$i];
97 function preg_quote ($heading) {
98 return str_replace(array("/",".","?","*"),
99 array('\/','\.','\?','\*'), $heading);
102 // Get HTML header corresponding to current level (level is set of !)
103 function _getHeader($level) {
104 $count = substr_count($level,'!');
106 case 1: $h = "h4"; break;
107 case 2: $h = "h3"; break;
108 case 3: $h = "h2"; break;
113 function _quote($heading) {
114 if (TOC_FULL_SYNTAX ) {
115 $theading = TransformInline($heading);
117 return preg_quote($theading->asXML(), "/");
119 return XmlContent::_quote(preg_quote($heading, "/"));
121 return XmlContent::_quote(preg_quote($heading, "/"));
126 * @param $hstart id (in $content) of heading start
127 * @param $hend id (in $content) of heading end
129 function searchHeader ($content, $start_index, $heading,
130 $level, &$hstart, &$hend, $basepage=false) {
133 $h = $this->_getHeader($level);
134 $qheading = $this->_quote($heading);
135 for ($j=$start_index; $j < count($content); $j++) {
136 if (is_string($content[$j])) {
137 if (preg_match("/<$h>$qheading<\/$h>/",
141 elseif (isa($content[$j], 'cached_link'))
143 if (method_exists($content[$j],'asXML')) {
144 $content[$j]->_basepage = $basepage;
145 $content[$j] = $content[$j]->asXML();
147 $content[$j] = $content[$j]->asString();
148 // shortcut for single wikiword or link headers
149 if ($content[$j] == $heading
150 and substr($content[$j-1],-4,4) == "<$h>"
151 and substr($content[$j+1],0,5) == "</$h>")
155 return $j; // single wikiword
157 elseif (TOC_FULL_SYNTAX) {
158 //DONE: To allow "!! WikiWord link" or !! http://anylink/
159 // Check against joined content (after cached_plugininvocation).
160 // The first link is the anchor then.
161 if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j-1])) {
164 for ($k=max($j-1,$start_index);$k<count($content);$k++) {
165 if (is_string($content[$k]))
166 $joined .= $content[$k];
167 elseif (method_exists($content[$k],'asXML'))
168 $joined .= $content[$k]->asXML();
170 $joined .= $content[$k]->asString();
171 if (preg_match("/<$h>$qheading<\/$h>/",$joined)) {
180 trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
184 /** prevent from duplicate anchors,
185 * beautify spaces: " " => "_" and not "x20."
187 function _nextAnchor($s) {
188 static $anchors = array();
190 $s = str_replace(' ','_',$s);
193 while (!empty($anchors[$anchor])) {
194 $anchor = sprintf("%s_%d",$s,$i++);
196 $anchors[$anchor] = $i;
200 // Feature request: proper nesting; multiple levels (e.g. 1,3)
201 function extractHeaders (&$content, &$markup, $backlink=0,
202 $counter=0, $levels=false, $basepage='')
204 if (!$levels) $levels = array(1,2);
205 $tocCounter = $this->_initTocCounter();
210 for ($i=0; $i<count($content); $i++) {
211 foreach ($levels as $level) {
212 if ($level < 1 or $level > 3) continue;
213 if (preg_match('/^\s*(!{'.$level.','.$level.'})([^!].*)$/',
214 $content[$i], $match))
216 $this->_tocCounter($tocCounter, $level);
217 if (!strstr($content[$i],'#[')) {
218 $s = trim($match[2]);
219 $anchor = $this->_nextAnchor($s);
220 $manchor = MangleXmlIdentifier($anchor);
223 $texts = $this->_getCounter($tocCounter, $level).' '.$s;
225 $headers[] = array('text' => $texts,
228 // Change original wikitext, but that is useless art...
229 $content[$i] = $match[1]." #[|$manchor][$s|#TOC]";
230 // And now change the to be printed markup (XmlTree):
231 // Search <hn>$s</hn> line in markup
232 /* Url for backlink */
233 $url = WikiURL(new WikiPageName($basepage,false,"TOC"));
234 $j = $this->searchHeader($markup->_content, $j, $s,
235 $match[1], $hstart, $hend,
237 if ($j and isset($markup->_content[$j])) {
238 $x = $markup->_content[$j];
239 $qheading = $this->_quote($s);
241 $counterString = $this->_getCounter($tocCounter, $level);
242 if (($hstart === 0) && is_string($markup->_content[$j])) {
245 $anchorString = "<a href=\"$url\" name=\"$manchor\">$counterString</a> - \$2";
247 $anchorString = "<a href=\"$url\" name=\"$manchor\">\$2</a>";
249 $anchorString = "<a name=\"$manchor\"></a>";
251 $anchorString .= "$counterString - ";
253 if ($x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
254 "\$1$anchorString\$2\$3",$x,1)) {
256 $x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
257 "\$1$anchorString\$3",
258 $markup->_content[$j],1);
260 $markup->_content[$j] = $x;
263 $x = $markup->_content[$hstart];
264 $h = $this->_getHeader($match[1]);
268 $anchorString = "\$1<a href=\"$url\" name=\"$manchor\">$counterString</a> - ";
270 /* Not possible to make a backlink on a
271 * title with a WikiWord */
272 $anchorString = "\$1<a name=\"$manchor\"></a>";
276 $anchorString = "\$1<a name=\"$manchor\"></a>";
278 $anchorString .= "$counterString - ";
280 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
281 $anchorString, $x, 1);
283 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
285 $markup->_content[$hstart],1);
287 $markup->_content[$hstart] = $x;
297 function run($dbi, $argstr, &$request, $basepage) {
298 extract($this->getArgs($argstr, $request));
300 // Expand relative page names.
301 $page = new WikiPageName($pagename, $basepage);
302 $pagename = $page->name;
305 return $this->error(_("no page specified"));
307 if ($jshide and isBrowserIE() and browserDetect("Mac")) {
308 //trigger_error(_("jshide set to 0 on Mac IE"), E_USER_NOTICE);
311 $page = $dbi->getPage($pagename);
312 $current = $page->getCurrentRevision();
313 //FIXME: I suspect this only to crash with Apache2
314 if (!$current->get('markup') or $current->get('markup') < 2) {
315 if (in_array(php_sapi_name(),array('apache2handler','apache2filter'))) {
316 trigger_error(_("CreateToc disabled for old markup"), E_USER_WARNING);
320 $content = $current->getContent();
321 $html = HTML::div(array('class' => 'toc', 'id'=>'toc'));
322 if ($liststyle == 'dl')
323 $list = HTML::dl(array('id'=>'toclist','class' => 'toc'));
324 elseif ($liststyle == 'ul')
325 $list = HTML::ul(array('id'=>'toclist','class' => 'toc'));
326 elseif ($liststyle == 'ol')
327 $list = HTML::ol(array('id'=>'toclist','class' => 'toc'));
328 if (!strstr($headers,",")) {
329 $headers = array($headers);
331 $headers = explode(",",$headers);
334 foreach ($headers as $h) {
335 //replace !!! with level 1, ...
336 if (strstr($h,"!")) {
337 $hcount = substr_count($h,'!');
338 $level = min(max(1, $hcount),3);
341 $level = min(max(1, (int) $h), 3);
346 require_once("lib/InlineParser.php");
347 if ($headers = $this->extractHeaders($content, $dbi->_markup,
348 $with_toclink, $with_counter,
351 foreach ($headers as $h) {
352 // proper heading indent
353 $level = $h['level'];
354 $indent = 3 - $level;
355 $link = new WikiPageName($pagename,$page,$h['anchor']);
356 $li = WikiLink($link,'known',$h['text']);
357 if ($liststyle == 'dl')
358 $list->pushContent(HTML::dt(HTML::raw
359 (str_repeat($indentstr,$indent)),$li));
361 $list->pushContent(HTML::li(HTML::raw
362 (str_repeat($indentstr,$indent)),$li));
365 $list->setAttr('style','display:'.($jshide?'none;':'block;'));
366 $html->pushContent(Javascript("
367 function toggletoc(a) {
368 toc=document.getElementById('toclist')
369 toctoggle=document.getElementById('toctoggle')
370 if (toc.style.display=='none') {
371 toc.style.display='block'
372 a.title='"._("Click to hide the TOC")."'
373 toctoggle.innerHTML='[-]'
375 toc.style.display='none';
376 a.title='"._("Click to display")."'
377 toctoggle.innerHTML='[+]'
381 $toclink = HTML(_("Table Of Contents"),
383 HTML::a(array('name'=>'TOC',
385 'class'=>'wikiaction',
386 'title'=>_("Click to display to TOC"),
387 'onclick'=>"toggletoc(this)"),
388 $jshide?'[+]':'[-]'));
390 $toclink = HTML::a(array('name'=>'TOC',
391 'class'=>'wikiaction',
392 'title'=>_("Click to display"),
393 'onclick'=>"toggletoc(this)"),
394 _("Table Of Contents"),
395 HTML::span(array('style'=>'display:none',
396 'id'=>'toctoggle')," "));
397 $html->pushContent(HTML::h4($toclink));
398 $html->pushContent($list);
403 // $Log: not supported by cvs2svn $
404 // Revision 1.31 2007/01/09 12:35:05 rurban
405 // Change align to position. Add extracollapse. js now always active, jshide just denotes the initial state.
407 // Revision 1.30 2006/12/22 17:49:38 rurban
410 // Revision 1.29 2006/04/15 12:26:54 rurban
411 // need basepage for subpages like /Remove (within CreateTOC)
413 // Revision 1.28 2005/10/12 06:15:25 rurban
416 // Revision 1.27 2005/10/10 19:50:45 rurban
417 // fix the missing formatting problems, add with_counter arg by ?? (20050106), Thanks to ManuelVacelet for the testcase
419 // Revision 1.26 2004/09/20 14:07:16 rurban
420 // fix Constant toc_full_syntax already defined warning
422 // Revision 1.25 2004/07/08 20:30:07 rurban
423 // plugin->run consistency: request as reference, added basepage.
424 // encountered strange bug in AllPages (and the test) which destroys ->_dbi
426 // Revision 1.24 2004/06/28 13:27:03 rurban
427 // CreateToc disabled for old markup and Apache2 only
429 // Revision 1.23 2004/06/28 13:13:58 rurban
430 // CreateToc disabled for old markup
432 // Revision 1.22 2004/06/15 14:56:37 rurban
433 // more allow_call_time_pass_reference false fixes
435 // Revision 1.21 2004/06/13 09:45:23 rurban
436 // display bug workaround for MacIE browsers, jshide: 0
438 // Revision 1.20 2004/05/11 13:57:46 rurban
439 // enable TOC_FULL_SYNTAX per default
440 // don't <a name>$header</a> to disable css formatting for such anchors
441 // => <a name></a>$header
443 // Revision 1.19 2004/05/08 16:59:27 rurban
444 // requires optional TOC_FULL_SYNTAX constnat to enable full link and
445 // wikiword syntax in headers.
447 // Revision 1.18 2004/04/29 21:55:15 rurban
448 // fixed TOC backlinks with USE_PATH_INFO false
449 // with_toclink=1, sf.net bug #940682
451 // Revision 1.17 2004/04/26 19:43:03 rurban
452 // support most cases of header markup. fixed duplicate MangleXmlIdentifier name
454 // Revision 1.16 2004/04/26 14:46:14 rurban
457 // Revision 1.14 2004/04/21 04:29:50 rurban
458 // write WikiURL consistently (not WikiUrl)
460 // Revision 1.12 2004/03/22 14:13:53 rurban
461 // fixed links to equal named headers
463 // Revision 1.11 2004/03/15 09:52:59 rurban
464 // jshide button: dynamic titles
466 // Revision 1.10 2004/03/14 20:30:21 rurban
469 // Revision 1.9 2004/03/09 19:24:20 rurban
473 // Revision 1.8 2004/03/09 19:05:12 rurban
474 // new liststyle arg. default: dl (no bullets)
476 // Revision 1.7 2004/03/09 11:51:54 rurban
477 // support jshide=1: DHTML button hide/unhide TOC
479 // Revision 1.6 2004/03/09 10:25:37 rurban
480 // slightly better formatted TOC indentation
482 // Revision 1.5 2004/03/09 08:57:10 rurban
483 // convert space to "_" instead of "x20." in anchors
484 // proper heading indent
485 // handle duplicate headers
486 // allow multiple headers like "!!!,!!" or "1,2"
488 // Revision 1.4 2004/03/02 18:21:29 rurban
491 // Revision 1.1 2004/03/01 18:10:28 rurban
492 // first version, without links, anchors and jscript folding
501 // c-hanging-comment-ender-p: nil
502 // indent-tabs-mode: nil