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