]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/CreateToc.php
Display correct TOC in history
[SourceForge/phpwiki.git] / lib / plugin / CreateToc.php
1 <?php // -*-php-*-
2 // rcs_id('$Id$');
3 /*
4  * Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5  * Copyright 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
6  *
7  * This file is part of PhpWiki.
8  *
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.
13  *
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.
18  *
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
22  */
23
24 /**
25  * CreateToc:  Create a Table of Contents and automatically link to headers
26  *
27  * Usage:
28  *  <<CreateToc arguments>>
29  * @author:  Reini Urban, Marc-Etienne Vargenau
30  *
31  * Known problems:
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.
37  * - some constructs might incorrectly be recognized as a header
38  *   (e.g. lines starting with "!!!" or "==" inside <verbatim>)
39  */
40
41 if (!defined('TOC_FULL_SYNTAX'))
42     define('TOC_FULL_SYNTAX', 1);
43
44 class WikiPlugin_CreateToc
45 extends WikiPlugin
46 {
47     function getName() {
48         return _("CreateToc");
49     }
50
51     function getDescription() {
52         return _("Create a Table of Contents and automatically link to headers");
53     }
54
55     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' => '&nbsp;&nbsp;',
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
67                      'width'     => '200px',
68                      'with_counter' => 0,
69                      'with_toclink' => 0,             // link back to TOC
70                      'version'   => false,
71                     );
72     }
73     // Initialisation of toc counter
74     function _initTocCounter() {
75         $counter = array(1=>0, 2=>0, 3=>0, 4=>0, 5=>0);
76         return $counter;
77     }
78
79     // Update toc counter with a new title
80     function _tocCounter(&$counter, $level) {
81         $counter[$level]++;
82         for($i = $level+1; $i <= 5; $i++) {
83             $counter[$i] = 0;
84         }
85     }
86
87     function _roman_counter($number) {
88
89         $n = intval($number);
90         $result = '';
91
92         $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
93                         'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
94
95         foreach ($lookup as $roman => $value) {
96             $matches = intval($n / $value);
97             $result .= str_repeat($roman, $matches);
98             $n = $n % $value;
99         }
100         return $result;
101     }
102
103     function _letter_counter($number) {
104         if ($number <= 26) {
105             return chr(ord("A") + $number - 1);
106         } else {
107             return chr(ord("A") + ($number/26) - 1) . chr(ord("A") + ($number%26));
108         }
109     }
110
111     // Get string corresponding to the current title
112     function _getCounter(&$counter, $level, $firstlevelstyle) {
113         if ($firstlevelstyle == 'roman') {
114             $str= $this->_roman_counter($counter[1]);
115         } else if ($firstlevelstyle == 'letter') {
116             $str= $this->_letter_counter($counter[1]);
117         } else {
118             $str=$counter[1];
119         }
120         for($i = 2; $i <= 5; $i++) {
121             if($counter[$i] != 0)
122                 $str .= '.'.$counter[$i];
123         }
124         return $str;
125     }
126
127     function preg_quote ($heading) {
128         return str_replace(array("/",".","?","*"),
129                                array('\/','\.','\?','\*'), $heading);
130     }
131
132     // Get HTML header corresponding to current level (level is set of ! or =)
133     function _getHeader($level) {
134
135         $count = substr_count($level,'!');
136         switch ($count) {
137             case 3: return "h2";
138             case 2: return "h3";
139             case 1: return "h4";
140         }
141         $count = substr_count($level,'=');
142         switch ($count) {
143             case 2: return "h2";
144             case 3: return "h3";
145             case 4: return "h4";
146             case 5: return "h5";
147             case 6: return "h6";
148         }
149         return "";
150     }
151
152     function _quote($heading) {
153         if (TOC_FULL_SYNTAX ) {
154             $theading = TransformInline($heading);
155             if ($theading)
156                 return preg_quote($theading->asXML(), "/");
157             else
158                 return XmlContent::_quote(preg_quote($heading, "/"));
159         } else {
160             return XmlContent::_quote(preg_quote($heading, "/"));
161         }
162     }
163
164     /*
165      * @param $hstart id (in $content) of heading start
166      * @param $hend   id (in $content) of heading end
167      */
168     function searchHeader ($content, $start_index, $heading,
169                            $level, &$hstart, &$hend, $basepage=false) {
170         $hstart = 0;
171         $hend = 0;
172         $h = $this->_getHeader($level);
173         $qheading = $this->_quote($heading);
174         for ($j=$start_index; $j < count($content); $j++) {
175             if (is_string($content[$j])) {
176                 if (preg_match("/<$h>$qheading<\/$h>/",
177                                    $content[$j]))
178                     return $j;
179             }
180             elseif (isa($content[$j], 'cached_link'))
181             {
182                 if (method_exists($content[$j],'asXML')) {
183                     $content[$j]->_basepage = $basepage;
184                     $content[$j] = $content[$j]->asXML();
185                 } else
186                     $content[$j] = $content[$j]->asString();
187                 // shortcut for single wikiword or link headers
188                 if ($content[$j] == $heading
189                     and substr($content[$j-1],-4,4) == "<$h>"
190                     and substr($content[$j+1],0,5) == "</$h>")
191                 {
192                     $hstart = $j-1;
193                     $hend = $j+1;
194                     return $j; // single wikiword
195                 }
196                 elseif (TOC_FULL_SYNTAX) {
197                     //DONE: To allow "!! WikiWord link" or !! http://anylink/
198                     // Check against joined content (after cached_plugininvocation).
199                     // The first link is the anchor then.
200                     if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j-1])) {
201                         $hstart = $j-1;
202                         $joined = '';
203                         for ($k=max($j-1,$start_index);$k<count($content);$k++) {
204                             if (is_string($content[$k]))
205                                 $joined .= $content[$k];
206                             elseif (method_exists($content[$k],'asXML'))
207                                 $joined .= $content[$k]->asXML();
208                             else
209                                 $joined .= $content[$k]->asString();
210                             if (preg_match("/<$h>$qheading<\/$h>/",$joined)) {
211                                 $hend=$k;
212                                 return $k;
213                             }
214                         }
215                     }
216                 }
217             }
218         }
219         trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
220         return 0;
221     }
222
223     /** prevent from duplicate anchors,
224      *  beautify spaces: " " => "_" and not "x20."
225      */
226     function _nextAnchor($s) {
227         static $anchors = array();
228
229         $s = str_replace(' ','_',$s);
230         $i = 1;
231         $anchor = $s;
232         while (!empty($anchors[$anchor])) {
233             $anchor = sprintf("%s_%d",$s,$i++);
234         }
235         $anchors[$anchor] = $i;
236         return $anchor;
237     }
238
239     // We have to find headers in both:
240     // - classic Phpwiki syntax (lines starting with "!", "!!" or "!!!")
241     // - Wikicreole syntax (lines starting with "==", "===", etc.)
242     // We must omit lines starting with "!" if inside a Mediawiki table
243     // (they represent a table header)
244     // Some constructs might incorrectly be recognized as a header
245     // (e.g. lines starting with "!!!" or "==" inside <verbatim>)
246     // Feature request: proper nesting; multiple levels (e.g. 1,3)
247     function extractHeaders (&$content, &$markup, $backlink=0,
248                              $counter=0, $levels=false, $firstlevelstyle='number', $basepage='')
249     {
250         if (!$levels) $levels = array(1,2);
251         $tocCounter = $this->_initTocCounter();
252         reset($levels);
253         sort($levels);
254         $headers = array();
255         $j = 0;
256         $insidetable = false;
257         for ($i=0; $i<count($content); $i++) {
258             if (preg_match('/^\s*{\|/', $content[$i])) {
259                $insidetable = true;
260                continue;
261             }
262             if (preg_match('/^\s*\|}/', $content[$i])) {
263                $insidetable = false;
264                continue;
265             }
266             if ($insidetable) {
267                continue;
268             }
269             foreach ($levels as $level) {
270                 if ($level < 1 or $level > 5) continue;
271                 $phpwikiclassiclevel = 4 -$level;
272                 $wikicreolelevel = $level + 1;
273                 $trim = trim($content[$i]);
274
275                 if ((((strpos($trim, '=') === 0))
276                       && (preg_match('/^\s*(={'.$wikicreolelevel.','.$wikicreolelevel.'})([^=].*)$/', $content[$i], $match)))
277                    or (((strpos($trim, '!') === 0))
278                       && ((preg_match('/^\s*(!{'.$phpwikiclassiclevel.','.$phpwikiclassiclevel.'})([^!].*)$/', $content[$i], $match))))) {
279                     $this->_tocCounter($tocCounter, $level);
280                     if (!strstr($content[$i],'#[')) {
281                         $s = trim($match[2]);
282                         // If it is Wikicreole syntax, remove '='s at the end
283                         if (string_starts_with($match[1], "=")) {
284                             $s = trim($s, "=");
285                             $s = trim($s);
286                         }
287                         $anchor = $this->_nextAnchor($s);
288                         $manchor = MangleXmlIdentifier($anchor);
289                         $texts = $s;
290                         if($counter) {
291                             $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle).' '.$s;
292                         }
293                         $headers[] = array('text' => $texts,
294                                            'anchor' => $anchor,
295                                            'level' => $level);
296                         // Change original wikitext, but that is useless art...
297                         $content[$i] = $match[1]." #[|$manchor][$s|#TOC]";
298                         // And now change the to be printed markup (XmlTree):
299                         // Search <hn>$s</hn> line in markup
300                         /* Url for backlink */
301                         $url = WikiURL(new WikiPageName($basepage,false,"TOC"));
302
303                         $j = $this->searchHeader($markup->_content, $j, $s,
304                                                  $match[1], $hstart, $hend,
305                                                  $markup->_basepage);
306                         if ($j and isset($markup->_content[$j])) {
307                             $x = $markup->_content[$j];
308                             $qheading = $this->_quote($s);
309                             if ($counter)
310                                  $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
311                             if (($hstart === 0) && is_string($markup->_content[$j])) {
312                                 if ($backlink) {
313                                     if ($counter)
314                                         $anchorString = "<a href=\"$url\" id=\"$manchor\">$counterString</a> - \$2";
315                                     else
316                                         $anchorString = "<a href=\"$url\" id=\"$manchor\">\$2</a>";
317                                 } else {
318                                     $anchorString = "<a id=\"$manchor\"></a>";
319                                     if ($counter)
320                                         $anchorString .= "$counterString - ";
321                                 }
322                                 if ($x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
323                                                       "\$1$anchorString\$2\$3",$x,1)) {
324                                     if ($backlink) {
325                                         $x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
326                                                           "\$1$anchorString\$3",
327                                                           $markup->_content[$j],1);
328                                     }
329                                     $markup->_content[$j] = $x;
330                                 }
331                             } else {
332                                 $x = $markup->_content[$hstart];
333                                 $h = $this->_getHeader($match[1]);
334
335                                 if ($backlink) {
336                                     if ($counter) {
337                                         $anchorString = "\$1<a href=\"$url\" id=\"$manchor\">$counterString</a> - ";
338                                     } else {
339                                         /* Not possible to make a backlink on a
340                                          * title with a WikiWord */
341                                         $anchorString = "\$1<a id=\"$manchor\"></a>";
342                                     }
343                                 }
344                                 else {
345                                     $anchorString = "\$1<a id=\"$manchor\"></a>";
346                                     if ($counter)
347                                         $anchorString .= "$counterString - ";
348                                 }
349                                 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
350                                                   $anchorString, $x, 1);
351                                 if ($backlink) {
352                                     $x =  preg_replace("/(<$h>)(?!.*<\/$h>)/",
353                                                       $anchorString,
354                                                       $markup->_content[$hstart],1);
355                                 }
356                                 $markup->_content[$hstart] = $x;
357                             }
358                         }
359                     }
360                 }
361             }
362         }
363         return $headers;
364     }
365
366     function run($dbi, $argstr, &$request, $basepage) {
367         global $WikiTheme;
368         extract($this->getArgs($argstr, $request));
369         if ($pagename) {
370             // Expand relative page names.
371             $page = new WikiPageName($pagename, $basepage);
372             $pagename = $page->name;
373         }
374         if (!$pagename) {
375             return $this->error(_("No page specified."));
376         }
377         if (isBrowserIE() and browserDetect("Mac")) {
378             $jshide = 0;
379         }
380         if (($notoc) or ($liststyle == 'ol')) {
381             $with_counter = 1;
382         }
383
384         // Check if page exists.
385         if (!($dbi->isWikiPage($pagename))) {
386             return $this->error(sprintf(_("Page '%s' does not exist."), $pagename));
387         }
388
389         // Check if user is allowed to get the page.
390         if (!mayAccessPage ('view', $pagename)) {
391             return $this->error(sprintf(_("Illegal access to page %s: no read access"),
392             $pagename));
393         }
394
395         $page = $dbi->getPage($pagename);
396
397         if ($version) {
398             $r = $page->getRevision($version);
399             if ((!$r) || ($r->hasDefaultContents())) {
400                 return $this->error(sprintf(_("%s: no such revision %d."),
401                                             $pagename, $version));
402             }
403         } else {
404             $r = $page->getCurrentRevision();
405         }
406
407         $current = $page->getCurrentRevision();
408         //FIXME: I suspect this only to crash with Apache2
409         if (!$current->get('markup') or $current->get('markup') < 2) {
410             if (in_array(php_sapi_name(),array('apache2handler','apache2filter'))) {
411                 return $this->error(_("CreateToc disabled for old markup."));
412             }
413         }
414
415         $content = $r->getContent();
416
417         $html = HTML::div(array('class' => 'toc', 'id'=> GenerateId("toc")));
418         if ($notoc) {
419             $html->setAttr('style','display:none;');
420         }
421         if (($position == "left") or ($position == "right")) {
422             $html->setAttr('style','float:'.$position.'; width:'.$width.';');
423         }
424         $toclistid = GenerateId("toclist");
425         $list = HTML::div(array('id'=>$toclistid, 'class'=>'toclist'));
426         if (!strstr($headers,",")) {
427             $headers = array($headers);
428         } else {
429             $headers = explode(",",$headers);
430         }
431         $levels = array();
432         foreach ($headers as $h) {
433             //replace !!! with level 1, ...
434             if (strstr($h,"!")) {
435                 $hcount = substr_count($h,'!');
436                 $level = min(max(1, $hcount),3);
437                 $levels[] = $level;
438             } else {
439                 $level = min(max(1, (int) $h), 5);
440                 $levels[] = $level;
441             }
442         }
443         if (TOC_FULL_SYNTAX)
444             require_once("lib/InlineParser.php");
445         if ($headers = $this->extractHeaders($content, $dbi->_markup,
446                                              $with_toclink, $with_counter,
447                                              $levels, $firstlevelstyle, $basepage))
448         {
449             foreach ($headers as $h) {
450                 // proper heading indent
451                 $level = $h['level'];
452                 $indent = $level - 1;
453                 $link = new WikiPageName($pagename,$page,$h['anchor']);
454                 $li = WikiLink($link,'known',$h['text']);
455                 // Hack to suppress pagename before #
456                 // $li->_attr["href"] = strstr($li->_attr["href"], '#');
457                 $list->pushContent(HTML::p(HTML::raw
458                        (str_repeat($indentstr,$indent)),$li));
459             }
460         }
461         $list->setAttr('style','display:'.($jshide?'none;':'block;'));
462         $open = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowOpen.png");
463         $close = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowClosed.png");
464       if ($noheader) {
465       } else {
466         $toctoggleid = GenerateId("toctoggle");
467         if ($extracollapse)
468             $toclink = HTML(_("Table of Contents"),
469                             " ",
470                             HTML::a(array('id'=>'TOC')),
471                             HTML::img(array(
472                                             'id'=>$toctoggleid,
473                                             'class'=>'wikiaction',
474                                             'title'=>_("Click to display to TOC"),
475                                             'onclick'=>"toggletoc(this, '".$open."', '".$close."', '".$toclistid."')",
476                                             'alt' => 'toctoggle',
477                                             'src' => $jshide ? $close : $open )));
478         else
479             $toclink = HTML::a(array('id'=>'TOC',
480                                      'class'=>'wikiaction',
481                                      'title'=>_("Click to display"),
482                                      'onclick'=>"toggletoc(this, '".$open."', '".$close."', '".$toclistid."')"),
483                                _("Table of Contents"),
484                                HTML::span(array('style'=>'display:none',
485                                                 'id'=>$toctoggleid)," "));
486         $html->pushContent(HTML::p(array('class'=>'toctitle'), $toclink));
487       }
488       $html->pushContent($list);
489       if (count($headers) == 0) {
490           // Do not display an empty TOC
491           $html->setAttr('style','display:none;');
492       }
493       return $html;
494     }
495 };
496
497 // Local Variables:
498 // mode: php
499 // tab-width: 8
500 // c-basic-offset: 4
501 // c-hanging-comment-ender-p: nil
502 // indent-tabs-mode: nil
503 // End:
504 ?>