]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/CreateToc.php
new liststyle arg. default: dl (no bullets)
[SourceForge/phpwiki.git] / lib / plugin / CreateToc.php
1 <?php // -*-php-*-
2 rcs_id('$Id: CreateToc.php,v 1.8 2004-03-09 19:05:12 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:   <?plugin CreateToc headers=!!!,!! with_toclink||=1 jshide||=1 align=left noheaders=0 ?>
27  * @author:  Reini Urban
28  */
29
30 class WikiPlugin_CreateToc
31 extends WikiPlugin
32 {
33     function getName() {
34         return _("CreateToc");
35     }
36
37     function getDescription() {
38         return _("Automatically link headers at the top");
39     }
40
41     function getVersion() {
42         return preg_replace("/[Revision: $]/", '',
43                             "\$Revision: 1.8 $");
44     }
45
46     function getDefaultArguments() {
47         return array( 'pagename'  => '[pagename]', // not sure yet. TOC of another page here?
48                       // or headers=1,2,3 is also possible.
49                       'headers'   => "!!!,!!,!",   // "!!!" => h1, "!!" => h2, "!" => h3
50                       'noheader'  => 0,            // omit <h1>Table of Contents</h1>
51                       'align'     => 'left',
52                       'with_toclink' => 0,         // link back to TOC
53                       'jshide'    => 0,            // collapsed TOC as DHTML button
54                       'liststyle' => 'dl',         // or 'ul' or 'ol'
55                       );
56     }
57
58     function preg_quote ($heading) {
59         return str_replace(array("/",".","?","*"),
60                            array('\/','\.','\?','\*'), $heading);
61     }
62     
63     function searchHeader ($content, $start_index, $heading, $level) {
64         $count = substr_count($level,'!');
65         switch ($count) {
66                 case 1: $h = "h4"; break;
67                 case 2: $h = "h3"; break;
68                 case 3: $h = "h2"; break;
69         }
70         for ($j=$start_index; $j<count($content); $j++) {
71             if (is_string($content[$j])) {
72                 $heading = preg_quote($heading);
73                 if (preg_match("/<$h>$heading<\/$h>/",$content[$j]))
74                     return $j;
75             }
76         }
77         trigger_error("Heading <$h> $heading </$h> not found\n", E_USER_NOTICE);
78         return 0;
79     }
80
81     /** prevent from duplicate anchors,
82      *  beautify spaces: " " => "_" and not "x20."
83      */
84     function _nextAnchor($s) {
85         static $anchors = array();
86
87         $s = str_replace(' ','_',$s);
88         $i = 1;
89         $anchor = MangleXmlIdentifier($s);
90         while (!empty($anchors[$anchor])) {
91             $anchor = MangleXmlIdentifier(sprintf("%s_%d",$s,$i++));
92         }
93         $anchors[$anchor] = $i;
94         return $anchor;
95     }
96     
97     // Feature request: proper nesting; multiple levels (e.g. 1,3)
98     function extractHeaders (&$content, &$markup, $backlink=0, $levels=false, $basepage='') {
99         if (!$levels) $levels = array(1,2);
100         reset($levels);
101         sort($levels);
102         $headers = array();
103         $j = 0;
104         for ($i=0; $i<count($content); $i++) {
105             foreach ($levels as $level) {
106                 if ($level < 1 or $level > 3) continue;
107                 if (preg_match('/^\s*(!{'.$level.','.$level.'})([^!].+)$/',$content[$i],$match)) {
108                     if (!strstr($content[$i],'#[')) {
109                         $s = trim($match[2]);
110                         $anchor = $this->_nextAnchor($s);
111                         $headers[] = array('text' => $s, 'anchor' => $anchor, 'level' => $level);
112                         // change original wikitext, but that is useless art...
113                         $content[$i] = $match[1]." #[|$anchor][$s|#TOC]";
114                         // and now change the to be printed markup (XmlTree):
115                         // search <hn>$s</hn> line in markup
116                         $j = $this->searchHeader($markup->_content, $j, $s, $match[1]);
117                         if (  $j and isset($markup->_content[$j]) and 
118                               is_string($markup->_content[$j])  ) {
119                             $x = $markup->_content[$j];
120                             $heading = preg_quote($s);
121                             if ($x = preg_replace('/(<h\d>)('.$heading.')(<\/h\d>)/',
122                                                   "\$1<a name=\"$anchor\">\$2</a>\$3",$x)) {
123                                 if ($backlink)
124                                     $x = preg_replace('/(<h\d>)('.$heading.')(<\/h\d>)/',
125                                                       "\$1<a href=\"$basepage#TOC\" name=\"$anchor\">\$2</a>\$3",
126                                                       $markup->_content[$j]);
127                                 $markup->_content[$j] = $x;
128                             }
129                         }
130                     }
131                 }
132             }
133         }
134         return $headers;
135     }
136                 
137     function run($dbi, $argstr, $request, $basepage) {
138         extract($this->getArgs($argstr, $request));
139         if ($pagename) {
140             // Expand relative page names.
141             $page = new WikiPageName($pagename, $basepage);
142             $pagename = $page->name;
143         }
144         if (!$pagename) {
145             return $this->error(_("no page specified"));
146         }
147         $page = $dbi->getPage($pagename);
148         $current = $page->getCurrentRevision();
149         $content = $current->getContent();
150         $html = HTML::div(array('class' => 'toc','align' => $align));
151         if ($liststyle == 'dl')
152             $list = HTML::dl(array('name'=>'toclist','id'=>'toclist','class' => 'toc'));
153         elseif ($liststyle == 'ul')
154             $list = HTML::ul(array('name'=>'toclist','id'=>'toclist','class' => 'toc'));
155         elseif ($liststyle == 'ol')
156             $list = HTML::ol(array('name'=>'toclist','id'=>'toclist','class' => 'toc'));
157         if (!strstr($headers,",")) {
158             $headers = array($headers); 
159         } else {
160             $headers = explode(",",$headers);
161         }
162         $levels = array();
163         foreach ($headers as $h) {
164             //replace !!! with level 1, ...
165             if (strstr($h,"!")) {
166                 $hcount = substr_count($h,'!');
167                 $level = min(max(1, $hcount),3);
168                 $levels[] = $level;
169             } else {
170                 $level = min(max(1, (int) $h), 3);
171                 $levels[] = $level;
172             }
173         }
174         if ($headers = $this->extractHeaders(&$content, &$dbi->_markup, $with_toclink, $levels, $basepage)) {
175             foreach ($headers as $h) {
176                 // proper heading indent
177                 $level = $h['level'];
178                 $indent = 3 - $level;
179                 $link = new WikiPageName($pagename,$page,$h['anchor']);
180                 $li = WikiLink($link,'known',$h['text']);
181                 if ($indent == 1)
182                     $t = HTML(HTML::raw("&nbsp;&nbsp;"),$li);
183                 elseif ($indent == 2)
184                     $t = HTML(HTML::raw("&nbsp;&nbsp;&nbsp;&nbsp;"),$li);
185                 else
186                     $t = $li;
187                 if ($liststyle == 'dl')
188                     $list->pushContent(HTML::dt($t));
189                 else
190                     $list->pushContent(HTML::li($t));
191             }
192         }
193         if ($jshide) {
194             $list->setAttr('style','display:none;');
195             $html->pushContent(Javascript("
196 function toggletoc() {
197   toc=document.getElementById('toclist');
198   if (toc.style.display=='none') {
199     toc.style.display='block';
200   } else {
201     toc.style.display='none';
202   }
203 }"));
204             $html->pushContent(HTML::h1(HTML::a(array('name'=>'TOC','class'=>'gridbutton',
205                                                       'title'=>_("Click to display"),
206                                                       'onclick'=>"toggletoc()"),
207                                                 _("Table Of Contents"))));
208         } else {
209             if (!$noheader)
210                 $html->pushContent(HTML::h1(HTML::a(array('name'=>'TOC'),_("Table Of Contents"))));
211             else 
212                 $html->pushContent(HTML::a(array('name'=>'TOC'),""));
213         }
214         $html->pushContent($list);
215         return $html;
216     }
217 };
218
219 // $Log: not supported by cvs2svn $
220 // Revision 1.7  2004/03/09 11:51:54  rurban
221 // support jshide=1: DHTML button hide/unhide TOC
222 //
223 // Revision 1.6  2004/03/09 10:25:37  rurban
224 // slightly better formatted TOC indentation
225 //
226 // Revision 1.5  2004/03/09 08:57:10  rurban
227 // convert space to "_" instead of "x20." in anchors
228 // proper heading indent
229 // handle duplicate headers
230 // allow multiple headers like "!!!,!!" or "1,2"
231 //
232 // Revision 1.4  2004/03/02 18:21:29  rurban
233 // typo: ref=>href
234 //
235 // Revision 1.1  2004/03/01 18:10:28  rurban
236 // first version, without links, anchors and jscript folding
237 //
238 //
239
240 // For emacs users
241 // Local Variables:
242 // mode: php
243 // tab-width: 8
244 // c-basic-offset: 4
245 // c-hanging-comment-ender-p: nil
246 // indent-tabs-mode: nil
247 // End:
248 ?>