]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
ConvertOldMarkup did not properly handle links containing pairs of pairs
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.227 2005-01-14 18:32:08 uckelman 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         // Temporarily URL-encode pairs of underscores in links to hide
756         // them from the re for bold markup.
757         $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
758         $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
759
760         // Escape '<'s
761         //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
762         //$repl[] = '~<';
763         
764         // Convert footnote references.
765         $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
766         $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
767
768         // Convert old style emphases to HTML style emphasis.
769         $orig[] = '/__(.*?)__/';
770         $repl[] = '<strong>\\1</strong>';
771         $orig[] = "/''(.*?)''/";
772         $repl[] = '<em>\\1</em>';
773
774         // Escape nestled markup.
775         $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
776         $repl[] = '~\\0';
777         
778         // in old markup headings only allowed at beginning of line
779         $orig[] = '/!/';
780         $repl[] = '~!';
781
782         // Convert URL-encoded pairs of underscores in links back to
783         // real underscores after bold markup has been converted.
784         $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
785         $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
786
787         $subs["inline"] = array($orig, $repl);
788
789         /*****************************************************************
790          * Patterns which match block markup constructs which take
791          * special handling...
792          */
793
794         // Indented blocks
795         $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
796         // Tables
797         $blockpats[] = '\|(?:.*\n\|)*';
798
799         // List items
800         $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
801
802         // Footnote definitions
803         $blockpats[] = '\[\s*(\d+)\s*\]';
804
805         if (!$debug_skip) {
806         // Plugins
807         $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
808         }
809
810         // Section Title
811         $blockpats[] = '!{1,3}[^!]';
812         /*
813         removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
814         this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
815         */
816         $block_re = ( '/\A((?:.|\n)*?)(^(?:'
817                       . join("|", $blockpats)
818                       . ').*$)\n?/m' );
819         
820     }
821     
822     if ($markup_type != "block") {
823         list ($orig, $repl) = $subs[$markup_type];
824         return preg_replace($orig, $repl, $text);
825     }
826     else {
827         list ($orig, $repl) = $subs['inline'];
828         $out = '';
829         //FIXME:
830         // php crashes here in the 2nd paragraph of OldTextFormattingRules, 
831         // AnciennesR%E8glesDeFormatage and more 
832         // See http://www.pcre.org/pcre.txt LIMITATIONS
833          while (preg_match($block_re, $text, $m)) {
834             $text = substr($text, strlen($m[0]));
835             list (,$leading_text, $block) = $m;
836             $suffix = "\n";
837             
838             if (strchr(" \t", $block[0])) {
839                 // Indented block
840                 $prefix = "<pre>\n";
841                 $suffix = "\n</pre>\n";
842             }
843             elseif ($block[0] == '|') {
844                 // Old-style table
845                 $prefix = "<?plugin OldStyleTable\n";
846                 $suffix = "\n?>\n";
847             }
848             elseif (strchr("#*;", $block[0])) {
849                 // Old-style list item
850                 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
851                 list (,$ind,$bullet) = $m;
852                 $block = substr($block, strlen($m[0]));
853                 
854                 $indent = str_repeat('     ', strlen($ind));
855                 if ($bullet[0] == ';') {
856                     //$term = ltrim(substr($bullet, 1));
857                     //return $indent . $term . "\n" . $indent . '     ';
858                     $prefix = $ind . $bullet;
859                 }
860                 else
861                     $prefix = $indent . $bullet . ' ';
862             }
863             elseif ($block[0] == '[') {
864                 // Footnote definition
865                 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
866                 $footnum = $m[1];
867                 $block = substr($block, strlen($m[0]));
868                 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
869             }
870             elseif ($block[0] == '<') {
871                 // Plugin.
872                 // HACK: no inline markup...
873                 $prefix = $block;
874                 $block = '';
875             }
876             elseif ($block[0] == '!') {
877                 // Section heading
878                 preg_match('/^!{1,3}/', $block, $m);
879                 $prefix = $m[0];
880                 $block = substr($block, strlen($m[0]));
881             }
882             else {
883                 // AAck!
884                 assert(0);
885             }
886             if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
887             if ($block) $block = preg_replace($orig, $repl, $block);
888             $out .= $leading_text;
889             $out .= $prefix;
890             $out .= $block;
891             $out .= $suffix;
892         }
893         return $out . preg_replace($orig, $repl, $text);
894     }
895 }
896
897
898 /**
899  * Expand tabs in string.
900  *
901  * Converts all tabs to (the appropriate number of) spaces.
902  *
903  * @param string $str
904  * @param integer $tab_width
905  * @return string
906  */
907 function expand_tabs($str, $tab_width = 8) {
908     $split = split("\t", $str);
909     $tail = array_pop($split);
910     $expanded = "\n";
911     foreach ($split as $hunk) {
912         $expanded .= $hunk;
913         $pos = strlen(strrchr($expanded, "\n")) - 1;
914         $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
915     }
916     return substr($expanded, 1) . $tail;
917 }
918
919 /**
920  * Split WikiWords in page names.
921  *
922  * It has been deemed useful to split WikiWords (into "Wiki Words") in
923  * places like page titles. This is rumored to help search engines
924  * quite a bit.
925  *
926  * @param $page string The page name.
927  *
928  * @return string The split name.
929  */
930 function SplitPagename ($page) {
931     
932     if (preg_match("/\s/", $page))
933         return $page;           // Already split --- don't split any more.
934     
935     // This algorithm is specialized for several languages.
936     // (Thanks to Pierrick MEIGNEN)
937     // Improvements for other languages welcome.
938     static $RE;
939     if (!isset($RE)) {
940         // This mess splits between a lower-case letter followed by
941         // either an upper-case or a numeral; except that it wont
942         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
943         switch ($GLOBALS['LANG']) {
944         case 'en':
945         case 'it':
946         case 'es': 
947         case 'de':
948             $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
949             break;
950         case 'fr': 
951             $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
952             break;
953         }
954         $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
955         // This the single-letter words 'I' and 'A' from any following
956         // capitalized words.
957         switch ($GLOBALS['LANG']) {
958         case 'en': 
959             $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
960             break;
961         case 'fr': 
962             $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
963             break;
964         }
965         // Split numerals from following letters.
966         $RE[] = '/(\d)([[:alpha:]])/';
967         // Split at subpage seperators. TBD in Theme.php
968         $RE[] = "/([^${sep}]+)(${sep})/";
969         
970         foreach ($RE as $key)
971             $RE[$key] = pcre_fix_posix_classes($key);
972     }
973
974     foreach ($RE as $regexp) {
975         $page = preg_replace($regexp, '\\1 \\2', $page);
976     }
977     return $page;
978 }
979
980 function NoSuchRevision (&$request, $page, $version) {
981     $html = HTML(HTML::h2(_("Revision Not Found")),
982                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
983                              $version, WikiLink($page, 'auto'))));
984     include_once('lib/Template.php');
985     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
986     $request->finish();
987 }
988
989
990 /**
991  * Get time offset for local time zone.
992  *
993  * @param $time time_t Get offset for this time. Default: now.
994  * @param $no_colon boolean Don't put colon between hours and minutes.
995  * @return string Offset as a string in the format +HH:MM.
996  */
997 function TimezoneOffset ($time = false, $no_colon = false) {
998     if ($time === false)
999         $time = time();
1000     $secs = date('Z', $time);
1001
1002     if ($secs < 0) {
1003         $sign = '-';
1004         $secs = -$secs;
1005     }
1006     else {
1007         $sign = '+';
1008     }
1009     $colon = $no_colon ? '' : ':';
1010     $mins = intval(($secs + 30) / 60);
1011     return sprintf("%s%02d%s%02d",
1012                    $sign, $mins / 60, $colon, $mins % 60);
1013 }
1014
1015
1016 /**
1017  * Format time in ISO-8601 format.
1018  *
1019  * @param $time time_t Time.  Default: now.
1020  * @return string Date and time in ISO-8601 format.
1021  */
1022 function Iso8601DateTime ($time = false) {
1023     if ($time === false)
1024         $time = time();
1025     $tzoff = TimezoneOffset($time);
1026     $date  = date('Y-m-d', $time);
1027     $time  = date('H:i:s', $time);
1028     return $date . 'T' . $time . $tzoff;
1029 }
1030
1031 /**
1032  * Format time in RFC-2822 format.
1033  *
1034  * @param $time time_t Time.  Default: now.
1035  * @return string Date and time in RFC-2822 format.
1036  */
1037 function Rfc2822DateTime ($time = false) {
1038     if ($time === false)
1039         $time = time();
1040     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1041 }
1042
1043 /**
1044  * Format time in RFC-1123 format.
1045  *
1046  * @param $time time_t Time.  Default: now.
1047  * @return string Date and time in RFC-1123 format.
1048  */
1049 function Rfc1123DateTime ($time = false) {
1050     if ($time === false)
1051         $time = time();
1052     return gmdate('D, d M Y H:i:s \G\M\T', $time);
1053 }
1054
1055 /** Parse date in RFC-1123 format.
1056  *
1057  * According to RFC 1123 we must accept dates in the following
1058  * formats:
1059  *
1060  *   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
1061  *   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1062  *   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
1063  *
1064  * (Though we're only allowed to generate dates in the first format.)
1065  */
1066 function ParseRfc1123DateTime ($timestr) {
1067     $timestr = trim($timestr);
1068     if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1069                    .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1070                    $timestr, $m)) {
1071         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1072     }
1073     elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1074                        .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1075                        $timestr, $m)) {
1076         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1077         if ($year < 70) $year += 2000;
1078         elseif ($year < 100) $year += 1900;
1079     }
1080     elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1081                        .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1082                        $timestr, $m)) {
1083         list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1084     }
1085     else {
1086         // Parse failed.
1087         return false;
1088     }
1089
1090     $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1091     if ($time == -1)
1092         return false;           // failed
1093     return $time;
1094 }
1095
1096 /**
1097  * Format time to standard 'ctime' format.
1098  *
1099  * @param $time time_t Time.  Default: now.
1100  * @return string Date and time.
1101  */
1102 function CTime ($time = false)
1103 {
1104     if ($time === false)
1105         $time = time();
1106     return date("D M j H:i:s Y", $time);
1107 }
1108
1109
1110 /**
1111  * Format number as kilobytes or bytes.
1112  * Short format is used for PageList
1113  * Long format is used in PageInfo
1114  *
1115  * @param $bytes       int.  Default: 0.
1116  * @param $longformat  bool. Default: false.
1117  * @return class FormattedText (XmlElement.php).
1118  */
1119 function ByteFormatter ($bytes = 0, $longformat = false) {
1120     if ($bytes < 0)
1121         return fmt("-???");
1122     if ($bytes < 1024) {
1123         if (! $longformat)
1124             $size = fmt("%s b", $bytes);
1125         else
1126             $size = fmt("%s bytes", $bytes);
1127     }
1128     else {
1129         $kb = round($bytes / 1024, 1);
1130         if (! $longformat)
1131             $size = fmt("%s k", $kb);
1132         else
1133             $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1134     }
1135     return $size;
1136 }
1137
1138 /**
1139  * Internationalized printf.
1140  *
1141  * This is essentially the same as PHP's built-in printf
1142  * with the following exceptions:
1143  * <ol>
1144  * <li> It passes the format string through gettext().
1145  * <li> It supports the argument reordering extensions.
1146  * </ol>
1147  *
1148  * Example:
1149  *
1150  * In php code, use:
1151  * <pre>
1152  *    __printf("Differences between versions %s and %s of %s",
1153  *             $new_link, $old_link, $page_link);
1154  * </pre>
1155  *
1156  * Then in locale/po/de.po, one can reorder the printf arguments:
1157  *
1158  * <pre>
1159  *    msgid "Differences between %s and %s of %s."
1160  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1161  * </pre>
1162  *
1163  * (Note that while PHP tries to expand $vars within double-quotes,
1164  * the values in msgstr undergo no such expansion, so the '$'s
1165  * okay...)
1166  *
1167  * One shouldn't use reordered arguments in the default format string.
1168  * Backslashes in the default string would be necessary to escape the
1169  * '$'s, and they'll cause all kinds of trouble....
1170  */ 
1171 function __printf ($fmt) {
1172     $args = func_get_args();
1173     array_shift($args);
1174     echo __vsprintf($fmt, $args);
1175 }
1176
1177 /**
1178  * Internationalized sprintf.
1179  *
1180  * This is essentially the same as PHP's built-in printf with the
1181  * following exceptions:
1182  *
1183  * <ol>
1184  * <li> It passes the format string through gettext().
1185  * <li> It supports the argument reordering extensions.
1186  * </ol>
1187  *
1188  * @see __printf
1189  */ 
1190 function __sprintf ($fmt) {
1191     $args = func_get_args();
1192     array_shift($args);
1193     return __vsprintf($fmt, $args);
1194 }
1195
1196 /**
1197  * Internationalized vsprintf.
1198  *
1199  * This is essentially the same as PHP's built-in printf with the
1200  * following exceptions:
1201  *
1202  * <ol>
1203  * <li> It passes the format string through gettext().
1204  * <li> It supports the argument reordering extensions.
1205  * </ol>
1206  *
1207  * @see __printf
1208  */ 
1209 function __vsprintf ($fmt, $args) {
1210     $fmt = gettext($fmt);
1211     // PHP's sprintf doesn't support variable with specifiers,
1212     // like sprintf("%*s", 10, "x"); --- so we won't either.
1213     
1214     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1215         // Format string has '%2$s' style argument reordering.
1216         // PHP doesn't support this.
1217         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1218             // literal variable name substitution only to keep locale
1219             // strings uncluttered
1220             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1221                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
1222         
1223         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1224         $newargs = array();
1225         
1226         // Reorder arguments appropriately.
1227         foreach($m[1] as $argnum) {
1228             if ($argnum < 1 || $argnum > count($args))
1229                 trigger_error(sprintf(_("%s: argument index out of range"), 
1230                                       $argnum), E_USER_WARNING);
1231             $newargs[] = $args[$argnum - 1];
1232         }
1233         $args = $newargs;
1234     }
1235     
1236     // Not all PHP's have vsprintf, so...
1237     array_unshift($args, $fmt);
1238     return call_user_func_array('sprintf', $args);
1239 }
1240
1241 function file_mtime ($filename) {
1242     if ($stat = @stat($filename))
1243         return $stat[9];
1244     else 
1245         return false;
1246 }
1247
1248 function sort_file_mtime ($a, $b) {
1249     $ma = file_mtime($a);
1250     $mb = file_mtime($b);
1251     if (!$ma or !$mb or $ma == $mb) return 0;
1252     return ($ma > $mb) ? -1 : 1;
1253 }
1254
1255 class fileSet {
1256     /**
1257      * Build an array in $this->_fileList of files from $dirname.
1258      * Subdirectories are not traversed.
1259      *
1260      * (This was a function LoadDir in lib/loadsave.php)
1261      * See also http://www.php.net/manual/en/function.readdir.php
1262      */
1263     function getFiles($exclude=false, $sortby=false, $limit=false) {
1264         $list = $this->_fileList;
1265
1266         if ($sortby) {
1267             require_once('lib/PageList.php');
1268             switch (Pagelist::sortby($sortby, 'db')) {
1269             case 'pagename ASC': break;
1270             case 'pagename DESC': 
1271                 $list = array_reverse($list); 
1272                 break;
1273             case 'mtime ASC': 
1274                 usort($list,'sort_file_mtime'); 
1275                 break;
1276             case 'mtime DESC': 
1277                 usort($list,'sort_file_mtime');
1278                 $list = array_reverse($list); 
1279                 break;
1280             }
1281         }
1282         if ($limit)
1283             return array_splice($list, 0, $limit);
1284         return $list;
1285     }
1286
1287     function _filenameSelector($filename) {
1288         if (! $this->_pattern)
1289             return true;
1290         else {
1291             return glob_match ($this->_pattern, $filename, $this->_case);
1292         }
1293     }
1294
1295     function fileSet($directory, $filepattern = false) {
1296         $this->_fileList = array();
1297         $this->_pattern = $filepattern;
1298         $this->_case = !isWindows();
1299         $this->_pathsep = '/';
1300
1301         if (empty($directory)) {
1302             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1303                           E_USER_NOTICE);
1304             return; // early return
1305         }
1306
1307         @ $dir_handle = opendir($dir=$directory);
1308         if (empty($dir_handle)) {
1309             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1310                                   $dir), E_USER_NOTICE);
1311             return; // early return
1312         }
1313
1314         while ($filename = readdir($dir_handle)) {
1315             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1316                 continue;
1317             if ($this->_filenameSelector($filename)) {
1318                 array_push($this->_fileList, "$filename");
1319                 //trigger_error(sprintf(_("found file %s"), $filename),
1320                 //                      E_USER_NOTICE); //debugging
1321             }
1322         }
1323         closedir($dir_handle);
1324     }
1325 };
1326
1327 // File globbing
1328
1329 // expands a list containing regex's to its matching entries
1330 class ListRegexExpand {
1331     //var $match, $list, $index, $case_sensitive;
1332     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1333         $this->match = str_replace('/','\/',$match);
1334         $this->list = &$list;
1335         $this->case_sensitive = $case_sensitive;        
1336         //$this->index = false;
1337     }
1338     function listMatchCallback ($item, $key) {
1339         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1340             unset($this->list[$this->index]);
1341             $this->list[] = $item;
1342         }
1343     }
1344     function expandRegex ($index, &$pages) {
1345         $this->index = $index;
1346         array_walk($pages, array($this, 'listMatchCallback'));
1347         return $this->list;
1348     }
1349 }
1350
1351 // convert fileglob to regex style:
1352 // convert some wildcards to pcre style, escape the rest
1353 // escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : 
1354 function glob_to_pcre ($glob) {
1355     // check simple case: no need to escape
1356     if (strcspn($glob, ".\\+*?[^]$(){}=!<>|:") == strlen($glob))
1357         return $glob;
1358     // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1359     $glob = strtr($glob, "\\", "\xff");
1360     // first convert some unescaped expressions to pcre style: . => \.
1361     $escape = ".^$";
1362     $re = preg_replace('/([^\xff])?(['.preg_quote($escape).'])/', "\\1\xff\\2", $glob);
1363
1364     // * => .*, ? => .
1365     $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1366     $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1367     if (!preg_match('/^[\?\*]/',$glob))
1368         $re = '^' . $re;
1369     if (!preg_match('/[\?\*]$/',$glob))
1370         $re = $re . '$';
1371
1372     // .*? handled above, now escape the rest
1373     $escape = '\[](){}=!<>|:';
1374     while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1375         $re = preg_replace('/([^\xff])(['.preg_quote($escape).'])/', "\\1\xff\\2", $re);
1376     return strtr($re, "\xff", "\\");
1377 }
1378
1379 function glob_match ($glob, $against, $case_sensitive = true) {
1380     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1381 }
1382
1383 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1384     $list = explode(',',$input);
1385     // expand wildcards from list of $allnames
1386     if (preg_match('/[\?\*]/',$input)) {
1387         // Optimizing loop invariants:
1388         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1389         for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1390             $f = $list[$i];
1391             if (preg_match('/[\?\*]/',$f)) {
1392                 reset($allnames);
1393                 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1394                 $expand->expandRegex($i, $allnames);
1395             }
1396         }
1397     }
1398     return $list;
1399 }
1400
1401 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1402 function explodePageList($input, $include_empty=false, $sortby='pagename', $limit=false, $exclude=false) {
1403     include_once("lib/PageList.php");
1404     return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1405 }
1406
1407 // Class introspections
1408
1409 /** 
1410  * Determine whether object is of a specified type.
1411  * In PHP builtin since 4.2.0 as is_a()
1412  *
1413  * @param $object object An object.
1414  * @param $class string Class name.
1415  * @return bool True iff $object is a $class
1416  * or a sub-type of $class. 
1417  */
1418 function isa ($object, $class) {
1419     //if (check_php_version(5)) 
1420     //    return $object instanceof $class;
1421     if (check_php_version(4,2) and !check_php_version(5)) 
1422         return is_a($object, $class);
1423
1424     $lclass = check_php_version(5) ? $class : strtolower($class);
1425     return is_object($object)
1426         && ( strtolower(get_class($object)) == strtolower($class)
1427              || is_subclass_of($object, $lclass) );
1428 }
1429
1430 /** Determine whether (possible) object has method.
1431  *
1432  * @param $object mixed Object
1433  * @param $method string Method name
1434  * @return bool True iff $object is an object with has method $method.
1435  */
1436 function can ($object, $method) {
1437     return is_object($object) && method_exists($object, strtolower($method));
1438 }
1439
1440 /** Determine whether a function is okay to use.
1441  *
1442  * Some providers (e.g. Lycos) disable some of PHP functions for
1443  * "security reasons."  This makes those functions, of course,
1444  * unusable, despite the fact the function_exists() says they
1445  * exist.
1446  *
1447  * This function test to see if a function exists and is not
1448  * disallowed by PHP's disable_functions config setting.
1449  *
1450  * @param string $function_name  Function name
1451  * @return bool  True iff function can be used.
1452  */
1453 function function_usable($function_name) {
1454     static $disabled;
1455     if (!is_array($disabled)) {
1456         $disabled = array();
1457         // Use get_cfg_var since ini_get() is one of the disabled functions
1458         // (on Lycos, at least.)
1459         $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1460         foreach ($split as $f)
1461             $disabled[strtolower($f)] = true;
1462     }
1463
1464     return ( function_exists($function_name)
1465              and ! isset($disabled[strtolower($function_name)])
1466              );
1467 }
1468     
1469     
1470 /** Hash a value.
1471  *
1472  * This is used for generating ETags.
1473  */
1474 function hash ($x) {
1475     if (is_scalar($x)) {
1476         return $x;
1477     }
1478     elseif (is_array($x)) {            
1479         ksort($x);
1480         return md5(serialize($x));
1481     }
1482     elseif (is_object($x)) {
1483         return $x->hash();
1484     }
1485     trigger_error("Can't hash $x", E_USER_ERROR);
1486 }
1487
1488     
1489 /**
1490  * Seed the random number generator.
1491  *
1492  * better_srand() ensures the randomizer is seeded only once.
1493  * 
1494  * How random do you want it? See:
1495  * http://www.php.net/manual/en/function.srand.php
1496  * http://www.php.net/manual/en/function.mt-srand.php
1497  */
1498 function better_srand($seed = '') {
1499     static $wascalled = FALSE;
1500     if (!$wascalled) {
1501         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1502         function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1503         $wascalled = TRUE;
1504         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1505     }
1506 }
1507
1508 /**
1509  * Recursively count all non-empty elements 
1510  * in array of any dimension or mixed - i.e. 
1511  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1512  * See http://www.php.net/manual/en/function.count.php
1513  */
1514 function count_all($arg) {
1515     // skip if argument is empty
1516     if ($arg) {
1517         //print_r($arg); //debugging
1518         $count = 0;
1519         // not an array, return 1 (base case) 
1520         if(!is_array($arg))
1521             return 1;
1522         // else call recursively for all elements $arg
1523         foreach($arg as $key => $val)
1524             $count += count_all($val);
1525         return $count;
1526     }
1527 }
1528
1529 function isSubPage($pagename) {
1530     return (strstr($pagename, SUBPAGE_SEPARATOR));
1531 }
1532
1533 function subPageSlice($pagename, $pos) {
1534     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1535     $pages = array_slice($pages,$pos,1);
1536     return $pages[0];
1537 }
1538
1539 /**
1540  * Alert
1541  *
1542  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1543  * pop up...)
1544  *
1545  * FIXME:
1546  * This is a hackish and needs to be refactored.  However it would be nice to
1547  * unify all the different methods we use for showing Alerts and Dialogs.
1548  * (E.g. "Page deleted", login form, ...)
1549  */
1550 class Alert {
1551     /** Constructor
1552      *
1553      * @param object $request
1554      * @param mixed $head  Header ("title") for alert box.
1555      * @param mixed $body  The text in the alert box.
1556      * @param hash $buttons  An array mapping button labels to URLs.
1557      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1558      */
1559     function Alert($head, $body, $buttons=false) {
1560         if ($buttons === false)
1561             $buttons = array();
1562
1563         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1564         $this->_buttons = $buttons;
1565     }
1566
1567     /**
1568      * Show the alert box.
1569      */
1570     function show() {
1571         global $request;
1572
1573         $tokens = $this->_tokens;
1574         $tokens['BUTTONS'] = $this->_getButtons();
1575         
1576         $request->discardOutput();
1577         $tmpl = new Template('dialog', $request, $tokens);
1578         $tmpl->printXML();
1579         $request->finish();
1580     }
1581
1582
1583     function _getButtons() {
1584         global $request;
1585
1586         $buttons = $this->_buttons;
1587         if (!$buttons)
1588             $buttons = array(_("Okay") => $request->getURLtoSelf());
1589         
1590         global $WikiTheme;
1591         foreach ($buttons as $label => $url)
1592             print "$label $url\n";
1593             $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1594         return new XmlContent($out);
1595     }
1596 }
1597
1598 // 1.3.8     => 1030.08
1599 // 1.3.9-p1  => 1030.091
1600 // 1.3.10pre => 1030.099
1601 // 1.3.11pre-20041120 => 1030.1120041120
1602 function phpwiki_version() {
1603     static $PHPWIKI_VERSION;
1604     if (!isset($PHPWIKI_VERSION)) {
1605         $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1606         $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1607         $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1608         if (strstr(PHPWIKI_VERSION, 'pre'))
1609             $PHPWIKI_VERSION -= 0.01;
1610     }
1611     return $PHPWIKI_VERSION;
1612 }
1613
1614 function isWikiWord($word) {
1615     global $WikiNameRegexp;
1616     //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1617     return preg_match("/^$WikiNameRegexp\$/",$word);
1618 }
1619
1620 // needed to store serialized objects-values only (perm, pref)
1621 function obj2hash ($obj, $exclude = false, $fields = false) {
1622     $a = array();
1623     if (! $fields ) $fields = get_object_vars($obj);
1624     foreach ($fields as $key => $val) {
1625         if (is_array($exclude)) {
1626             if (in_array($key,$exclude)) continue;
1627         }
1628         $a[$key] = $val;
1629     }
1630     return $a;
1631 }
1632
1633 /**
1634  * isUtf8String($string) - cheap utf-8 detection
1635  *
1636  * segfaults for strings longer than 10kb!
1637  * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1638  * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1639  */
1640 function isUtf8String( $s ) {
1641     $ptrASCII  = '[\x00-\x7F]';
1642     $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1643     $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1644     $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1645     $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1646     $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1647     return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1648 }
1649
1650 /** 
1651  * Check for UTF-8 URLs; Internet Explorer produces these if you
1652  * type non-ASCII chars in the URL bar or follow unescaped links.
1653  * Requires urldecoded pagename.
1654  * Fixes sf.net bug #953949
1655  *
1656  * src: languages/Language.php:checkTitleEncoding() from mediawiki
1657  */
1658 function fixTitleEncoding( $s ) {
1659     global $charset;
1660
1661     $s = trim($s);
1662     // print a warning?
1663     if (empty($s)) return $s;
1664
1665     $ishigh = preg_match( '/[\x80-\xff]/', $s);
1666     /*
1667     $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1668                                     '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1669     */
1670     $isutf = ($ishigh ? isUtf8String($s) : true);
1671     $locharset = strtolower($charset);
1672
1673     if( $locharset != "utf-8" and $ishigh and $isutf )
1674         // if charset == 'iso-8859-1' then simply use utf8_decode()
1675         if ($locharset == 'iso-8859-1')
1676             return utf8_decode( $s );
1677         else
1678             // TODO: check for iconv support
1679             return iconv( "UTF-8", $charset, $s );
1680
1681     if ($locharset == "utf-8" and $ishigh and !$isutf )
1682         return utf8_encode( $s );
1683
1684     // Other languages can safely leave this function, or replace
1685     // it with one to detect and convert another legacy encoding.
1686     return $s;
1687 }
1688
1689 /** 
1690  * MySQL fulltext index doesn't grok utf-8, so we
1691  * need to fold cases and convert to hex.
1692  * src: languages/Language.php:stripForSearch() from mediawiki
1693  */
1694 /*
1695 function stripForSearch( $string ) {
1696     global $wikiLowerChars; 
1697     // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1698     return preg_replace(
1699                         "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1700                         "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1701                         $string );
1702 }
1703 */
1704
1705 /** 
1706  * Workaround for allow_url_fopen, to get the content of an external URI.
1707  * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1708  * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1709  */
1710 function url_get_contents( $uri ) {
1711     if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1712         return @file_get_contents($uri);
1713     } else {
1714         require_once("lib/HttpClient.php");
1715         $bits = parse_url($uri);
1716         $host = $bits['host'];
1717         $port = isset($bits['port']) ? $bits['port'] : 80;
1718         $path = isset($bits['path']) ? $bits['path'] : '/';
1719         if (isset($bits['query'])) {
1720             $path .= '?'.$bits['query'];
1721         }
1722         $client = new HttpClient($host, $port);
1723         $client->use_gzip = false;
1724         if (!$client->get($path)) {
1725             return false;
1726         } else {
1727             return $client->getContent();
1728         }
1729     }
1730 }
1731
1732 /**
1733  * Generate consecutively named strings:
1734  *   Name, Name2, Name3, ...
1735  */
1736 function GenerateId($name) {
1737     static $ids = array();
1738     if (empty($ids[$name])) {
1739         $ids[$name] = 1;
1740         return $name;
1741     } else {
1742         $ids[$name]++;
1743         return $name . $ids[$name];
1744     }
1745 }
1746
1747 // from IncludePage. To be of general use.
1748 // content: string or array of strings
1749 function firstNWordsOfContent( $n, $content ) {
1750     if ($content and $n > 0) {
1751         if (is_array($content)) {
1752             // fixme: return a list of lines then?
1753             $content = join("\n", $content);
1754             $return_array = true;
1755             $wordcount = 0;
1756             foreach ($content as $line) {
1757                 $words = explode(' ', $line);
1758                 if ($wordcount + count($words) > $n) {
1759                     $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1760                            . sprintf(_("... (first %s words)"), $n);
1761                     return $new;
1762                 } else {
1763                     $wordcount += count($words);
1764                     $new[] = $line;
1765                 }
1766             }
1767             return $new;
1768         } else {
1769             // fixme: use better whitespace/word seperators
1770             $words = explode(' ', $content);
1771             if (count($words) > $n) {
1772                 return join(' ', array_slice($words, 0, $n))
1773                        . sprintf(_("... (first %s words)"), $n);
1774             } else {
1775                 return $content;
1776             }
1777         }
1778     } else {
1779         return '';
1780     }
1781 }
1782
1783 // moved from lib/plugin/IncludePage.php
1784 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1785     $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1786
1787     if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
1788                    . "  \\s*$\\n?"           // possible blank lines
1789                    . "  ( (?: ^.*\\n? )*? )" // some lines
1790                    . "  (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1791                    implode("\n", $content),
1792                    $match)) {
1793         // Strip trailing blanks lines and ---- <hr>s
1794         $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1795         if ($sectionhead)
1796             $text = $match[1] . $section ."\n". $text;
1797         return explode("\n", $text);
1798     }
1799     if ($quiet)
1800         $mesg = $page ." ". $section;
1801     else
1802         $mesg = $section;
1803     return array(sprintf(_("<%s: no such section>"), $mesg));
1804 }
1805
1806 // use this faster version: only load ExternalReferrer if we came from an external referrer
1807 function isExternalReferrer(&$request) {
1808     if ($referrer = $request->get('HTTP_REFERER')) {
1809         $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
1810         if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
1811         require_once("lib/ExternalReferrer.php");
1812         $se = new SearchEngines();
1813         return $se->parseSearchQuery($referrer);
1814     }
1815     return false;
1816 }
1817
1818 /**
1819  * useful for PECL overrides: cvsclient, ldap, soap.
1820  */
1821 function loadPhpExtension($extension) {
1822     if (!extension_loaded($extension)) {
1823         $soname = (isWindows() ? 'php_' : '') . $extension . (isWindows() ? '.dll' : '.so');
1824         if (!@dl($soname))
1825             return false;
1826     }
1827     return extension_loaded($extension);
1828 }
1829
1830 function string_starts_with($string, $prefix) {
1831     return (substr($string, 0, strlen($prefix)) == $prefix);
1832 }
1833
1834 /** 
1835  * Ensure that the script will have another $secs time left. 
1836  * Works only if safe_mode is off.
1837  * For example not to timeout on waiting socket connections.
1838  *   Use the socket timeout as arg.
1839  */
1840 function longer_timeout($secs = 30) {
1841     $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
1842     $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
1843     if ($timeleft < $secs)
1844         @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
1845 }
1846
1847 function printSimpleTrace($bt) {
1848     //print_r($bt);
1849     echo "Traceback:\n";
1850     foreach ($bt as $i => $elem) {
1851         if (!array_key_exists('file', $elem)) {
1852             continue;
1853         }
1854         echo join(" ",array_values($elem)),"\n";
1855         //print "  " . $elem['file'] . ':' . $elem['line'] . " " .$elem['function']"\n";
1856     }
1857 }
1858
1859 // $Log: not supported by cvs2svn $
1860 // Revision 1.226  2004/12/26 17:12:06  rurban
1861 // avoid stdargs in url, php5 fixes
1862 //
1863 // Revision 1.225  2004/12/22 19:02:29  rurban
1864 // fix glob for starting * or ?
1865 //
1866 // Revision 1.224  2004/12/20 12:11:50  rurban
1867 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
1868 //   not reproducable other than on sf.net, but this seems to fix it.
1869 //
1870 // Revision 1.223  2004/12/18 16:49:29  rurban
1871 // fix RPC for !USE_PATH_INFO, add debugging helper
1872 //
1873 // Revision 1.222  2004/12/17 16:40:45  rurban
1874 // add not yet used url helper
1875 //
1876 // Revision 1.221  2004/12/06 19:49:58  rurban
1877 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
1878 // renamed delete_page to purge_page.
1879 // enable action=edit&version=-1 to force creation of a new version.
1880 // added BABYCART_PATH config
1881 // fixed magiqc in adodb.inc.php
1882 // and some more docs
1883 //
1884 // Revision 1.220  2004/11/30 17:47:41  rurban
1885 // added mt_srand, check for native isa
1886 //
1887 // Revision 1.219  2004/11/26 18:39:02  rurban
1888 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1889 //
1890 // Revision 1.218  2004/11/25 08:28:48  rurban
1891 // support exclude
1892 //
1893 // Revision 1.217  2004/11/16 17:31:03  rurban
1894 // re-enable old block markup conversion
1895 //
1896 // Revision 1.216  2004/11/11 18:31:26  rurban
1897 // add simple backtrace on such general failures to get at least an idea where
1898 //
1899 // Revision 1.215  2004/11/11 14:34:12  rurban
1900 // minor clarifications
1901 //
1902 // Revision 1.214  2004/11/11 11:01:20  rurban
1903 // fix loadPhpExtension
1904 //
1905 // Revision 1.213  2004/11/01 10:43:57  rurban
1906 // seperate PassUser methods into seperate dir (memory usage)
1907 // fix WikiUser (old) overlarge data session
1908 // remove wikidb arg from various page class methods, use global ->_dbi instead
1909 // ...
1910 //
1911 // Revision 1.212  2004/10/22 09:15:39  rurban
1912 // Alert::show has no arg anymore
1913 //
1914 // Revision 1.211  2004/10/22 09:05:11  rurban
1915 // added longer_timeout (HttpClient)
1916 // fixed warning
1917 //
1918 // Revision 1.210  2004/10/14 21:06:02  rurban
1919 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
1920 //
1921 // Revision 1.209  2004/10/14 19:19:34  rurban
1922 // loadsave: check if the dumped file will be accessible from outside.
1923 // and some other minor fixes. (cvsclient native not yet ready)
1924 //
1925 // Revision 1.208  2004/10/12 13:13:20  rurban
1926 // php5 compatibility (5.0.1 ok)
1927 //
1928 // Revision 1.207  2004/09/26 12:21:40  rurban
1929 // removed old log entries.
1930 // added persistent start_debug on internal links and DEBUG
1931 // added isExternalReferrer (not yet used)
1932 //
1933 // Revision 1.206  2004/09/25 16:28:36  rurban
1934 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
1935 //
1936 // Revision 1.205  2004/09/23 13:59:35  rurban
1937 // Before removing a page display a sample of 100 words.
1938 //
1939 // Revision 1.204  2004/09/17 13:19:15  rurban
1940 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
1941 // by SteveBennett.
1942 //
1943 // Revision 1.203  2004/09/16 08:00:52  rurban
1944 // just some comments
1945 //
1946 // Revision 1.202  2004/09/14 10:11:44  rurban
1947 // start 2nd Id with ...Plugin2
1948 //
1949 // Revision 1.201  2004/09/14 10:06:42  rurban
1950 // generate iterated plugin ids, set plugin span id also
1951 //
1952 // Revision 1.200  2004/08/05 17:34:26  rurban
1953 // move require to sortby branch
1954 //
1955 // Revision 1.199  2004/08/05 10:38:15  rurban
1956 // fix Bug #993692:  Making Snapshots or Backups doesn't work anymore
1957 // in CVS version.
1958 //
1959 // Revision 1.198  2004/07/02 10:30:36  rurban
1960 // always disable getimagesize for < php-4.3 with external png's
1961 //
1962 // Revision 1.197  2004/07/02 09:55:58  rurban
1963 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
1964 //
1965 // Revision 1.196  2004/07/01 08:51:22  rurban
1966 // dumphtml: added exclude, print pagename before processing
1967 //
1968 // Revision 1.195  2004/06/29 08:52:22  rurban
1969 // Use ...version() $need_content argument in WikiDB also:
1970 // To reduce the memory footprint for larger sets of pagelists,
1971 // we don't cache the content (only true or false) and
1972 // we purge the pagedata (_cached_html) also.
1973 // _cached_html is only cached for the current pagename.
1974 // => Vastly improved page existance check, ACL check, ...
1975 //
1976 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1977 //
1978 // Revision 1.194  2004/06/29 06:48:04  rurban
1979 // Improve LDAP auth and GROUP_LDAP membership:
1980 //   no error message on false password,
1981 //   added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
1982 //   fixed two group queries (this -> user)
1983 // stdlib: ConvertOldMarkup still flawed
1984 //
1985 // Revision 1.193  2004/06/28 13:27:03  rurban
1986 // CreateToc disabled for old markup and Apache2 only
1987 //
1988 // Revision 1.192  2004/06/28 12:47:43  rurban
1989 // skip if non-DEBUG and old markup with CreateToc
1990 //
1991 // Revision 1.191  2004/06/25 14:31:56  rurban
1992 // avoid debug_skip warning
1993 //
1994 // Revision 1.190  2004/06/25 14:29:20  rurban
1995 // WikiGroup refactoring:
1996 //   global group attached to user, code for not_current user.
1997 //   improved helpers for special groups (avoid double invocations)
1998 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1999 // fixed a XHTML validation error on userprefs.tmpl
2000 //
2001 // Revision 1.189  2004/06/20 09:45:35  rurban
2002 // php5 isa fix (wrong strtolower)
2003 //
2004 // Revision 1.188  2004/06/16 10:38:58  rurban
2005 // Disallow refernces in calls if the declaration is a reference
2006 // ("allow_call_time_pass_reference clean").
2007 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
2008 //   but several external libraries may not.
2009 //   In detail these libs look to be affected (not tested):
2010 //   * Pear_DB odbc
2011 //   * adodb oracle
2012 //
2013 // Revision 1.187  2004/06/14 11:31:37  rurban
2014 // renamed global $Theme to $WikiTheme (gforge nameclash)
2015 // inherit PageList default options from PageList
2016 //   default sortby=pagename
2017 // use options in PageList_Selectable (limit, sortby, ...)
2018 // added action revert, with button at action=diff
2019 // added option regex to WikiAdminSearchReplace
2020 //
2021 // Revision 1.186  2004/06/13 13:54:25  rurban
2022 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2023 // FoafViewer: Check against external requirements, instead of fatal.
2024 // Change output for xhtmldumps: using file:// urls to the local fs.
2025 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2026 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2027 //
2028 // Revision 1.185  2004/06/11 09:07:30  rurban
2029 // support theme-specific LinkIconAttr: front or after or none
2030 //
2031 // Revision 1.184  2004/06/04 20:32:53  rurban
2032 // Several locale related improvements suggested by Pierrick Meignen
2033 // LDAP fix by John Cole
2034 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2035 //
2036 // Revision 1.183  2004/06/01 10:22:56  rurban
2037 // added url_get_contents() used in XmlParser and elsewhere
2038 //
2039 // Revision 1.182  2004/05/25 12:40:48  rurban
2040 // trim the pagename
2041 //
2042 // Revision 1.181  2004/05/25 10:18:44  rurban
2043 // Check for UTF-8 URLs; Internet Explorer produces these if you
2044 // type non-ASCII chars in the URL bar or follow unescaped links.
2045 // Fixes sf.net bug #953949
2046 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2047 //
2048 // Revision 1.180  2004/05/18 16:23:39  rurban
2049 // rename split_pagename to SplitPagename
2050 //
2051 // Revision 1.179  2004/05/18 16:18:37  rurban
2052 // AutoSplit at subpage seperators
2053 // RssFeed stability fix for empty feeds or broken connections
2054 //
2055 // Revision 1.178  2004/05/12 10:49:55  rurban
2056 // require_once fix for those libs which are loaded before FileFinder and
2057 //   its automatic include_path fix, and where require_once doesn't grok
2058 //   dirname(__FILE__) != './lib'
2059 // upgrade fix with PearDB
2060 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2061 //
2062 // Revision 1.177  2004/05/08 14:06:12  rurban
2063 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2064 // minor stability and portability fixes
2065 //
2066 // Revision 1.176  2004/05/08 11:25:15  rurban
2067 // php-4.0.4 fixes
2068 //
2069 // Revision 1.175  2004/05/06 17:30:38  rurban
2070 // CategoryGroup: oops, dos2unix eol
2071 // improved phpwiki_version:
2072 //   pre -= .0001 (1.3.10pre: 1030.099)
2073 //   -p1 += .001 (1.3.9-p1: 1030.091)
2074 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2075 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2076 //   backend->backendType(), backend->database(),
2077 //   backend->listOfFields(),
2078 //   backend->listOfTables(),
2079 //
2080 // Revision 1.174  2004/05/06 12:02:05  rurban
2081 // fix sf.net bug#949002: [ Link | ] assertion
2082 //
2083 // Revision 1.173  2004/05/03 15:00:31  rurban
2084 // added more database upgrading: session.sess_ip, page.id autp_increment
2085 //
2086 // Revision 1.172  2004/04/26 20:44:34  rurban
2087 // locking table specific for better databases
2088 //
2089 // Revision 1.171  2004/04/19 23:13:03  zorloc
2090 // Connect the rest of PhpWiki to the IniConfig system.  Also the keyword regular expression is not a config setting
2091 //
2092 // Revision 1.170  2004/04/19 18:27:45  rurban
2093 // Prevent from some PHP5 warnings (ref args, no :: object init)
2094 //   php5 runs now through, just one wrong XmlElement object init missing
2095 // Removed unneccesary UpgradeUser lines
2096 // Changed WikiLink to omit version if current (RecentChanges)
2097 //
2098 // Revision 1.169  2004/04/15 21:29:48  rurban
2099 // allow [0] with new markup: link to page "0"
2100 //
2101 // Revision 1.168  2004/04/10 02:30:49  rurban
2102 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2103 // Fixed "cannot setlocale..." (sf.net problem)
2104 //
2105 // Revision 1.167  2004/04/02 15:06:55  rurban
2106 // fixed a nasty ADODB_mysql session update bug
2107 // improved UserPreferences layout (tabled hints)
2108 // fixed UserPreferences auth handling
2109 // improved auth stability
2110 // improved old cookie handling: fixed deletion of old cookies with paths
2111 //
2112 // Revision 1.166  2004/04/01 15:57:10  rurban
2113 // simplified Sidebar theme: table, not absolute css positioning
2114 // added the new box methods.
2115 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2116 //
2117 // Revision 1.165  2004/03/24 19:39:03  rurban
2118 // php5 workaround code (plus some interim debugging code in XmlElement)
2119 //   php5 doesn't work yet with the current XmlElement class constructors,
2120 //   WikiUserNew does work better than php4.
2121 // rewrote WikiUserNew user upgrading to ease php5 update
2122 // fixed pref handling in WikiUserNew
2123 // added Email Notification
2124 // added simple Email verification
2125 // removed emailVerify userpref subclass: just a email property
2126 // changed pref binary storage layout: numarray => hash of non default values
2127 // print optimize message only if really done.
2128 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2129 //   prefs should be stored in db or homepage, besides the current session.
2130 //
2131 // Revision 1.164  2004/03/18 21:41:09  rurban
2132 // fixed sqlite support
2133 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2134 //
2135 // Revision 1.163  2004/03/17 18:41:49  rurban
2136 // just reformatting
2137 //
2138 // Revision 1.162  2004/03/16 15:43:08  rurban
2139 // make fileSet sortable to please PageList
2140 //
2141 // Revision 1.161  2004/03/12 15:48:07  rurban
2142 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2143 // simplified lib/stdlib.php:explodePageList
2144 //
2145 // Revision 1.160  2004/02/28 21:14:08  rurban
2146 // generally more PHPDOC docs
2147 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2148 // fxied WikiUserNew pref handling: empty theme not stored, save only
2149 //   changed prefs, sql prefs improved, fixed password update,
2150 //   removed REPLACE sql (dangerous)
2151 // moved gettext init after the locale was guessed
2152 // + some minor changes
2153 //
2154
2155 // (c-file-style: "gnu")
2156 // Local Variables:
2157 // mode: php
2158 // tab-width: 8
2159 // c-basic-offset: 4
2160 // c-hanging-comment-ender-p: nil
2161 // indent-tabs-mode: nil
2162 // End:   
2163 ?>