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