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