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