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