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