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