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