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