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