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