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