]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/CreateToc.php
fixed TOC backlinks with USE_PATH_INFO false
[SourceForge/phpwiki.git] / lib / plugin / CreateToc.php
1 <?php // -*-php-*-
2 rcs_id('$Id: CreateToc.php,v 1.18 2004-04-29 21:55:15 rurban Exp $');
3 /*
4  Copyright 2004 $ThePhpWikiProgrammingTeam
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /**
24  * CreateToc:  Automatically link to headers
25  *
26  * Usage:   
27  *  <?plugin CreateToc headers=!!!,!! with_toclink||=1 
28  *                     jshide||=1 ?>
29  * @author:  Reini Urban
30  */
31
32 class WikiPlugin_CreateToc
33 extends WikiPlugin
34 {
35     function getName() {
36         return _("CreateToc");
37     }
38
39     function getDescription() {
40         return _("Automatically link headers at the top");
41     }
42
43     function getVersion() {
44         return preg_replace("/[Revision: $]/", '',
45                             "\$Revision: 1.18 $");
46     }
47
48     function getDefaultArguments() {
49         return array( 'pagename'  => '[pagename]', // not sure yet. TOC of another page here?
50                       // or headers=1,2,3 is also possible.
51                       'headers'   => "!!!,!!,!",   // "!!!" => h1, "!!" => h2, "!" => h3
52                       'noheader'  => 0,            // omit <h1>Table of Contents</h1>
53                       'align'     => 'left',
54                       'with_toclink' => 0,         // link back to TOC
55                       'jshide'    => 0,            // collapsed TOC as DHTML button
56                       'liststyle' => 'dl',         // or 'ul' or 'ol'
57                       'indentstr' => '&nbsp;&nbsp;',
58                       );
59     }
60
61     function preg_quote ($heading) {
62         return str_replace(array("/",".","?","*"),
63                            array('\/','\.','\?','\*'), $heading);
64     }
65     
66     function searchHeader ($content, $start_index, $heading, $level) {
67         $count = substr_count($level,'!');
68         switch ($count) {
69                 case 1: $h = "h4"; break;
70                 case 2: $h = "h3"; break;
71                 case 3: $h = "h2"; break;
72         }
73         $theading = TransformInline($heading);
74         $qheading = preg_quote($theading->asString());
75         
76         for ($j=$start_index; $j < count($content); $j++) {
77             if (is_string($content[$j])) {
78                 if (preg_match("/<$h>$qheading<\/$h>/",$content[$j])) {
79                     return $j;
80                 }
81             } elseif (isa($content[$j],'cached_wikilink')) {
82                 // shortcut for single wikiword headers
83                 $content[$j] = $content[$j]->asString();
84                 if ($content[$j] == $heading and 
85                     substr($content[$j-1],-4,4) == "<$h>" and
86                     substr($content[$j+1],0,5) == "</$h>") {
87                     return $j; // single wikiword
88                 } else {
89                     //DONE: To allow "!! WikiWord link"
90                     // Split heading into WikiWords and check against 
91                     // joined content (after cached_plugininvocation).
92                     // The first wikilink is the anchor then.
93                     $joined = '';
94                     for ($k=max($j-1,$start_index); $k < count($content); $k++) {
95                         $joined .= is_string($content[$k]) ? $content[$k] 
96                                                            : $content[$k]->asString();
97                     }
98                     if (preg_match("/<$h>$qheading<\/$h>/",$joined))
99                         return $j;
100                 }
101             }
102         }
103         trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
104         return 0;
105     }
106
107     /** prevent from duplicate anchors,
108      *  beautify spaces: " " => "_" and not "x20."
109      */
110     function _nextAnchor($s) {
111         static $anchors = array();
112
113         $s = str_replace(' ','_',$s);
114         $i = 1;
115         $anchor = $s;
116         while (!empty($anchors[$anchor])) {
117             $anchor = sprintf("%s_%d",$s,$i++);
118         }
119         $anchors[$anchor] = $i;
120         return $anchor;
121     }
122     
123     // Feature request: proper nesting; multiple levels (e.g. 1,3)
124     function extractHeaders (&$content, &$markup, $backlink=0, $levels=false, $basepage='') {
125         if (!$levels) $levels = array(1,2);
126         reset($levels);
127         sort($levels);
128         $headers = array();
129         $j = 0;
130         for ($i=0; $i<count($content); $i++) {
131             foreach ($levels as $level) {
132                 if ($level < 1 or $level > 3) continue;
133                 if (preg_match('/^\s*(!{'.$level.','.$level.'})([^!].*)$/',$content[$i],$match)) {
134                     if (!strstr($content[$i],'#[')) {
135                         $s = trim($match[2]);
136                         $anchor = $this->_nextAnchor($s);
137                         $manchor = MangleXmlIdentifier($anchor);
138                         $headers[] = array('text' => $s, 'anchor' => $anchor, 'level' => $level);
139                         // Change original wikitext, but that is useless art...
140                         $content[$i] = $match[1]." #[|$manchor][$s|#TOC]";
141                         // And now change the to be printed markup (XmlTree):
142                         // Search <hn>$s</hn> line in markup
143                         //Fixme: Find non-singleworded wikilink'ed headers also.
144                         $j = $this->searchHeader($markup->_content, $j, $s, $match[1]);
145                         if ($j and isset($markup->_content[$j])) {
146                             $x = $markup->_content[$j];
147                             if (is_string($markup->_content[$j])) {
148                                 $x = $markup->_content[$j];
149                                 $heading = preg_quote($s);
150                                 if ($x = preg_replace('/(<h\d>)('.$heading.')(<\/h\d>)/',
151                                                       "\$1<a name=\"$manchor\">\$2</a>\$3",$x,1)) {
152                                     if ($backlink) {
153                                         $url = WikiURL(new WikiPageName($basepage,false,"TOC"));
154                                         $x = preg_replace('/(<h\d>)('.$heading.')(<\/h\d>)/',
155                                                           "\$1<a href=\"$url\" name=\"$manchor\">\$2</a>\$3",
156                                                           $markup->_content[$j],1);
157                                     }
158                                     $markup->_content[$j] = $x;
159                                 }
160                             }
161                             elseif (isa($markup->_content[$j],'cached_wikilink')) {
162                                 $label = isset($x->_label) ? $x->_label : false;
163                                 $markup->_content[$j] = HTML::a(array('name'=>$manchor),WikiLink($x->_page, 'auto', $label));
164                             }
165                         }
166                     }
167                 }
168             }
169         }
170         return $headers;
171     }
172                 
173     function run($dbi, $argstr, $request, $basepage) {
174         extract($this->getArgs($argstr, $request));
175         if ($pagename) {
176             // Expand relative page names.
177             $page = new WikiPageName($pagename, $basepage);
178             $pagename = $page->name;
179         }
180         if (!$pagename) {
181             return $this->error(_("no page specified"));
182         }
183         $page = $dbi->getPage($pagename);
184         $current = $page->getCurrentRevision();
185         $content = $current->getContent();
186         $html = HTML::div(array('class' => 'toc','align' => $align));
187         if ($liststyle == 'dl')
188             $list = HTML::dl(array('name'=>'toclist','id'=>'toclist','class' => 'toc'));
189         elseif ($liststyle == 'ul')
190             $list = HTML::ul(array('name'=>'toclist','id'=>'toclist','class' => 'toc'));
191         elseif ($liststyle == 'ol')
192             $list = HTML::ol(array('name'=>'toclist','id'=>'toclist','class' => 'toc'));
193         if (!strstr($headers,",")) {
194             $headers = array($headers); 
195         } else {
196             $headers = explode(",",$headers);
197         }
198         $levels = array();
199         foreach ($headers as $h) {
200             //replace !!! with level 1, ...
201             if (strstr($h,"!")) {
202                 $hcount = substr_count($h,'!');
203                 $level = min(max(1, $hcount),3);
204                 $levels[] = $level;
205             } else {
206                 $level = min(max(1, (int) $h), 3);
207                 $levels[] = $level;
208             }
209         }
210         require_once("lib/InlineParser.php");
211         if ($headers = $this->extractHeaders(&$content, &$dbi->_markup, $with_toclink, $levels, $basepage)) {
212             foreach ($headers as $h) {
213                 // proper heading indent
214                 $level = $h['level'];
215                 $indent = 3 - $level;
216                 $link = new WikiPageName($pagename,$page,$h['anchor']);
217                 $li = WikiLink($link,'known',$h['text']);
218                 if ($liststyle == 'dl')
219                     $list->pushContent(HTML::dt(HTML::raw(str_repeat($indentstr,$indent)),$li));
220                 else
221                     $list->pushContent(HTML::li(HTML::raw(str_repeat($indentstr,$indent)),$li));
222             }
223         }
224         if ($jshide) {
225             $list->setAttr('style','display:none;');
226             $html->pushContent(Javascript("
227 function toggletoc(a) {
228   toc=document.getElementById('toclist');
229   if (toc.style.display=='none') {
230     toc.style.display='block';
231     a.title='"._("Click to hide the TOC")."';
232   } else {
233     toc.style.display='none';
234     a.title='"._("Click to display")."';
235   }
236 }"));
237             $html->pushContent(HTML::h4(HTML::a(array('name'=>'TOC',
238                                                       'class'=>'wikiaction',
239                                                       'title'=>_("Click to display"),
240                                                       'onclick'=>"toggletoc(this)"),
241                                                 _("Table Of Contents"))));
242         } else {
243             if (!$noheader)
244                 $html->pushContent(HTML::h2(HTML::a(array('name'=>'TOC'),_("Table Of Contents"))));
245             else 
246                 $html->pushContent(HTML::a(array('name'=>'TOC'),""));
247         }
248         $html->pushContent($list);
249         return $html;
250     }
251 };
252
253 // $Log: not supported by cvs2svn $
254 // Revision 1.17  2004/04/26 19:43:03  rurban
255 // support most cases of header markup. fixed duplicate MangleXmlIdentifier name
256 //
257 // Revision 1.16  2004/04/26 14:46:14  rurban
258 // better comments
259 //
260 // Revision 1.14  2004/04/21 04:29:50  rurban
261 // write WikiURL consistently (not WikiUrl)
262 //
263 // Revision 1.12  2004/03/22 14:13:53  rurban
264 // fixed links to equal named headers
265 //
266 // Revision 1.11  2004/03/15 09:52:59  rurban
267 // jshide button: dynamic titles
268 //
269 // Revision 1.10  2004/03/14 20:30:21  rurban
270 // jshide button
271 //
272 // Revision 1.9  2004/03/09 19:24:20  rurban
273 // custom indentstr
274 // h2 toc header
275 //
276 // Revision 1.8  2004/03/09 19:05:12  rurban
277 // new liststyle arg. default: dl (no bullets)
278 //
279 // Revision 1.7  2004/03/09 11:51:54  rurban
280 // support jshide=1: DHTML button hide/unhide TOC
281 //
282 // Revision 1.6  2004/03/09 10:25:37  rurban
283 // slightly better formatted TOC indentation
284 //
285 // Revision 1.5  2004/03/09 08:57:10  rurban
286 // convert space to "_" instead of "x20." in anchors
287 // proper heading indent
288 // handle duplicate headers
289 // allow multiple headers like "!!!,!!" or "1,2"
290 //
291 // Revision 1.4  2004/03/02 18:21:29  rurban
292 // typo: ref=>href
293 //
294 // Revision 1.1  2004/03/01 18:10:28  rurban
295 // first version, without links, anchors and jscript folding
296 //
297 //
298
299 // For emacs users
300 // Local Variables:
301 // mode: php
302 // tab-width: 8
303 // c-basic-offset: 4
304 // c-hanging-comment-ender-p: nil
305 // indent-tabs-mode: nil
306 // End:
307 ?>