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