]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/CreateToc.php
Use paragraphs instead of lists
[SourceForge/phpwiki.git] / lib / plugin / CreateToc.php
1 <?php // -*-php-*-
2 rcs_id('$Id$');
3 /*
4  Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5  Copyright 2008 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  *  <?plugin 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  */
38
39 if (!defined('TOC_FULL_SYNTAX'))
40     define('TOC_FULL_SYNTAX', 1);
41
42 class WikiPlugin_CreateToc
43 extends WikiPlugin
44 {
45     function getName() {
46         return _("CreateToc");
47     }
48
49     function getDescription() {
50         return _("Create a Table of Contents and automatically link to headers");
51     }
52
53     function getVersion() {
54         return preg_replace("/[Revision: $]/", '',
55                             "\$Revision$");
56     }
57
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' => '&nbsp;&nbsp;',
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
70                      'with_counter' => 0,
71                      'with_toclink' => 0,             // link back to TOC
72                     );
73     }
74     // Initialisation of toc counter
75     function _initTocCounter() {
76         $counter = array(1=>0, 2=>0, 3=>0, 4=>0, 5=>0);
77         return $counter;
78     }
79
80     // Update toc counter with a new title
81     function _tocCounter(&$counter, $level) {
82         $counter[$level]++;
83         for($i = $level+1; $i <= 5; $i++) {
84             $counter[$i] = 0;
85         }
86     }
87
88     function _roman_counter($number) {
89
90         $n = intval($number);
91         $result = '';
92
93         $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
94                         'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
95
96         foreach ($lookup as $roman => $value) {
97             $matches = intval($n / $value);
98             $result .= str_repeat($roman, $matches);
99             $n = $n % $value;
100         }
101         return $result;
102     }
103
104     function _letter_counter($number) {
105         if ($number <= 26) {
106             return chr(ord("A") + $number - 1);
107         } else {
108             return chr(ord("A") + ($number/26) - 1) . chr(ord("A") + ($number%26));
109         }
110     }
111
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]);
118         } else {
119             $str=$counter[1];
120         }
121         for($i = 2; $i <= 5; $i++) {
122             if($counter[$i] != 0)
123                 $str .= '.'.$counter[$i];
124         }
125         return $str;
126     }
127
128     function preg_quote ($heading) {
129         return str_replace(array("/",".","?","*"),
130                            array('\/','\.','\?','\*'), $heading);
131     }
132     
133     // Get HTML header corresponding to current level (level is set of ! or =)
134     function _getHeader($level) {
135
136         $count = substr_count($level,'!');
137         switch ($count) {
138             case 3: return "h2";
139             case 2: return "h3";
140             case 1: return "h4";
141         }
142         $count = substr_count($level,'=');
143         switch ($count) {
144             case 2: return "h2";
145             case 3: return "h3";
146             case 4: return "h4";
147             case 5: return "h5";
148             case 6: return "h6";
149         }
150         return "";
151     }
152
153     function _quote($heading) {
154         if (TOC_FULL_SYNTAX ) {
155             $theading = TransformInline($heading);
156             if ($theading)
157                 return preg_quote($theading->asXML(), "/");
158             else 
159                 return XmlContent::_quote(preg_quote($heading, "/"));
160         } else {
161             return XmlContent::_quote(preg_quote($heading, "/"));
162         }
163     }
164     
165     /*
166      * @param $hstart id (in $content) of heading start
167      * @param $hend   id (in $content) of heading end
168      */
169     function searchHeader ($content, $start_index, $heading, 
170                            $level, &$hstart, &$hend, $basepage=false) {
171         $hstart = 0;
172         $hend = 0;
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>/", 
178                                $content[$j]))
179                     return $j;
180             }
181             elseif (isa($content[$j], 'cached_link'))
182             {
183                 if (method_exists($content[$j],'asXML')) {
184                     $content[$j]->_basepage = $basepage;
185                     $content[$j] = $content[$j]->asXML();
186                 } else
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>") 
192                 {
193                     $hstart = $j-1;
194                     $hend = $j+1;
195                     return $j; // single wikiword
196                 } 
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])) {
202                         $hstart = $j-1;                     
203                         $joined = '';
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();
209                             else
210                                 $joined .= $content[$k]->asString();
211                             if (preg_match("/<$h>$qheading<\/$h>/",$joined)) {
212                                 $hend=$k;
213                                 return $k;
214                             }
215                         }
216                     }
217                 }
218             }
219         }
220         trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
221         return 0;
222     }
223
224     /** prevent from duplicate anchors,
225      *  beautify spaces: " " => "_" and not "x20."
226      */
227     function _nextAnchor($s) {
228         static $anchors = array();
229
230         $s = str_replace(' ','_',$s);
231         $i = 1;
232         $anchor = $s;
233         while (!empty($anchors[$anchor])) {
234             $anchor = sprintf("%s_%d",$s,$i++);
235         }
236         $anchors[$anchor] = $i;
237         return $anchor;
238     }
239     
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='')
243     {
244         if (!$levels) $levels = array(1,2);
245         $tocCounter = $this->_initTocCounter();        
246         reset($levels);
247         sort($levels);
248         $headers = array();
249         $j = 0;
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)) )
258                 {
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], "=")) {
264                             $s = trim($s, "=");
265                             $s = trim($s);
266                         }
267                         $anchor = $this->_nextAnchor($s);
268                         $manchor = MangleXmlIdentifier($anchor);
269                         $texts = $s;
270                         if($counter) {
271                             $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle).' '.$s;
272                         }
273                         $headers[] = array('text' => $texts, 
274                                            'anchor' => $anchor, 
275                                            'level' => $level);
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, 
284                                                  $markup->_basepage);
285                         if ($j and isset($markup->_content[$j])) {
286                             $x = $markup->_content[$j];
287                             $qheading = $this->_quote($s);
288                             if ($counter)
289                                  $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
290                             if (($hstart === 0) && is_string($markup->_content[$j])) {
291                                 if ($backlink) {
292                                     if ($counter)
293                                         $anchorString = "<a href=\"$url\" name=\"$manchor\">$counterString</a> - \$2";
294                                     else
295                                         $anchorString = "<a href=\"$url\" name=\"$manchor\">\$2</a>";
296                                 } else {
297                                     $anchorString = "<a name=\"$manchor\"></a>";
298                                     if ($counter)
299                                         $anchorString .= "$counterString - ";
300                                 }
301                                 if ($x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
302                                                       "\$1$anchorString\$2\$3",$x,1)) {
303                                     if ($backlink) {
304                                         $x = preg_replace('/(<h\d>)('.$qheading.')(<\/h\d>)/',
305                                                           "\$1$anchorString\$3",
306                                                           $markup->_content[$j],1);
307                                     }
308                                     $markup->_content[$j] = $x;
309                                 }
310                             } else {
311                                 $x = $markup->_content[$hstart];
312                                 $h = $this->_getHeader($match[1]);
313
314                                 if ($backlink) {
315                                     if ($counter)
316                                         $anchorString = "\$1<a href=\"$url\" name=\"$manchor\">$counterString</a> - ";
317                                     else {
318                                         /* Not possible to make a backlink on a
319                                          * title with a WikiWord */
320                                         $anchorString = "\$1<a name=\"$manchor\"></a>";
321                                     }
322                                 }
323                                 else {
324                                     $anchorString = "\$1<a name=\"$manchor\"></a>";
325                                     if ($counter)
326                                         $anchorString .= "$counterString - ";
327                                 }
328                                 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/", 
329                                                   $anchorString, $x, 1);
330                                 if ($backlink) {
331                                     $x =  preg_replace("/(<$h>)(?!.*<\/$h>)/", 
332                                                       $anchorString,
333                                                       $markup->_content[$hstart],1);
334                                 }
335                                 $markup->_content[$hstart] = $x;
336                             }
337                         }
338                     }
339                 }
340             }
341         }
342         return $headers;
343     }
344                 
345     function run($dbi, $argstr, &$request, $basepage) {
346         global $WikiTheme;
347         extract($this->getArgs($argstr, $request));
348         if ($pagename) {
349             // Expand relative page names.
350             $page = new WikiPageName($pagename, $basepage);
351             $pagename = $page->name;
352         }
353         if (!$pagename) {
354             return $this->error(_("no page specified"));
355         }
356         if ($jshide and isBrowserIE() and browserDetect("Mac")) {
357             //trigger_error(_("jshide set to 0 on Mac IE"), E_USER_NOTICE);
358             $jshide = 0;
359         }
360         if (($notoc) or ($liststyle == 'ol')) {
361             $with_counter = 1;
362         }
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);
369                 return '';
370             }
371         }
372         $content = $current->getContent();
373         $html = HTML::div(array('class' => 'toc', 'id'=>'toc'));
374         if ($notoc) {
375             $html->setAttr('style','display:none;');
376         }
377         if (($position == "left") or ($position == "right")) {
378             $html->setAttr('style','float:'.$position.'; width:'.$width.';');
379         }
380         $list = HTML::div(array('id'=>'toclist'));
381         if (!strstr($headers,",")) {
382             $headers = array($headers); 
383         } else {
384             $headers = explode(",",$headers);
385         }
386         $levels = array();
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);
392                 $levels[] = $level;
393             } else {
394                 $level = min(max(1, (int) $h), 5);
395                 $levels[] = $level;
396             }
397         }
398         if (TOC_FULL_SYNTAX)
399             require_once("lib/InlineParser.php");
400         if ($headers = $this->extractHeaders($content, $dbi->_markup, 
401                                              $with_toclink, $with_counter, 
402                                              $levels, $firstlevelstyle, $basepage))
403         {
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));
412             }
413         }
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')
421   var open='".$open."'
422   var close='".$close."'
423   if (toc.style.display=='none') {
424     toc.style.display='block'
425     a.title='"._("Click to hide the TOC")."'
426     a.src = open
427   } else {
428     toc.style.display='none';
429     a.title='"._("Click to display")."'
430     a.src = close
431   }
432 }"));
433       if ($noheader) {
434       } else {
435         if ($extracollapse)
436             $toclink = HTML(_("Table of Contents"),
437                             " ",
438                             HTML::a(array('name'=>'TOC')),
439                             HTML::img(array(
440                                             'id'=>'toctoggle',
441                                             'class'=>'wikiaction',
442                                             'title'=>_("Click to display to TOC"),
443                                             'onclick'=>"toggletoc(this)",
444                                             'border' => 0,
445                                             'alt' => 'toctoggle',
446                                             'src' => $jshide ? $close : $open )));
447         else
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));
456       }
457       $html->pushContent($list);
458       if (count($headers) == 0) {
459           // Do not display an empty TOC
460           $html->setAttr('style','display:none;');
461       }
462       return $html;
463     }
464 };
465
466 // For emacs users
467 // Local Variables:
468 // mode: php
469 // tab-width: 8
470 // c-basic-offset: 4
471 // c-hanging-comment-ender-p: nil
472 // indent-tabs-mode: nil
473 // End:
474 ?>