]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Try to dl() load the iconv extension, if not already loaded
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.255 2006-12-22 16:53:38 rurban Exp $');
2 /*
3  Copyright 1999,2000,2001,2002,2004,2005 $ThePhpWikiProgrammingTeam
4
5  This file is part of PhpWiki.
6
7  PhpWiki is free software; you can redistribute it and/or modify
8  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation; either version 2 of the License, or
10  (at your option) any later version.
11
12  PhpWiki is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  GNU General Public License for more details.
16
17  You should have received a copy of the GNU General Public License
18  along with PhpWiki; if not, write to the Free Software
19  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 /*
23   Standard functions for Wiki functionality
24     WikiURL ($pagename, $args, $get_abs_url)
25     AbsoluteURL ($url)
26     IconForLink ($protocol_or_url)
27     PossiblyGlueIconToText($proto_or_url, $text)
28     IsSafeURL($url)
29     LinkURL ($url, $linktext)
30     LinkImage ($url, $alt)
31
32     SplitQueryArgs ($query_args)
33     LinkPhpwikiURL ($url, $text, $basepage)
34     ConvertOldMarkup ($content, $markup_type = "block")
35     MangleXmlIdentifier($str)
36     UnMangleXmlIdentifier($str)
37     
38     class Stack { push($item), pop(), cnt(), top() }
39     class Alert { show() }
40     class WikiPageName {getParent(),isValid(),getWarnings() }
41
42     expand_tabs($str, $tab_width = 8)
43     SplitPagename ($page)
44     NoSuchRevision ($request, $page, $version)
45     TimezoneOffset ($time, $no_colon)
46     Iso8601DateTime ($time)
47     Rfc2822DateTime ($time)
48     ParseRfc1123DateTime ($timestr)
49     CTime ($time)
50     ByteFormatter ($bytes = 0, $longformat = false)
51     __printf ($fmt)
52     __sprintf ($fmt)
53     __vsprintf ($fmt, $args)
54
55     file_mtime ($filename)
56     sort_file_mtime ($a, $b)
57     class fileSet {fileSet($directory, $filepattern = false), 
58                    getFiles($exclude=false, $sortby=false, $limit=false) }
59     class ListRegexExpand { listMatchCallback($item, $key),  
60                             expandRegex ($index, &$pages) }
61
62     glob_to_pcre ($glob)
63     glob_match ($glob, $against, $case_sensitive = true)
64     explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
65     explodePageList ($input, $perm = false)
66     isa ($object, $class)
67     can ($object, $method)
68     function_usable ($function_name)
69     wikihash ($x)
70     better_srand ($seed = '')
71     count_all ($arg)
72     isSubPage ($pagename)
73     subPageSlice ($pagename, $pos)
74
75     phpwiki_version ()
76     isWikiWord ($word)
77     obj2hash ($obj, $exclude = false, $fields = false)
78     isUtf8String ($s)
79     fixTitleEncoding ($s)
80     url_get_contents ($uri)
81     GenerateId ($name)
82     firstNWordsOfContent ($n, $content)
83     extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
84     isExternalReferrer()
85
86   function: LinkInterWikiLink($link, $linktext)
87   moved to: lib/interwiki.php
88   function: linkExistingWikiWord($wikiword, $linktext, $version)
89   moved to: lib/Theme.php
90   function: LinkUnknownWikiWord($wikiword, $linktext)
91   moved to: lib/Theme.php
92   function: UpdateRecentChanges($dbi, $pagename, $isnewpage) 
93   gone see: lib/plugin/RecentChanges.php
94 */
95 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
96 else define('_PHPWIKI_STDLIB_LOADED', true);
97
98 define('MAX_PAGENAME_LENGTH', 100);
99             
100 /**
101  * Convert string to a valid XML identifier.
102  *
103  * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
104  *
105  * We would like to have, e.g. named anchors within wiki pages
106  * names like "Table of Contents" --- clearly not a valid XML
107  * fragment identifier.
108  *
109  * This function implements a one-to-one map from {any string}
110  * to {valid XML identifiers}.
111  *
112  * It does this by
113  * converting all bytes not in [A-Za-z0-9:_-],
114  * and any leading byte not in [A-Za-z] to 'xbb.',
115  * where 'bb' is the hexadecimal representation of the
116  * character.
117  *
118  * As a special case, the empty string is converted to 'empty.'
119  *
120  * @param string $str
121  * @return string
122  */
123 function MangleXmlIdentifier($str) {
124     if (!$str)
125         return 'empty.';
126     
127     return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
128                         "'x' . sprintf('%02x', ord('\\0')) . '.'",
129                         $str);
130 }
131
132 function UnMangleXmlIdentifier($str) {
133     if ($str == 'empty.')
134         return '';
135     return preg_replace('/x(\w\w)\./e',
136                         "sprintf('%c', hex('\\0'))",
137                         $str);
138 }
139
140 /**
141  * Returns a name for the WIKI_ID cookie that should be unique on the host.
142  * But for it to be unique you must have set a unique WIKI_NAME in your
143  * configuration file.
144  * @return string The name of the WIKI_ID cookie to use for this wiki.
145  */
146 function GetCookieName() {
147     return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
148 }
149
150 /**
151  * Generates a valid URL for a given Wiki pagename.
152  * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
153  *                        If a WikiDB_Page object function will extract the name to link to.
154  *                        If a WikiDB_PageRevision object function will extract the name to link to.
155  * @param array $args 
156  * @param boolean $get_abs_url Default value is false.
157  * @return string The absolute URL to the page passed as $pagename.
158  */
159 function WikiURL($pagename, $args = '', $get_abs_url = false) {
160     $anchor = false;
161     
162     if (is_object($pagename)) {
163         if (isa($pagename, 'WikiDB_Page')) {
164             $pagename = $pagename->getName();
165         }
166         elseif (isa($pagename, 'WikiDB_PageRevision')) {
167             $page = $pagename->getPage();
168             $args['version'] = $pagename->getVersion();
169             $pagename = $page->getName();
170         }
171         elseif (isa($pagename, 'WikiPageName')) {
172             $anchor = $pagename->anchor;
173             $pagename = $pagename->name;
174         } else { // php5
175             $anchor = $pagename->anchor;
176             $pagename = $pagename->name;
177         }
178     }
179     if (!$get_abs_url and DEBUG and $GLOBALS['request']->getArg('start_debug')) {
180         if (!$args)
181             $args = 'start_debug=' . $GLOBALS['request']->getArg('start_debug');
182         elseif (is_array($args))
183             $args['start_debug'] = $GLOBALS['request']->getArg('start_debug');
184         else 
185             $args .= '&start_debug=' . $GLOBALS['request']->getArg('start_debug');
186     }
187     if (is_array($args)) {
188         $enc_args = array();
189         foreach ($args as $key => $val) {
190             // avoid default args
191             if (USE_PATH_INFO and $key == 'pagename')
192                 ; 
193             elseif ($key == 'action' and $val == 'browse')
194                 ;
195             elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
196               $enc_args[] = urlencode($key) . '=' . urlencode($val);
197         }
198         $args = join('&', $enc_args);
199     }
200
201     if (USE_PATH_INFO or !empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX)) {
202         $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
203         $url = $url . preg_replace('/%2f/i', '/', rawurlencode($pagename));
204         if (!empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX))
205             $url .= $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
206         if ($args)
207             $url .= "?$args";
208     }
209     else {
210         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
211         $url .= "?pagename=" . rawurlencode($pagename);
212         if ($args)
213             $url .= "&$args";
214     }
215     if ($anchor)
216         $url .= "#" . MangleXmlIdentifier($anchor);
217     return $url;
218 }
219
220 /** Convert relative URL to absolute URL.
221  *
222  * This converts a relative URL to one of PhpWiki's support files
223  * to an absolute one.
224  *
225  * @param string $url
226  * @return string Absolute URL
227  */
228 function AbsoluteURL ($url) {
229     if (preg_match('/^https?:/', $url))
230         return $url;
231     if ($url[0] != '/') {
232         $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
233         while ($base != '/' and substr($url, 0, 3) == "../") {
234             $url = substr($url, 3);
235             $base = dirname($base);
236         }
237         if ($base != '/')
238             $base .= '/';
239         $url = $base . $url;
240     }
241     return SERVER_URL . $url;
242 }
243
244 function DataURL ($url) {
245     if (preg_match('/^https?:/', $url))
246         return $url;
247     $url = NormalizeWebFileName($url);
248     if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
249         $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
250     return AbsoluteURL($url);
251 }
252
253 /**
254  * Generates icon in front of links.
255  *
256  * @param string $protocol_or_url URL or protocol to determine which icon to use.
257  *
258  * @return HtmlElement HtmlElement object that contains data to create img link to
259  * icon for use with url or protocol passed to the function. False if no img to be
260  * displayed.
261  */
262 function IconForLink($protocol_or_url) {
263     global $WikiTheme;
264     if (0 and $filename_suffix == false) {
265         // display apache style icon for file type instead of protocol icon
266         // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
267         // - document: html, htm, text, txt, rtf, pdf, doc
268         // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
269         // - audio: mp3,mp2,aiff,aif,au
270         // - multimedia: mpeg,mpg,mov,qt
271     } else {
272         list ($proto) = explode(':', $protocol_or_url, 2);
273         $src = $WikiTheme->getLinkIconURL($proto);
274         if ($src)
275             return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
276         else
277             return false;
278     }
279 }
280
281 /**
282  * Glue icon in front of or after text.
283  * Pref: 'noLinkIcons'  - ignore icon if set
284  * Theme: 'LinkIcons'   - 'yes'   at front
285  *                      - 'no'    display no icon
286  *                      - 'front' display at left
287  *                      - 'after' display at right
288  *
289  * @param string $protocol_or_url Protocol or URL.  Used to determine the
290  * proper icon.
291  * @param string $text The text.
292  * @return XmlContent.
293  */
294 function PossiblyGlueIconToText($proto_or_url, $text) {
295     global $request, $WikiTheme;
296     if ($request->getPref('noLinkIcons'))
297         return $text;
298     $icon = IconForLink($proto_or_url);
299     if (!$icon)
300         return $text;
301     if ($where = $WikiTheme->getLinkIconAttr()) {
302         if ($where == 'no') return $text;
303         if ($where != 'after') $where = 'front';
304     } else {
305         $where = 'front';
306     }
307     if ($where == 'after') {
308         // span the icon only to the last word (tie them together), 
309         // to let the previous words wrap on line breaks.
310         if (!is_object($text)) {
311             preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
312             list (, $prefix, $last_word) = $m;
313         }
314         else {
315             $last_word = $text;
316             $prefix = false;
317         }
318         $text = HTML::span(array('style' => 'white-space: nowrap'),
319                            $last_word, HTML::Raw('&nbsp;'), $icon);
320         if ($prefix)
321             $text = HTML($prefix, $text);
322         return $text;
323     }
324     // span the icon only to the first word (tie them together), 
325     // to let the next words wrap on line breaks
326     if (!is_object($text)) {
327         preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
328         list (, $first_word, $tail) = $m;
329     }
330     else {
331         $first_word = $text;
332         $tail = false;
333     }
334     $text = HTML::span(array('style' => 'white-space: nowrap'),
335                        $icon, $first_word);
336     if ($tail)
337         $text = HTML($text, $tail);
338     return $text;
339 }
340
341 /**
342  * Determines if the url passed to function is safe, by detecting if the characters
343  * '<', '>', or '"' are present.
344  * Check against their urlencoded values also.
345  *
346  * @param string $url URL to check for unsafe characters.
347  * @return boolean True if same, false else.
348  */
349 function IsSafeURL($url) {
350     return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
351 }
352
353 /**
354  * Generates an HtmlElement object to store data for a link.
355  *
356  * @param string $url URL that the link will point to.
357  * @param string $linktext Text to be displayed as link.
358  * @return HtmlElement HtmlElement object that contains data to construct an html link.
359  */
360 function LinkURL($url, $linktext = '') {
361     // FIXME: Is this needed (or sufficient?)
362     if(! IsSafeURL($url)) {
363         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
364                                      _("BAD URL -- remove all of <, >, \"")));
365     }
366     else {
367         if (!$linktext)
368             $linktext = preg_replace("/mailto:/A", "", $url);
369         $args = array('href' => $url);
370         if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
371             $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
372         $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
373     }
374     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
375     return $link;
376 }
377
378 /**
379  * Inline Images
380  *
381  * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
382  * Disallows sizes which are too small. 
383  * Spammers may use such (typically invisible) image attributes to higher their GoogleRank.
384  *
385  * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
386  */
387 function LinkImage($url, $alt = false) {
388     $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
389     // Disallow tags in img src urls. Typical CSS attacks.
390     // FIXME: Is this needed (or sufficient?)
391     if(! IsSafeURL($url)) {
392         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
393                                      _("BAD URL -- remove all of <, >, \"")));
394     } else {
395         // support new syntax: [image.jpg size=50% border=n]
396         if (!preg_match("/\.(".$force_img.")/i", $url))
397             $ori_url = $url;
398         $arr = split(' ',$url);
399         if (count($arr) > 1) {
400             $url = $arr[0];
401         }
402         if (empty($alt)) $alt = basename($url);
403         $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
404         if (count($arr) > 1) {
405             array_shift($arr);
406             foreach ($arr as $attr) {
407                 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
408                     $link->setAttr('width',$m[1]);
409                     $link->setAttr('height',$m[1]);
410                 }
411                 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
412                     $link->setAttr('width',$m[1]);
413                     $link->setAttr('height',$m[2]);
414                 }
415                 if (preg_match('/^border=(\d+)$/',$attr,$m))
416                     $link->setAttr('border',$m[1]);
417                 if (preg_match('/^align=(\w+)$/',$attr,$m))
418                     $link->setAttr('align',$m[1]);
419                 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
420                     $link->setAttr('hspace',$m[1]);
421                 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
422                     $link->setAttr('vspace',$m[1]);
423             }
424         }
425         // Check width and height as spam countermeasure
426         if (($width  = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
427             //$width  = (int) $width; // px or % or other suffix
428             //$height = (int) $height;
429             if (($width < 3 and $height < 10) or 
430                 ($height < 3 and $width < 20) or 
431                 ($height < 7 and $width < 7))
432             {
433                 trigger_error(_("Invalid image size"), E_USER_WARNING);
434                 return '';
435             }
436         } else {
437             // Older php versions crash here with certain png's: 
438             // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
439             //   http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
440             // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
441             if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
442                 ; // it's safe to assume that this will fail.
443             elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
444                 $width  = $size[0];
445                 $height = $size[1];
446                 if (($width < 3 and $height < 10) 
447                     or ($height < 3 and $width < 20)
448                     or ($height < 7 and $width < 7))
449                 {
450                     trigger_error(_("Invalid image size"), E_USER_WARNING);
451                     return '';
452                 }
453             }
454         }
455     }
456     $link->setAttr('class', 'inlineimage');
457
458     /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
459      * png|jpg|gif|jpeg|bmp|pl|cgi
460      * Note: Allow cgi's (pl,cgi) returning images.
461      */
462     if (!preg_match("/\.(".$force_img.")/i", $url)) {
463         //HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
464         // => HTML::object(array('src' => $url)) ...;
465         return ImgObject($link, $ori_url);
466     }
467     return $link;
468 }
469
470 /**
471  * <object> / <embed> tags instead of <img> for all non-image extensions allowed via INLINE_IMAGES
472  * Called by LinkImage(), not directly.
473  * Syntax: [image.svg size=50% border=n align= hspace= vspace= width= height=]
474  * $alt may be an alternate img
475  * TODO: Need to unify with WikiPluginCached::embedObject()
476  *
477  * Note that Safari 1.0 will crash with <object>, so use only <embed>
478  *   http://www.alleged.org.uk/pdc/2002/svg-object.html
479  */
480 function ImgObject($img, $url) {
481     // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
482     $args = split(' ', $url);
483     if (count($args) >= 1) {
484         $url = array_shift($args);
485         foreach ($args as $attr) {
486             if (preg_match('/^type=(\S+)$/',$attr,$m))
487                 $img->setAttr('type', $m[1]);
488             if (preg_match('/^data=(\S+)$/',$attr,$m))
489                 $img->setAttr('data', $m[1]);
490         }
491     }
492     $type = $img->getAttr('type');
493     if (!$type) {
494         // TODO: map extension to mime-types if type is not given and php < 4.3
495         if (function_exists('mime_content_type'))
496             $type = mime_content_type($url);
497     }
498     $link = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)));
499     $link->setAttr('class', 'inlineobject');
500     if (isBrowserSafari()) {
501         return HTML::embed($link->_attr);
502     }
503     $link->pushContent(HTML::embed($link->_attr));
504     return $link;
505 }
506
507
508 class Stack {
509
510     // var in php5 deprecated
511     function Stack() {
512         $this->items = array();
513         $this->size = 0;
514     }
515     function push($item) {
516         $this->items[$this->size] = $item;
517         $this->size++;
518         return true;
519     }  
520     
521     function pop() {
522         if ($this->size == 0) {
523             return false; // stack is empty
524         }  
525         $this->size--;
526         return $this->items[$this->size];
527     }  
528     
529     function cnt() {
530         return $this->size;
531     }  
532     
533     function top() {
534         if($this->size)
535             return $this->items[$this->size - 1];
536         else
537             return '';
538     }
539     
540 }  
541 // end class definition
542
543 function SplitQueryArgs ($query_args = '') 
544 {
545     // FIXME: use the arg-seperator which might not be &
546     $split_args = split('&', $query_args);
547     $args = array();
548     while (list($key, $val) = each($split_args))
549         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
550             $args[$m[1]] = $m[2];
551     return $args;
552 }
553
554 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
555     $args = array();
556     
557     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
558         return HTML::strong(array('class' => 'rawurl'),
559                             HTML::u(array('class' => 'baduri'),
560                                     _("BAD phpwiki: URL")));
561     }
562
563     if ($m[1])
564         $pagename = urldecode($m[1]);
565     $qargs = $m[2];
566     
567     if (empty($pagename) &&
568         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
569         // Convert old style links (to not break diff links in
570         // RecentChanges).
571         $pagename = urldecode($m[2]);
572         $args = array("action" => $m[1]);
573     }
574     else {
575         $args = SplitQueryArgs($qargs);
576     }
577
578     if (empty($pagename))
579         $pagename = $GLOBALS['request']->getArg('pagename');
580
581     if (isset($args['action']) && $args['action'] == 'browse')
582         unset($args['action']);
583     
584     /*FIXME:
585       if (empty($args['action']))
586       $class = 'wikilink';
587       else if (is_safe_action($args['action']))
588       $class = 'wikiaction';
589     */
590     if (empty($args['action']) || is_safe_action($args['action']))
591         $class = 'wikiaction';
592     else {
593         // Don't allow administrative links on unlocked pages.
594         $dbi = $GLOBALS['request']->getDbh();
595         $page = $dbi->getPage($basepage ? $basepage : $pagename);
596         if (!$page->get('locked'))
597             return HTML::span(array('class' => 'wikiunsafe'),
598                               HTML::u(_("Lock page to enable link")));
599         $class = 'wikiadmin';
600     }
601     
602     if (!$text)
603         $text = HTML::span(array('class' => 'rawurl'), $url);
604
605     $wikipage = new WikiPageName($pagename);
606     if (!$wikipage->isValid()) {
607         global $WikiTheme;
608         return $WikiTheme->linkBadWikiWord($wikipage, $url);
609     }
610     
611     return HTML::a(array('href'  => WikiURL($pagename, $args),
612                          'class' => $class),
613                    $text);
614 }
615
616 /**
617  * A class to assist in parsing wiki pagenames.
618  *
619  * Now with subpages and anchors, parsing and passing around
620  * pagenames is more complicated.  This should help.
621  */
622 class WikiPageName
623 {
624     /** Short name for page.
625      *
626      * This is the value of $name passed to the constructor.
627      * (For use, e.g. as a default label for links to the page.)
628      */
629     //var $shortName;
630
631     /** The full page name.
632      *
633      * This is the full name of the page (without anchor).
634      */
635     //var $name;
636     
637     /** The anchor.
638      *
639      * This is the referenced anchor within the page, or the empty string.
640      */
641     //var $anchor;
642     
643     /** Constructor
644      *
645      * @param mixed $name Page name.
646      * WikiDB_Page, WikiDB_PageRevision, or string.
647      * This can be a relative subpage name (like '/SubPage'),
648      * or can be the empty string to refer to the $basename.
649      *
650      * @param string $anchor For links to anchors in page.
651      *
652      * @param mixed $basename Page name from which to interpret
653      * relative or other non-fully-specified page names.
654      */
655     function WikiPageName($name, $basename=false, $anchor=false) {
656         if (is_string($name)) {
657             $this->shortName = $name;
658             if (strstr($name, ':')) {
659                 list($moniker, $this->shortName) = split (":", $name, 2);
660                 $map = getInterwikiMap(); // allow overrides to custom maps
661                 if (isset($map->_map[$moniker])) {
662                     $url = $map->_map[$moniker];
663                     if (strstr($url, '%s'))
664                         $url = sprintf($url, $this->shortName);
665                     else
666                         $url .= $this->shortName;
667                     // expand Talk or User, but not to absolute urls!
668                     if (strstr($url, '//')) {
669                         if ($moniker == 'Talk')
670                             $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
671                         elseif ($moniker == 'User')
672                             $name = $name;
673                     } else {
674                         $name = $url;
675                     }
676                     if (strstr($name, '?'))
677                         list($name, $dummy) = split("?", $name, 2);
678                 }
679             }
680             // FIXME: We should really fix the cause for "/PageName" in the WikiDB
681             if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
682                 if ($basename)
683                     $name = $this->_pagename($basename) . $name;
684                 else {
685                     $name = $this->_normalize_bad_pagename($name);
686                     $this->shortName = $name;
687                 }
688             }
689         }
690         else {
691             $name = $this->_pagename($name);
692             $this->shortName = $name;
693         }
694
695         $this->name = $this->_check($name);
696         $this->anchor = (string)$anchor;
697     }
698
699     function getName() {
700         return $this->name;
701     }
702     
703     function getParent() {
704         $name = $this->name;
705         if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
706             return false;
707         return substr($name, 0, -strlen($tail));
708     }
709
710     function isValid($strict = false) {
711         if ($strict)
712             return !isset($this->_errors);
713         return (is_string($this->name) and $this->name != '');
714     }
715
716     function getWarnings() {
717         $warnings = array();
718         if (isset($this->_warnings))
719             $warnings = array_merge($warnings, $this->_warnings);
720         if (isset($this->_errors))
721             $warnings = array_merge($warnings, $this->_errors);
722         if (!$warnings)
723             return false;
724         
725         return sprintf(_("'%s': Bad page name: %s"),
726                        $this->shortName, join(', ', $warnings));
727     }
728     
729     function _pagename($page) {
730         if (isa($page, 'WikiDB_Page'))
731             return $page->getName();
732         elseif (isa($page, 'WikiDB_PageRevision'))
733             return $page->getPageName();
734         elseif (isa($page, 'WikiPageName'))
735             return $page->name;
736         // '0' or e.g. '1984' should be allowed though
737         if (!is_string($page) and !is_integer($page)) {
738             trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
739                                   $page, gettype($page), get_class($page)),
740                           E_USER_NOTICE);
741         }
742         //assert(is_string($page));
743         return $page;
744     }
745
746     function _normalize_bad_pagename($name) {
747         trigger_error("Bad pagename: " . $name, E_USER_WARNING);
748
749         // Punt...  You really shouldn't get here.
750         if (empty($name)) {
751             global $request;
752             return $request->getArg('pagename');
753         }
754         assert($name[0] == SUBPAGE_SEPARATOR);
755         $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
756         return substr($name, 1);
757     }
758
759
760     function _check($pagename) {
761         // Compress internal white-space to single space character.
762         $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
763         if ($pagename != $orig)
764             $this->_warnings[] = _("White space converted to single space");
765     
766         // Delete any control characters.
767         if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file') {
768             $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
769             if ($pagename != $orig)
770                 $this->_errors[] = _("Control characters not allowed");
771         }
772
773         // Strip leading and trailing white-space.
774         $pagename = trim($pagename);
775
776         $orig = $pagename;
777         while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
778             $pagename = substr($pagename, 1);
779         if ($pagename != $orig)
780             $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
781
782         // ";" is urlencoded, so safe from php arg-delim problems
783         /*if (strstr($pagename, ';')) {
784             $this->_warnings[] = _("';' is deprecated");
785             $pagename = str_replace(';', '', $pagename);
786         }*/
787         
788         // not only for SQL, also to restrict url length
789         if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
790             $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
791             $this->_errors[] = _("too long");
792         }
793
794         // disallow some chars only on file and cvs
795         if ((DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file') 
796             and preg_match('/(:|\.\.)/', $pagename, $m)) {
797             $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
798             $pagename = str_replace('..', '', $pagename);
799             $pagename = str_replace(':', '', $pagename);
800         }
801         
802         return $pagename;
803     }
804 }
805
806 /**
807  * Convert old page markup to new-style markup.
808  *
809  * @param string $text Old-style wiki markup.
810  *
811  * @param string $markup_type
812  * One of: <dl>
813  * <dt><code>"block"</code>  <dd>Convert all markup.
814  * <dt><code>"inline"</code> <dd>Convert only inline markup.
815  * <dt><code>"links"</code>  <dd>Convert only link markup.
816  * </dl>
817  *
818  * @return string New-style wiki markup.
819  *
820  * @bugs Footnotes don't work quite as before (esp if there are
821  *   multiple references to the same footnote.  But close enough,
822  *   probably for now....
823  * @bugs  Apache2 and IIS crash with OldTextFormattingRules or
824  *   AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
825  *   It only crashes with CreateToc so far, but other pages (not in pgsrc) are 
826  *   also known to crash, even with Apache1.
827  */
828 function ConvertOldMarkup ($text, $markup_type = "block") {
829
830     static $subs;
831     static $block_re;
832     
833     // FIXME:
834     // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
835     // AnciennesR%E8glesDeFormatage crashes. 
836     // It only crashes with CreateToc so far, but other pages (not in pgsrc) are 
837     // also known to crash, even with Apache1.
838     $debug_skip = false;
839     // I suspect this only to crash with Apache2 and IIS.
840     if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
841         and preg_match("/plugin CreateToc/", $text)) 
842     {
843         trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
844                      ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
845                      ._("Skipped."), E_USER_WARNING);
846         $debug_skip = true;
847         //if (!DEBUG) return $text;
848         return $text;
849     }
850
851     if (empty($subs)) {
852         /*****************************************************************
853          * Conversions for inline markup:
854          */
855
856         // escape tilde's
857         $orig[] = '/~/';
858         $repl[] = '~~';
859
860         // escape escaped brackets
861         $orig[] = '/\[\[/';
862         $repl[] = '~[';
863
864         // change ! escapes to ~'s.
865         global $WikiNameRegexp, $request;
866         $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
867         // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
868         if (check_php_version(4,3,9)) {
869           $map = getInterwikiMap();
870           if ($map_regex = $map->getRegexp())
871             $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
872         }
873         $bang_esc[] = $WikiNameRegexp;
874         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
875         $repl[] = '~\\1';
876
877         $subs["links"] = array($orig, $repl);
878
879         // Temporarily URL-encode pairs of underscores in links to hide
880         // them from the re for bold markup.
881         $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
882         $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
883
884         // Escape '<'s
885         //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
886         //$repl[] = '~<';
887         
888         // Convert footnote references.
889         $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
890         $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
891
892         // Convert old style emphases to HTML style emphasis.
893         $orig[] = '/__(.*?)__/';
894         $repl[] = '<strong>\\1</strong>';
895         $orig[] = "/''(.*?)''/";
896         $repl[] = '<em>\\1</em>';
897
898         // Escape nestled markup.
899         $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
900         $repl[] = '~\\0';
901         
902         // in old markup headings only allowed at beginning of line
903         $orig[] = '/!/';
904         $repl[] = '~!';
905
906         // Convert URL-encoded pairs of underscores in links back to
907         // real underscores after bold markup has been converted.
908         $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
909         $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
910
911         $subs["inline"] = array($orig, $repl);
912
913         /*****************************************************************
914          * Patterns which match block markup constructs which take
915          * special handling...
916          */
917
918         // Indented blocks
919         $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
920         // Tables
921         $blockpats[] = '\|(?:.*\n\|)*';
922
923         // List items
924         $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
925
926         // Footnote definitions
927         $blockpats[] = '\[\s*(\d+)\s*\]';
928
929         if (!$debug_skip) {
930         // Plugins
931         $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
932         }
933
934         // Section Title
935         $blockpats[] = '!{1,3}[^!]';
936         /*
937         removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
938         this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
939         */
940         $block_re = ( '/\A((?:.|\n)*?)(^(?:'
941                       . join("|", $blockpats)
942                       . ').*$)\n?/m' );
943         
944     }
945     
946     if ($markup_type != "block") {
947         list ($orig, $repl) = $subs[$markup_type];
948         return preg_replace($orig, $repl, $text);
949     }
950     else {
951         list ($orig, $repl) = $subs['inline'];
952         $out = '';
953         //FIXME:
954         // php crashes here in the 2nd paragraph of OldTextFormattingRules, 
955         // AnciennesR%E8glesDeFormatage and more 
956         // See http://www.pcre.org/pcre.txt LIMITATIONS
957          while (preg_match($block_re, $text, $m)) {
958             $text = substr($text, strlen($m[0]));
959             list (,$leading_text, $block) = $m;
960             $suffix = "\n";
961             
962             if (strchr(" \t", $block[0])) {
963                 // Indented block
964                 $prefix = "<pre>\n";
965                 $suffix = "\n</pre>\n";
966             }
967             elseif ($block[0] == '|') {
968                 // Old-style table
969                 $prefix = "<?plugin OldStyleTable\n";
970                 $suffix = "\n?>\n";
971             }
972             elseif (strchr("#*;", $block[0])) {
973                 // Old-style list item
974                 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
975                 list (,$ind,$bullet) = $m;
976                 $block = substr($block, strlen($m[0]));
977                 
978                 $indent = str_repeat('     ', strlen($ind));
979                 if ($bullet[0] == ';') {
980                     //$term = ltrim(substr($bullet, 1));
981                     //return $indent . $term . "\n" . $indent . '     ';
982                     $prefix = $ind . $bullet;
983                 }
984                 else
985                     $prefix = $indent . $bullet . ' ';
986             }
987             elseif ($block[0] == '[') {
988                 // Footnote definition
989                 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
990                 $footnum = $m[1];
991                 $block = substr($block, strlen($m[0]));
992                 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
993             }
994             elseif ($block[0] == '<') {
995                 // Plugin.
996                 // HACK: no inline markup...
997                 $prefix = $block;
998                 $block = '';
999             }
1000             elseif ($block[0] == '!') {
1001                 // Section heading
1002                 preg_match('/^!{1,3}/', $block, $m);
1003                 $prefix = $m[0];
1004                 $block = substr($block, strlen($m[0]));
1005             }
1006             else {
1007                 // AAck!
1008                 assert(0);
1009             }
1010             if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1011             if ($block) $block = preg_replace($orig, $repl, $block);
1012             $out .= $leading_text;
1013             $out .= $prefix;
1014             $out .= $block;
1015             $out .= $suffix;
1016         }
1017         return $out . preg_replace($orig, $repl, $text);
1018     }
1019 }
1020
1021
1022 /**
1023  * Expand tabs in string.
1024  *
1025  * Converts all tabs to (the appropriate number of) spaces.
1026  *
1027  * @param string $str
1028  * @param integer $tab_width
1029  * @return string
1030  */
1031 function expand_tabs($str, $tab_width = 8) {
1032     $split = split("\t", $str);
1033     $tail = array_pop($split);
1034     $expanded = "\n";
1035     foreach ($split as $hunk) {
1036         $expanded .= $hunk;
1037         $pos = strlen(strrchr($expanded, "\n")) - 1;
1038         $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1039     }
1040     return substr($expanded, 1) . $tail;
1041 }
1042
1043 /**
1044  * Split WikiWords in page names.
1045  *
1046  * It has been deemed useful to split WikiWords (into "Wiki Words") in
1047  * places like page titles. This is rumored to help search engines
1048  * quite a bit.
1049  *
1050  * @param $page string The page name.
1051  *
1052  * @return string The split name.
1053  */
1054 function SplitPagename ($page) {
1055     
1056     if (preg_match("/\s/", $page))
1057         return $page;           // Already split --- don't split any more.
1058     
1059     // This algorithm is specialized for several languages.
1060     // (Thanks to Pierrick MEIGNEN)
1061     // Improvements for other languages welcome.
1062     static $RE;
1063     if (!isset($RE)) {
1064         // This mess splits between a lower-case letter followed by
1065         // either an upper-case or a numeral; except that it wont
1066         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1067         switch ($GLOBALS['LANG']) {
1068         case 'en':
1069         case 'it':
1070         case 'es': 
1071         case 'de':
1072             $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1073             break;
1074         case 'fr': 
1075             $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1076             break;
1077         }
1078         $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1079         // This the single-letter words 'I' and 'A' from any following
1080         // capitalized words.
1081         switch ($GLOBALS['LANG']) {
1082         case 'en': 
1083             $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1084             break;
1085         case 'fr': 
1086             $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1087             break;
1088         }
1089         // Split numerals from following letters.
1090         $RE[] = '/(\d)([[:alpha:]])/';
1091         // Split at subpage seperators. TBD in Theme.php
1092         $RE[] = "/([^${sep}]+)(${sep})/";
1093         $RE[] = "/(${sep})([^${sep}]+)/";
1094         
1095         foreach ($RE as $key)
1096             $RE[$key] = pcre_fix_posix_classes($key);
1097     }
1098
1099     foreach ($RE as $regexp) {
1100         $page = preg_replace($regexp, '\\1 \\2', $page);
1101     }
1102     return $page;
1103 }
1104
1105 function NoSuchRevision (&$request, $page, $version) {
1106     $html = HTML(HTML::h2(_("Revision Not Found")),
1107                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
1108                              $version, WikiLink($page, 'auto'))));
1109     include_once('lib/Template.php');
1110     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1111     $request->finish();
1112 }
1113
1114
1115 /**
1116  * Get time offset for local time zone.
1117  *
1118  * @param $time time_t Get offset for this time. Default: now.
1119  * @param $no_colon boolean Don't put colon between hours and minutes.
1120  * @return string Offset as a string in the format +HH:MM.
1121  */
1122 function TimezoneOffset ($time = false, $no_colon = false) {
1123     if ($time === false)
1124         $time = time();
1125     $secs = date('Z', $time);
1126
1127     if ($secs < 0) {
1128         $sign = '-';
1129         $secs = -$secs;
1130     }
1131     else {
1132         $sign = '+';
1133     }
1134     $colon = $no_colon ? '' : ':';
1135     $mins = intval(($secs + 30) / 60);
1136     return sprintf("%s%02d%s%02d",
1137                    $sign, $mins / 60, $colon, $mins % 60);
1138 }
1139
1140
1141 /**
1142  * Format time in ISO-8601 format.
1143  *
1144  * @param $time time_t Time.  Default: now.
1145  * @return string Date and time in ISO-8601 format.
1146  */
1147 function Iso8601DateTime ($time = false) {
1148     if ($time === false)
1149         $time = time();
1150     $tzoff = TimezoneOffset($time);
1151     $date  = date('Y-m-d', $time);
1152     $time  = date('H:i:s', $time);
1153     return $date . 'T' . $time . $tzoff;
1154 }
1155
1156 /**
1157  * Format time in RFC-2822 format.
1158  *
1159  * @param $time time_t Time.  Default: now.
1160  * @return string Date and time in RFC-2822 format.
1161  */
1162 function Rfc2822DateTime ($time = false) {
1163     if ($time === false)
1164         $time = time();
1165     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1166 }
1167
1168 /**
1169  * Format time in RFC-1123 format.
1170  *
1171  * @param $time time_t Time.  Default: now.
1172  * @return string Date and time in RFC-1123 format.
1173  */
1174 function Rfc1123DateTime ($time = false) {
1175     if ($time === false)
1176         $time = time();
1177     return gmdate('D, d M Y H:i:s \G\M\T', $time);
1178 }
1179
1180 /** Parse date in RFC-1123 format.
1181  *
1182  * According to RFC 1123 we must accept dates in the following
1183  * formats:
1184  *
1185  *   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
1186  *   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1187  *   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
1188  *
1189  * (Though we're only allowed to generate dates in the first format.)
1190  */
1191 function ParseRfc1123DateTime ($timestr) {
1192     $timestr = trim($timestr);
1193     if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1194                    .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1195                    $timestr, $m)) {
1196         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1197     }
1198     elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1199                        .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1200                        $timestr, $m)) {
1201         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1202         if ($year < 70) $year += 2000;
1203         elseif ($year < 100) $year += 1900;
1204     }
1205     elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1206                        .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1207                        $timestr, $m)) {
1208         list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1209     }
1210     else {
1211         // Parse failed.
1212         return false;
1213     }
1214
1215     $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1216     if ($time == -1)
1217         return false;           // failed
1218     return $time;
1219 }
1220
1221 /**
1222  * Format time to standard 'ctime' format.
1223  *
1224  * @param $time time_t Time.  Default: now.
1225  * @return string Date and time.
1226  */
1227 function CTime ($time = false)
1228 {
1229     if ($time === false)
1230         $time = time();
1231     return date("D M j H:i:s Y", $time);
1232 }
1233
1234
1235 /**
1236  * Format number as kilobytes or bytes.
1237  * Short format is used for PageList
1238  * Long format is used in PageInfo
1239  *
1240  * @param $bytes       int.  Default: 0.
1241  * @param $longformat  bool. Default: false.
1242  * @return class FormattedText (XmlElement.php).
1243  */
1244 function ByteFormatter ($bytes = 0, $longformat = false) {
1245     if ($bytes < 0)
1246         return fmt("-???");
1247     if ($bytes < 1024) {
1248         if (! $longformat)
1249             $size = fmt("%s b", $bytes);
1250         else
1251             $size = fmt("%s bytes", $bytes);
1252     }
1253     else {
1254         $kb = round($bytes / 1024, 1);
1255         if (! $longformat)
1256             $size = fmt("%s k", $kb);
1257         else
1258             $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1259     }
1260     return $size;
1261 }
1262
1263 /**
1264  * Internationalized printf.
1265  *
1266  * This is essentially the same as PHP's built-in printf
1267  * with the following exceptions:
1268  * <ol>
1269  * <li> It passes the format string through gettext().
1270  * <li> It supports the argument reordering extensions.
1271  * </ol>
1272  *
1273  * Example:
1274  *
1275  * In php code, use:
1276  * <pre>
1277  *    __printf("Differences between versions %s and %s of %s",
1278  *             $new_link, $old_link, $page_link);
1279  * </pre>
1280  *
1281  * Then in locale/po/de.po, one can reorder the printf arguments:
1282  *
1283  * <pre>
1284  *    msgid "Differences between %s and %s of %s."
1285  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1286  * </pre>
1287  *
1288  * (Note that while PHP tries to expand $vars within double-quotes,
1289  * the values in msgstr undergo no such expansion, so the '$'s
1290  * okay...)
1291  *
1292  * One shouldn't use reordered arguments in the default format string.
1293  * Backslashes in the default string would be necessary to escape the
1294  * '$'s, and they'll cause all kinds of trouble....
1295  */ 
1296 function __printf ($fmt) {
1297     $args = func_get_args();
1298     array_shift($args);
1299     echo __vsprintf($fmt, $args);
1300 }
1301
1302 /**
1303  * Internationalized sprintf.
1304  *
1305  * This is essentially the same as PHP's built-in printf with the
1306  * following exceptions:
1307  *
1308  * <ol>
1309  * <li> It passes the format string through gettext().
1310  * <li> It supports the argument reordering extensions.
1311  * </ol>
1312  *
1313  * @see __printf
1314  */ 
1315 function __sprintf ($fmt) {
1316     $args = func_get_args();
1317     array_shift($args);
1318     return __vsprintf($fmt, $args);
1319 }
1320
1321 /**
1322  * Internationalized vsprintf.
1323  *
1324  * This is essentially the same as PHP's built-in printf with the
1325  * following exceptions:
1326  *
1327  * <ol>
1328  * <li> It passes the format string through gettext().
1329  * <li> It supports the argument reordering extensions.
1330  * </ol>
1331  *
1332  * @see __printf
1333  */ 
1334 function __vsprintf ($fmt, $args) {
1335     $fmt = gettext($fmt);
1336     // PHP's sprintf doesn't support variable with specifiers,
1337     // like sprintf("%*s", 10, "x"); --- so we won't either.
1338     
1339     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1340         // Format string has '%2$s' style argument reordering.
1341         // PHP doesn't support this.
1342         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1343             // literal variable name substitution only to keep locale
1344             // strings uncluttered
1345             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1346                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
1347         
1348         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1349         $newargs = array();
1350         
1351         // Reorder arguments appropriately.
1352         foreach($m[1] as $argnum) {
1353             if ($argnum < 1 || $argnum > count($args))
1354                 trigger_error(sprintf(_("%s: argument index out of range"), 
1355                                       $argnum), E_USER_WARNING);
1356             $newargs[] = $args[$argnum - 1];
1357         }
1358         $args = $newargs;
1359     }
1360     
1361     // Not all PHP's have vsprintf, so...
1362     array_unshift($args, $fmt);
1363     return call_user_func_array('sprintf', $args);
1364 }
1365
1366 function file_mtime ($filename) {
1367     if ($stat = @stat($filename))
1368         return $stat[9];
1369     else 
1370         return false;
1371 }
1372
1373 function sort_file_mtime ($a, $b) {
1374     $ma = file_mtime($a);
1375     $mb = file_mtime($b);
1376     if (!$ma or !$mb or $ma == $mb) return 0;
1377     return ($ma > $mb) ? -1 : 1;
1378 }
1379
1380 class fileSet {
1381     /**
1382      * Build an array in $this->_fileList of files from $dirname.
1383      * Subdirectories are not traversed.
1384      *
1385      * (This was a function LoadDir in lib/loadsave.php)
1386      * See also http://www.php.net/manual/en/function.readdir.php
1387      */
1388     function getFiles($exclude=false, $sortby=false, $limit=false) {
1389         $list = $this->_fileList;
1390
1391         if ($sortby) {
1392             require_once('lib/PageList.php');
1393             switch (Pagelist::sortby($sortby, 'db')) {
1394             case 'pagename ASC': break;
1395             case 'pagename DESC': 
1396                 $list = array_reverse($list); 
1397                 break;
1398             case 'mtime ASC': 
1399                 usort($list,'sort_file_mtime'); 
1400                 break;
1401             case 'mtime DESC': 
1402                 usort($list,'sort_file_mtime');
1403                 $list = array_reverse($list); 
1404                 break;
1405             }
1406         }
1407         if ($limit)
1408             return array_splice($list, 0, $limit);
1409         return $list;
1410     }
1411
1412     function _filenameSelector($filename) {
1413         if (! $this->_pattern )
1414             return true;
1415         else {
1416             if (! $this->_pcre_pattern )
1417                 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1418             return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'), 
1419                               $filename);
1420         }
1421     }
1422
1423     function fileSet($directory, $filepattern = false) {
1424         $this->_fileList = array();
1425         $this->_pattern = $filepattern;
1426         if ($filepattern)
1427             $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1428         $this->_case = !isWindows();
1429         $this->_pathsep = '/';
1430
1431         if (empty($directory)) {
1432             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1433                           E_USER_NOTICE);
1434             return; // early return
1435         }
1436
1437         @ $dir_handle = opendir($dir=$directory);
1438         if (empty($dir_handle)) {
1439             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1440                                   $dir), E_USER_NOTICE);
1441             return; // early return
1442         }
1443
1444         while ($filename = readdir($dir_handle)) {
1445             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1446                 continue;
1447             if ($this->_filenameSelector($filename)) {
1448                 array_push($this->_fileList, "$filename");
1449                 //trigger_error(sprintf(_("found file %s"), $filename),
1450                 //                      E_USER_NOTICE); //debugging
1451             }
1452         }
1453         closedir($dir_handle);
1454     }
1455 };
1456
1457 // File globbing
1458
1459 // expands a list containing regex's to its matching entries
1460 class ListRegexExpand {
1461     //var $match, $list, $index, $case_sensitive;
1462     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1463         $this->match = $match;
1464         $this->list = &$list;
1465         $this->case_sensitive = $case_sensitive;        
1466         //$this->index = false;
1467     }
1468     function listMatchCallback ($item, $key) {
1469         $quoted = str_replace('/','\/',$item);
1470         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), 
1471                        $quoted)) {
1472             unset($this->list[$this->index]);
1473             $this->list[] = $item;
1474         }
1475     }
1476     function expandRegex ($index, &$pages) {
1477         $this->index = $index;
1478         array_walk($pages, array($this, 'listMatchCallback'));
1479         return $this->list;
1480     }
1481 }
1482
1483 // Convert fileglob to regex style:
1484 // Convert some wildcards to pcre style, escape the rest
1485 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1486 // Fixed bug #994994: "/" in $glob.
1487 function glob_to_pcre ($glob) {
1488     // check simple case: no need to escape
1489     $escape = '\[](){}=!<>|:/';
1490     if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1491         return $glob;
1492     // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1493     $glob = strtr($glob, "\\", "\xff");
1494     $glob = str_replace("/", '\/', $glob);
1495     // first convert some unescaped expressions to pcre style: . => \.
1496     $special = ".^$";
1497     $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/', 
1498                        "\\1\xff\\2", $glob);
1499
1500     // * => .*, ? => .
1501     $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1502     $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1503     if (!preg_match('/^[\?\*]/', $glob))
1504         $re = '^' . $re;
1505     if (!preg_match('/[\?\*]$/', $glob))
1506         $re = $re . '$';
1507
1508     // .*? handled above, now escape the rest
1509     //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1510     $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/', 
1511                        "\\1\xff\\2", $re);
1512     return strtr($re, "\xff", "\\");
1513 }
1514
1515 function glob_match ($glob, $against, $case_sensitive = true) {
1516     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), 
1517                       $against);
1518 }
1519
1520 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1521     $list = explode(',',$input);
1522     // expand wildcards from list of $allnames
1523     if (preg_match('/[\?\*]/',$input)) {
1524         // Optimizing loop invariants:
1525         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1526         for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1527             $f = $list[$i];
1528             if (preg_match('/[\?\*]/',$f)) {
1529                 reset($allnames);
1530                 $expand = new ListRegexExpand($list, 
1531                     $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1532                 $expand->expandRegex($i, $allnames);
1533             }
1534         }
1535     }
1536     return $list;
1537 }
1538
1539 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1540 function explodePageList($input, $include_empty=false, $sortby='pagename', 
1541                          $limit=false, $exclude=false) {
1542     include_once("lib/PageList.php");
1543     return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1544 }
1545
1546 // Class introspections
1547
1548 /** 
1549  * Determine whether object is of a specified type.
1550  * In PHP builtin since 4.2.0 as is_a()
1551  * is_a() deprecated in PHP 5, in favor of instanceof operator
1552
1553  * @param $object object An object.
1554  * @param $class string Class name.
1555  * @return bool True iff $object is a $class
1556  * or a sub-type of $class. 
1557  */
1558 function isa ($object, $class) {
1559     //if (check_php_version(5)) 
1560     //    return $object instanceof $class;
1561     if (check_php_version(4,2) and !check_php_version(5)) 
1562         return is_a($object, $class);
1563
1564     $lclass = check_php_version(5) ? $class : strtolower($class);
1565     return is_object($object)
1566         && ( strtolower(get_class($object)) == strtolower($class)
1567              || is_subclass_of($object, $lclass) );
1568 }
1569
1570 /** Determine whether (possible) object has method.
1571  *
1572  * @param $object mixed Object
1573  * @param $method string Method name
1574  * @return bool True iff $object is an object with has method $method.
1575  */
1576 function can ($object, $method) {
1577     return is_object($object) && method_exists($object, strtolower($method));
1578 }
1579
1580 /** Determine whether a function is okay to use.
1581  *
1582  * Some providers (e.g. Lycos) disable some of PHP functions for
1583  * "security reasons."  This makes those functions, of course,
1584  * unusable, despite the fact the function_exists() says they
1585  * exist.
1586  *
1587  * This function test to see if a function exists and is not
1588  * disallowed by PHP's disable_functions config setting.
1589  *
1590  * @param string $function_name  Function name
1591  * @return bool  True iff function can be used.
1592  */
1593 function function_usable($function_name) {
1594     static $disabled;
1595     if (!is_array($disabled)) {
1596         $disabled = array();
1597         // Use get_cfg_var since ini_get() is one of the disabled functions
1598         // (on Lycos, at least.)
1599         $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1600         foreach ($split as $f)
1601             $disabled[strtolower($f)] = true;
1602     }
1603
1604     return ( function_exists($function_name)
1605              and ! isset($disabled[strtolower($function_name)])
1606              );
1607 }
1608     
1609     
1610 /** Hash a value.
1611  *
1612  * This is used for generating ETags.
1613  */
1614 function wikihash ($x) {
1615     if (is_scalar($x)) {
1616         return $x;
1617     }
1618     elseif (is_array($x)) {            
1619         ksort($x);
1620         return md5(serialize($x));
1621     }
1622     elseif (is_object($x)) {
1623         return $x->hash();
1624     }
1625     trigger_error("Can't hash $x", E_USER_ERROR);
1626 }
1627
1628
1629 /**
1630  * Seed the random number generator.
1631  *
1632  * better_srand() ensures the randomizer is seeded only once.
1633  * 
1634  * How random do you want it? See:
1635  * http://www.php.net/manual/en/function.srand.php
1636  * http://www.php.net/manual/en/function.mt-srand.php
1637  */
1638 function better_srand($seed = '') {
1639     static $wascalled = FALSE;
1640     if (!$wascalled) {
1641         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1642         function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1643         $wascalled = TRUE;
1644         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1645     }
1646 }
1647
1648 function rand_ascii($length = 1) {
1649     better_srand();
1650     $s = "";
1651     for ($i = 1; $i <= $length; $i++) {
1652         // return only typeable 7 bit ascii, avoid quotes
1653         if (function_exists('mt_rand'))
1654             $s .= chr(mt_rand(40, 126)); 
1655         else
1656             // the usually bad glibc srand()
1657             $s .= chr(rand(40, 126));
1658     }
1659     return $s;
1660 }
1661
1662 /* by Dan Frankowski.
1663  */
1664 function rand_ascii_readable ($length = 6) {
1665     // Pick a few random letters or numbers
1666     $word = "";
1667     better_srand();
1668     // Don't use 1lI0O, because they're hard to read
1669     $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1670     $letter_len = strlen($letters);
1671     for ($i=0; $i < $length; $i++) {
1672         if (function_exists('mt_rand'))
1673             $word .= $letters[mt_rand(0, $letter_len-1)];
1674         else
1675             $word .= $letters[rand(0, $letter_len-1)];
1676     }
1677     return $word;
1678 }
1679
1680 /**
1681  * Recursively count all non-empty elements 
1682  * in array of any dimension or mixed - i.e. 
1683  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1684  * See http://www.php.net/manual/en/function.count.php
1685  */
1686 function count_all($arg) {
1687     // skip if argument is empty
1688     if ($arg) {
1689         //print_r($arg); //debugging
1690         $count = 0;
1691         // not an array, return 1 (base case) 
1692         if(!is_array($arg))
1693             return 1;
1694         // else call recursively for all elements $arg
1695         foreach($arg as $key => $val)
1696             $count += count_all($val);
1697         return $count;
1698     }
1699 }
1700
1701 function isSubPage($pagename) {
1702     return (strstr($pagename, SUBPAGE_SEPARATOR));
1703 }
1704
1705 function subPageSlice($pagename, $pos) {
1706     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1707     $pages = array_slice($pages,$pos,1);
1708     return $pages[0];
1709 }
1710
1711 /**
1712  * Alert
1713  *
1714  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1715  * pop up...)
1716  *
1717  * FIXME:
1718  * This is a hackish and needs to be refactored.  However it would be nice to
1719  * unify all the different methods we use for showing Alerts and Dialogs.
1720  * (E.g. "Page deleted", login form, ...)
1721  */
1722 class Alert {
1723     /** Constructor
1724      *
1725      * @param object $request
1726      * @param mixed $head  Header ("title") for alert box.
1727      * @param mixed $body  The text in the alert box.
1728      * @param hash $buttons  An array mapping button labels to URLs.
1729      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1730      */
1731     function Alert($head, $body, $buttons=false) {
1732         if ($buttons === false)
1733             $buttons = array();
1734
1735         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1736         $this->_buttons = $buttons;
1737     }
1738
1739     /**
1740      * Show the alert box.
1741      */
1742     function show() {
1743         global $request;
1744
1745         $tokens = $this->_tokens;
1746         $tokens['BUTTONS'] = $this->_getButtons();
1747         
1748         $request->discardOutput();
1749         $tmpl = new Template('dialog', $request, $tokens);
1750         $tmpl->printXML();
1751         $request->finish();
1752     }
1753
1754
1755     function _getButtons() {
1756         global $request;
1757
1758         $buttons = $this->_buttons;
1759         if (!$buttons)
1760             $buttons = array(_("Okay") => $request->getURLtoSelf());
1761         
1762         global $WikiTheme;
1763         foreach ($buttons as $label => $url)
1764             print "$label $url\n";
1765             $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1766         return new XmlContent($out);
1767     }
1768 }
1769
1770 // 1.3.8     => 1030.08
1771 // 1.3.9-p1  => 1030.091
1772 // 1.3.10pre => 1030.099
1773 // 1.3.11pre-20041120 => 1030.1120041120
1774 // 1.3.12-rc1 => 1030.119
1775 function phpwiki_version() {
1776     static $PHPWIKI_VERSION;
1777     if (!isset($PHPWIKI_VERSION)) {
1778         $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1779         $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1780         $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1781         if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1782             $PHPWIKI_VERSION -= 0.01;
1783     }
1784     return $PHPWIKI_VERSION;
1785 }
1786
1787 function phpwiki_gzhandler($ob) {
1788     if (function_exists('gzencode'))
1789         $ob = gzencode($ob);
1790         $GLOBALS['request']->_ob_get_length = strlen($ob);
1791     if (!headers_sent()) {
1792         header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1793     }
1794     return $ob;
1795 }
1796
1797 function isWikiWord($word) {
1798     global $WikiNameRegexp;
1799     //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1800     return preg_match("/^$WikiNameRegexp\$/",$word);
1801 }
1802
1803 // needed to store serialized objects-values only (perm, pref)
1804 function obj2hash ($obj, $exclude = false, $fields = false) {
1805     $a = array();
1806     if (! $fields ) $fields = get_object_vars($obj);
1807     foreach ($fields as $key => $val) {
1808         if (is_array($exclude)) {
1809             if (in_array($key, $exclude)) continue;
1810         }
1811         $a[$key] = $val;
1812     }
1813     return $a;
1814 }
1815
1816 /**
1817  * isUtf8String($string) - cheap utf-8 detection
1818  *
1819  * segfaults for strings longer than 10kb!
1820  * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1821  * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1822  */
1823 function isUtf8String( $s ) {
1824     $ptrASCII  = '[\x00-\x7F]';
1825     $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1826     $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1827     $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1828     $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1829     $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1830     return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1831 }
1832
1833 /** 
1834  * Check for UTF-8 URLs; Internet Explorer produces these if you
1835  * type non-ASCII chars in the URL bar or follow unescaped links.
1836  * Requires urldecoded pagename.
1837  * Fixes sf.net bug #953949
1838  *
1839  * src: languages/Language.php:checkTitleEncoding() from mediawiki
1840  */
1841 function fixTitleEncoding( $s ) {
1842     global $charset;
1843
1844     $s = trim($s);
1845     // print a warning?
1846     if (empty($s)) return $s;
1847
1848     $ishigh = preg_match( '/[\x80-\xff]/', $s);
1849     /*
1850     $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1851                                     '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1852     */
1853     $isutf = ($ishigh ? isUtf8String($s) : true);
1854     $locharset = strtolower($charset);
1855
1856     if( $locharset != "utf-8" and $ishigh and $isutf )
1857         // if charset == 'iso-8859-1' then simply use utf8_decode()
1858         if ($locharset == 'iso-8859-1')
1859             return utf8_decode( $s );
1860         else {
1861             // check for iconv support
1862             loadPhpExtension("iconv");
1863             return iconv( "UTF-8", $charset, $s );
1864         }
1865
1866     if ($locharset == "utf-8" and $ishigh and !$isutf )
1867         return utf8_encode( $s );
1868
1869     // Other languages can safely leave this function, or replace
1870     // it with one to detect and convert another legacy encoding.
1871     return $s;
1872 }
1873
1874 /** 
1875  * MySQL fulltext index doesn't grok utf-8, so we
1876  * need to fold cases and convert to hex.
1877  * src: languages/Language.php:stripForSearch() from mediawiki
1878  */
1879 /*
1880 function stripForSearch( $string ) {
1881     global $wikiLowerChars; 
1882     // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1883     return preg_replace(
1884                         "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1885                         "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1886                         $string );
1887 }
1888 */
1889
1890 /** 
1891  * Workaround for allow_url_fopen, to get the content of an external URI.
1892  * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1893  * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1894  */
1895 function url_get_contents( $uri ) {
1896     if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1897         return @file_get_contents($uri);
1898     } else {
1899         require_once("lib/HttpClient.php");
1900         $bits = parse_url($uri);
1901         $host = $bits['host'];
1902         $port = isset($bits['port']) ? $bits['port'] : 80;
1903         $path = isset($bits['path']) ? $bits['path'] : '/';
1904         if (isset($bits['query'])) {
1905             $path .= '?'.$bits['query'];
1906         }
1907         $client = new HttpClient($host, $port);
1908         $client->use_gzip = false;
1909         if (!$client->get($path)) {
1910             return false;
1911         } else {
1912             return $client->getContent();
1913         }
1914     }
1915 }
1916
1917 /**
1918  * Generate consecutively named strings:
1919  *   Name, Name2, Name3, ...
1920  */
1921 function GenerateId($name) {
1922     static $ids = array();
1923     if (empty($ids[$name])) {
1924         $ids[$name] = 1;
1925         return $name;
1926     } else {
1927         $ids[$name]++;
1928         return $name . $ids[$name];
1929     }
1930 }
1931
1932 // from IncludePage. To be of general use.
1933 // content: string or array of strings
1934 function firstNWordsOfContent( $n, $content ) {
1935     if ($content and $n > 0) {
1936         if (is_array($content)) {
1937             // fixme: return a list of lines then?
1938             //$content = join("\n", $content);
1939             //$return_array = true;
1940             $wordcount = 0;
1941             foreach ($content as $line) {
1942                 $words = explode(' ', $line);
1943                 if ($wordcount + count($words) > $n) {
1944                     $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1945                            . sprintf(_("... (first %s words)"), $n);
1946                     return $new;
1947                 } else {
1948                     $wordcount += count($words);
1949                     $new[] = $line;
1950                 }
1951             }
1952             return $new;
1953         } else {
1954             // fixme: use better whitespace/word seperators
1955             $words = explode(' ', $content);
1956             if (count($words) > $n) {
1957                 return join(' ', array_slice($words, 0, $n))
1958                        . sprintf(_("... (first %s words)"), $n);
1959             } else {
1960                 return $content;
1961             }
1962         }
1963     } else {
1964         return '';
1965     }
1966 }
1967
1968 // moved from lib/plugin/IncludePage.php
1969 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1970     $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1971
1972     if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
1973                    . "  \\s*$\\n?"           // possible blank lines
1974                    . "  ( (?: ^.*\\n? )*? )" // some lines
1975                    . "  (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1976                    implode("\n", $content),
1977                    $match)) {
1978         // Strip trailing blanks lines and ---- <hr>s
1979         $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1980         if ($sectionhead)
1981             $text = $match[1] . $section ."\n". $text;
1982         return explode("\n", $text);
1983     }
1984     if ($quiet)
1985         $mesg = $page ." ". $section;
1986     else
1987         $mesg = $section;
1988     return array(sprintf(_("<%s: no such section>"), $mesg));
1989 }
1990
1991 // use this faster version: only load ExternalReferrer if we came from an external referrer
1992 function isExternalReferrer(&$request) {
1993     if ($referrer = $request->get('HTTP_REFERER')) {
1994         $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
1995         if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
1996         require_once("lib/ExternalReferrer.php");
1997         $se = new SearchEngines();
1998         return $se->parseSearchQuery($referrer);
1999     }
2000     return false;
2001 }
2002
2003 /**
2004  * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2005  */
2006 function loadPhpExtension($extension) {
2007     if (!extension_loaded($extension)) {
2008         $soname = (isWindows() ? 'php_' : '') . $extension . (isWindows() ? '.dll' : '.so');
2009         if (!@dl($soname))
2010             return false;
2011     }
2012     return extension_loaded($extension);
2013 }
2014
2015 function string_starts_with($string, $prefix) {
2016     return (substr($string, 0, strlen($prefix)) == $prefix);
2017 }
2018 function string_ends_with($string, $suffix) {
2019     return (substr($string, -strlen($suffix)) == $suffix);
2020 }
2021 function array_remove($arr,$value) {
2022    return array_values(array_diff($arr,array($value)));
2023 }
2024
2025 /** 
2026  * Ensure that the script will have another $secs time left. 
2027  * Works only if safe_mode is off.
2028  * For example not to timeout on waiting socket connections.
2029  *   Use the socket timeout as arg.
2030  */
2031 function longer_timeout($secs = 30) {
2032     $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2033     $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2034     if ($timeleft < $secs)
2035         @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2036 }
2037
2038 function printSimpleTrace($bt) {
2039     //print_r($bt);
2040     echo "Traceback:\n";
2041     foreach ($bt as $i => $elem) {
2042         if (!array_key_exists('file', $elem)) {
2043             continue;
2044         }
2045         echo join(" ",array_values($elem)),"\n";
2046         //print "  " . $elem['file'] . ':' . $elem['line'] . " " .$elem['function']"\n";
2047     }
2048 }
2049
2050 /**
2051  * Return the used process memory (in byte?)
2052  * Enable the section which will work for you. (They are very slow)
2053  * Special quirks for Windows: Requires cygwin.
2054  */
2055 function getMemoryUsage() {
2056     if (function_exists('memory_get_usage') and memory_get_usage()) {
2057         return memory_get_usage();
2058     } elseif (function_exists('getrusage') and ($u = getrusage()) and !empty($u['ru_maxrss'])) {
2059         $mem = $u['ru_maxrss'];
2060     } elseif (substr(PHP_OS,0,3) == 'WIN') { // requires a newer cygwin
2061         // what we want is the process memory only: apache or php (if CGI)
2062         $pid = getmypid();
2063         $memstr = '';
2064         // win32_ps_stat_proc, win32_ps_stat_mem
2065         if (function_exists('win32_ps_list_procs')) {
2066             $info = win32_ps_stat_proc($pid);
2067             $memstr = $info['mem']['working_set_size'];
2068         } else {
2069             // This works only if it's a cygwin process (apache or php).
2070             // Requires a newer cygwin
2071             //$memstr = exec("cat /proc/$pid/statm |cut -f1");
2072
2073             // if it's native windows use something like this: 
2074             //   (requires pslist from sysinternals.com)
2075             $memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2076         }
2077         return (integer) trim($memstr);
2078     } elseif (1) {
2079         $pid = getmypid();
2080         //%MEM: Percentage of total memory in use by this process
2081         //VSZ: Total virtual memory size, in 1K blocks.
2082         //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2083         //CPU time used by process since it started.
2084         //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2085         $memstr = exec("ps -orss -p $pid|sed 1d");
2086         return (integer) trim($memstr);
2087     }
2088 }
2089
2090 // $Log: not supported by cvs2svn $
2091 // Revision 1.254  2006/12/02 19:53:05  rurban
2092 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2093 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2094 // or later.
2095 //
2096 // Revision 1.253  2006/08/25 22:20:52  rurban
2097 // better split subpages at sep
2098 //
2099 // Revision 1.252  2006/06/18 11:03:36  rurban
2100 // support rc version
2101 //
2102 // Revision 1.251  2006/03/19 15:01:00  rurban
2103 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2104 //
2105 // Revision 1.250  2006/03/07 20:45:44  rurban
2106 // wikihash for php-5.1
2107 //
2108 // Revision 1.249  2005/10/30 14:24:33  rurban
2109 // move rand_ascii_readable from Captcha to stdlib
2110 //
2111 // Revision 1.248  2005/10/29 14:18:30  uckelman
2112 // Added is_a() deprecation note.
2113 //
2114 // Revision 1.247  2005/10/10 20:31:21  rurban
2115 // fix win32ps call
2116 //
2117 // Revision 1.246  2005/10/10 19:38:48  rurban
2118 // add win32ps
2119 //
2120 // Revision 1.245  2005/09/18 16:01:09  rurban
2121 // trick to send the correct gzipped Content-Length
2122 //
2123 // Revision 1.244  2005/09/11 13:24:33  rurban
2124 // fix shortname, dont quote twice in ListRegexExpand
2125 //
2126 // Revision 1.243  2005/08/06 15:01:38  rurban
2127 // workaround php VBASIC alike limitation: allow integer pagenames
2128 //
2129 // Revision 1.242  2005/08/06 13:07:04  rurban
2130 // quote paths correctly (not the best method though)
2131 //
2132 // Revision 1.241  2005/05/06 16:54:19  rurban
2133 // support optional EXTERNAL_LINK_TARGET, default: _blank
2134 //
2135 // Revision 1.240  2005/04/23 11:15:49  rurban
2136 // handle allowed inlined objects within INLINE_IMAGES
2137 //
2138 // Revision 1.239  2005/04/01 16:11:42  rurban
2139 // just whitespace
2140 //
2141 // Revision 1.238  2005/03/04 16:29:14  rurban
2142 // Fixed bug #994994 (escape / in glob)
2143 // Optimized glob_to_pcre within fileSet() matching.
2144 //
2145 // Revision 1.237  2005/02/12 17:22:18  rurban
2146 // locale update: missing . : fixed. unified strings
2147 // proper linebreaks
2148 //
2149 // Revision 1.236  2005/02/08 13:41:32  rurban
2150 // add rand_ascii
2151 //
2152 // Revision 1.235  2005/02/04 11:54:48  rurban
2153 // fix Talk: names
2154 //
2155 // Revision 1.234  2005/02/03 05:09:25  rurban
2156 // Talk: + User: fix
2157 //
2158 // Revision 1.233  2005/02/02 20:40:12  rurban
2159 // fix Talk: and User: names and links
2160 //
2161 // Revision 1.232  2005/02/02 19:34:09  rurban
2162 // more maps: Talk, User
2163 //
2164 // Revision 1.231  2005/01/30 19:48:52  rurban
2165 // enable ps memory on unix
2166 //
2167 // Revision 1.230  2005/01/25 07:10:51  rurban
2168 // add getMemoryUsage to stdlib
2169 //
2170 // Revision 1.229  2005/01/21 11:51:22  rurban
2171 // changed (c)
2172 //
2173 // Revision 1.228  2005/01/17 20:28:30  rurban
2174 // Allow more pagename chars: Limit only on certain backends.
2175 // Re-Allow : and ; and control chars on non-file backends.
2176 //
2177 // Revision 1.227  2005/01/14 18:32:08  uckelman
2178 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2179 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2180 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2181 // conversion of '__' into '<strong>', and then unhidden afterwards.
2182 //
2183 // Revision 1.226  2004/12/26 17:12:06  rurban
2184 // avoid stdargs in url, php5 fixes
2185 //
2186 // Revision 1.225  2004/12/22 19:02:29  rurban
2187 // fix glob for starting * or ?
2188 //
2189 // Revision 1.224  2004/12/20 12:11:50  rurban
2190 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2191 //   not reproducable other than on sf.net, but this seems to fix it.
2192 //
2193 // Revision 1.223  2004/12/18 16:49:29  rurban
2194 // fix RPC for !USE_PATH_INFO, add debugging helper
2195 //
2196 // Revision 1.222  2004/12/17 16:40:45  rurban
2197 // add not yet used url helper
2198 //
2199 // Revision 1.221  2004/12/06 19:49:58  rurban
2200 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2201 // renamed delete_page to purge_page.
2202 // enable action=edit&version=-1 to force creation of a new version.
2203 // added BABYCART_PATH config
2204 // fixed magiqc in adodb.inc.php
2205 // and some more docs
2206 //
2207 // Revision 1.220  2004/11/30 17:47:41  rurban
2208 // added mt_srand, check for native isa
2209 //
2210 // Revision 1.219  2004/11/26 18:39:02  rurban
2211 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2212 //
2213 // Revision 1.218  2004/11/25 08:28:48  rurban
2214 // support exclude
2215 //
2216 // Revision 1.217  2004/11/16 17:31:03  rurban
2217 // re-enable old block markup conversion
2218 //
2219 // Revision 1.216  2004/11/11 18:31:26  rurban
2220 // add simple backtrace on such general failures to get at least an idea where
2221 //
2222 // Revision 1.215  2004/11/11 14:34:12  rurban
2223 // minor clarifications
2224 //
2225 // Revision 1.214  2004/11/11 11:01:20  rurban
2226 // fix loadPhpExtension
2227 //
2228 // Revision 1.213  2004/11/01 10:43:57  rurban
2229 // seperate PassUser methods into seperate dir (memory usage)
2230 // fix WikiUser (old) overlarge data session
2231 // remove wikidb arg from various page class methods, use global ->_dbi instead
2232 // ...
2233 //
2234 // Revision 1.212  2004/10/22 09:15:39  rurban
2235 // Alert::show has no arg anymore
2236 //
2237 // Revision 1.211  2004/10/22 09:05:11  rurban
2238 // added longer_timeout (HttpClient)
2239 // fixed warning
2240 //
2241 // Revision 1.210  2004/10/14 21:06:02  rurban
2242 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2243 //
2244 // Revision 1.209  2004/10/14 19:19:34  rurban
2245 // loadsave: check if the dumped file will be accessible from outside.
2246 // and some other minor fixes. (cvsclient native not yet ready)
2247 //
2248 // Revision 1.208  2004/10/12 13:13:20  rurban
2249 // php5 compatibility (5.0.1 ok)
2250 //
2251 // Revision 1.207  2004/09/26 12:21:40  rurban
2252 // removed old log entries.
2253 // added persistent start_debug on internal links and DEBUG
2254 // added isExternalReferrer (not yet used)
2255 //
2256 // Revision 1.206  2004/09/25 16:28:36  rurban
2257 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2258 //
2259 // Revision 1.205  2004/09/23 13:59:35  rurban
2260 // Before removing a page display a sample of 100 words.
2261 //
2262 // Revision 1.204  2004/09/17 13:19:15  rurban
2263 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2264 // by SteveBennett.
2265 //
2266 // Revision 1.203  2004/09/16 08:00:52  rurban
2267 // just some comments
2268 //
2269 // Revision 1.202  2004/09/14 10:11:44  rurban
2270 // start 2nd Id with ...Plugin2
2271 //
2272 // Revision 1.201  2004/09/14 10:06:42  rurban
2273 // generate iterated plugin ids, set plugin span id also
2274 //
2275 // Revision 1.200  2004/08/05 17:34:26  rurban
2276 // move require to sortby branch
2277 //
2278 // Revision 1.199  2004/08/05 10:38:15  rurban
2279 // fix Bug #993692:  Making Snapshots or Backups doesn't work anymore
2280 // in CVS version.
2281 //
2282 // Revision 1.198  2004/07/02 10:30:36  rurban
2283 // always disable getimagesize for < php-4.3 with external png's
2284 //
2285 // Revision 1.197  2004/07/02 09:55:58  rurban
2286 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2287 //
2288 // Revision 1.196  2004/07/01 08:51:22  rurban
2289 // dumphtml: added exclude, print pagename before processing
2290 //
2291 // Revision 1.195  2004/06/29 08:52:22  rurban
2292 // Use ...version() $need_content argument in WikiDB also:
2293 // To reduce the memory footprint for larger sets of pagelists,
2294 // we don't cache the content (only true or false) and
2295 // we purge the pagedata (_cached_html) also.
2296 // _cached_html is only cached for the current pagename.
2297 // => Vastly improved page existance check, ACL check, ...
2298 //
2299 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2300 //
2301 // Revision 1.194  2004/06/29 06:48:04  rurban
2302 // Improve LDAP auth and GROUP_LDAP membership:
2303 //   no error message on false password,
2304 //   added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2305 //   fixed two group queries (this -> user)
2306 // stdlib: ConvertOldMarkup still flawed
2307 //
2308 // Revision 1.193  2004/06/28 13:27:03  rurban
2309 // CreateToc disabled for old markup and Apache2 only
2310 //
2311 // Revision 1.192  2004/06/28 12:47:43  rurban
2312 // skip if non-DEBUG and old markup with CreateToc
2313 //
2314 // Revision 1.191  2004/06/25 14:31:56  rurban
2315 // avoid debug_skip warning
2316 //
2317 // Revision 1.190  2004/06/25 14:29:20  rurban
2318 // WikiGroup refactoring:
2319 //   global group attached to user, code for not_current user.
2320 //   improved helpers for special groups (avoid double invocations)
2321 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2322 // fixed a XHTML validation error on userprefs.tmpl
2323 //
2324 // Revision 1.189  2004/06/20 09:45:35  rurban
2325 // php5 isa fix (wrong strtolower)
2326 //
2327 // Revision 1.188  2004/06/16 10:38:58  rurban
2328 // Disallow refernces in calls if the declaration is a reference
2329 // ("allow_call_time_pass_reference clean").
2330 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
2331 //   but several external libraries may not.
2332 //   In detail these libs look to be affected (not tested):
2333 //   * Pear_DB odbc
2334 //   * adodb oracle
2335 //
2336 // Revision 1.187  2004/06/14 11:31:37  rurban
2337 // renamed global $Theme to $WikiTheme (gforge nameclash)
2338 // inherit PageList default options from PageList
2339 //   default sortby=pagename
2340 // use options in PageList_Selectable (limit, sortby, ...)
2341 // added action revert, with button at action=diff
2342 // added option regex to WikiAdminSearchReplace
2343 //
2344 // Revision 1.186  2004/06/13 13:54:25  rurban
2345 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2346 // FoafViewer: Check against external requirements, instead of fatal.
2347 // Change output for xhtmldumps: using file:// urls to the local fs.
2348 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2349 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2350 //
2351 // Revision 1.185  2004/06/11 09:07:30  rurban
2352 // support theme-specific LinkIconAttr: front or after or none
2353 //
2354 // Revision 1.184  2004/06/04 20:32:53  rurban
2355 // Several locale related improvements suggested by Pierrick Meignen
2356 // LDAP fix by John Cole
2357 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2358 //
2359 // Revision 1.183  2004/06/01 10:22:56  rurban
2360 // added url_get_contents() used in XmlParser and elsewhere
2361 //
2362 // Revision 1.182  2004/05/25 12:40:48  rurban
2363 // trim the pagename
2364 //
2365 // Revision 1.181  2004/05/25 10:18:44  rurban
2366 // Check for UTF-8 URLs; Internet Explorer produces these if you
2367 // type non-ASCII chars in the URL bar or follow unescaped links.
2368 // Fixes sf.net bug #953949
2369 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2370 //
2371 // Revision 1.180  2004/05/18 16:23:39  rurban
2372 // rename split_pagename to SplitPagename
2373 //
2374 // Revision 1.179  2004/05/18 16:18:37  rurban
2375 // AutoSplit at subpage seperators
2376 // RssFeed stability fix for empty feeds or broken connections
2377 //
2378 // Revision 1.178  2004/05/12 10:49:55  rurban
2379 // require_once fix for those libs which are loaded before FileFinder and
2380 //   its automatic include_path fix, and where require_once doesn't grok
2381 //   dirname(__FILE__) != './lib'
2382 // upgrade fix with PearDB
2383 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2384 //
2385 // Revision 1.177  2004/05/08 14:06:12  rurban
2386 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2387 // minor stability and portability fixes
2388 //
2389 // Revision 1.176  2004/05/08 11:25:15  rurban
2390 // php-4.0.4 fixes
2391 //
2392 // Revision 1.175  2004/05/06 17:30:38  rurban
2393 // CategoryGroup: oops, dos2unix eol
2394 // improved phpwiki_version:
2395 //   pre -= .0001 (1.3.10pre: 1030.099)
2396 //   -p1 += .001 (1.3.9-p1: 1030.091)
2397 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2398 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2399 //   backend->backendType(), backend->database(),
2400 //   backend->listOfFields(),
2401 //   backend->listOfTables(),
2402 //
2403 // Revision 1.174  2004/05/06 12:02:05  rurban
2404 // fix sf.net bug#949002: [ Link | ] assertion
2405 //
2406 // Revision 1.173  2004/05/03 15:00:31  rurban
2407 // added more database upgrading: session.sess_ip, page.id autp_increment
2408 //
2409 // Revision 1.172  2004/04/26 20:44:34  rurban
2410 // locking table specific for better databases
2411 //
2412 // Revision 1.171  2004/04/19 23:13:03  zorloc
2413 // Connect the rest of PhpWiki to the IniConfig system.  Also the keyword regular expression is not a config setting
2414 //
2415 // Revision 1.170  2004/04/19 18:27:45  rurban
2416 // Prevent from some PHP5 warnings (ref args, no :: object init)
2417 //   php5 runs now through, just one wrong XmlElement object init missing
2418 // Removed unneccesary UpgradeUser lines
2419 // Changed WikiLink to omit version if current (RecentChanges)
2420 //
2421 // Revision 1.169  2004/04/15 21:29:48  rurban
2422 // allow [0] with new markup: link to page "0"
2423 //
2424 // Revision 1.168  2004/04/10 02:30:49  rurban
2425 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2426 // Fixed "cannot setlocale..." (sf.net problem)
2427 //
2428 // Revision 1.167  2004/04/02 15:06:55  rurban
2429 // fixed a nasty ADODB_mysql session update bug
2430 // improved UserPreferences layout (tabled hints)
2431 // fixed UserPreferences auth handling
2432 // improved auth stability
2433 // improved old cookie handling: fixed deletion of old cookies with paths
2434 //
2435 // Revision 1.166  2004/04/01 15:57:10  rurban
2436 // simplified Sidebar theme: table, not absolute css positioning
2437 // added the new box methods.
2438 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2439 //
2440 // Revision 1.165  2004/03/24 19:39:03  rurban
2441 // php5 workaround code (plus some interim debugging code in XmlElement)
2442 //   php5 doesn't work yet with the current XmlElement class constructors,
2443 //   WikiUserNew does work better than php4.
2444 // rewrote WikiUserNew user upgrading to ease php5 update
2445 // fixed pref handling in WikiUserNew
2446 // added Email Notification
2447 // added simple Email verification
2448 // removed emailVerify userpref subclass: just a email property
2449 // changed pref binary storage layout: numarray => hash of non default values
2450 // print optimize message only if really done.
2451 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2452 //   prefs should be stored in db or homepage, besides the current session.
2453 //
2454 // Revision 1.164  2004/03/18 21:41:09  rurban
2455 // fixed sqlite support
2456 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2457 //
2458 // Revision 1.163  2004/03/17 18:41:49  rurban
2459 // just reformatting
2460 //
2461 // Revision 1.162  2004/03/16 15:43:08  rurban
2462 // make fileSet sortable to please PageList
2463 //
2464 // Revision 1.161  2004/03/12 15:48:07  rurban
2465 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2466 // simplified lib/stdlib.php:explodePageList
2467 //
2468 // Revision 1.160  2004/02/28 21:14:08  rurban
2469 // generally more PHPDOC docs
2470 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2471 // fxied WikiUserNew pref handling: empty theme not stored, save only
2472 //   changed prefs, sql prefs improved, fixed password update,
2473 //   removed REPLACE sql (dangerous)
2474 // moved gettext init after the locale was guessed
2475 // + some minor changes
2476 //
2477
2478 // (c-file-style: "gnu")
2479 // Local Variables:
2480 // mode: php
2481 // tab-width: 8
2482 // c-basic-offset: 4
2483 // c-hanging-comment-ender-p: nil
2484 // indent-tabs-mode: nil
2485 // End:   
2486 ?>