]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
AutoSplit at subpage seperators
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.179 2004-05-18 16:18:37 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     split_pagename ($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 $Theme;
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 = $Theme->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 text.
196  *
197  * @param string $protocol_or_url Protocol or URL.  Used to determine the
198  * proper icon.
199  * @param string $text The text.
200  * @return XmlContent.
201  */
202 function PossiblyGlueIconToText($proto_or_url, $text) {
203     global $request;
204     if (! $request->getPref('noLinkIcons')) {
205         $icon = IconForLink($proto_or_url);
206         if ($icon) {
207             if (!is_object($text)) {
208                 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
209                 list (, $first_word, $tail) = $m;
210             }
211             else {
212                 $first_word = $text;
213                 $tail = false;
214             }
215             
216             $text = HTML::span(array('style' => 'white-space: nowrap'),
217                                $icon, $first_word);
218             if ($tail)
219                 $text = HTML($text, $tail);
220         }
221     }
222     return $text;
223 }
224
225 /**
226  * Determines if the url passed to function is safe, by detecting if the characters
227  * '<', '>', or '"' are present.
228  *
229  * @param string $url URL to check for unsafe characters.
230  * @return boolean True if same, false else.
231  */
232 function IsSafeURL($url) {
233     return !ereg('[<>"]', $url);
234 }
235
236 /**
237  * Generates an HtmlElement object to store data for a link.
238  *
239  * @param string $url URL that the link will point to.
240  * @param string $linktext Text to be displayed as link.
241  * @return HtmlElement HtmlElement object that contains data to construct an html link.
242  */
243 function LinkURL($url, $linktext = '') {
244     // FIXME: Is this needed (or sufficient?)
245     if(! IsSafeURL($url)) {
246         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
247                                      _("BAD URL -- remove all of <, >, \"")));
248     }
249     else {
250         if (!$linktext)
251             $linktext = preg_replace("/mailto:/A", "", $url);
252         
253         $link = HTML::a(array('href' => $url),
254                         PossiblyGlueIconToText($url, $linktext));
255         
256     }
257     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
258     return $link;
259 }
260
261
262 function LinkImage($url, $alt = false) {
263     // FIXME: Is this needed (or sufficient?)
264     if(! IsSafeURL($url)) {
265         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
266                                      _("BAD URL -- remove all of <, >, \"")));
267     } else {
268         // support new syntax: [image.jpg size=50% border=n]
269         $arr = split(' ',$url);
270         if (count($arr) > 1) {
271             $url = $arr[0];
272         }
273         if (empty($alt)) $alt = basename($url);
274         $link = HTML::img(array('src' => $url, 'alt' => $alt));
275         if (count($arr) > 1) {
276             array_shift($arr);
277             foreach ($arr as $attr) {
278                 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
279                     $link->setAttr('width',$m[1]);
280                     $link->setAttr('height',$m[1]);
281                 }
282                 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
283                     $link->setAttr('width',$m[1]);
284                     $link->setAttr('height',$m[2]);
285                 }
286                 if (preg_match('/^border=(\d+)$/',$attr,$m))
287                     $link->setAttr('border',$m[1]);
288                 if (preg_match('/^align=(\w+)$/',$attr,$m))
289                     $link->setAttr('align',$m[1]);
290                 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
291                     $link->setAttr('hspace',$m[1]);
292                 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
293                     $link->setAttr('vspace',$m[1]);
294             }
295         }
296     }
297     $link->setAttr('class', 'inlineimage');
298     return $link;
299 }
300
301
302
303 class Stack {
304     var $items = array();
305     var $size = 0;
306     // var in php5.0.0.rc1 deprecated
307
308     function push($item) {
309         $this->items[$this->size] = $item;
310         $this->size++;
311         return true;
312     }  
313     
314     function pop() {
315         if ($this->size == 0) {
316             return false; // stack is empty
317         }  
318         $this->size--;
319         return $this->items[$this->size];
320     }  
321     
322     function cnt() {
323         return $this->size;
324     }  
325     
326     function top() {
327         if($this->size)
328             return $this->items[$this->size - 1];
329         else
330             return '';
331     }
332     
333 }  
334 // end class definition
335
336 function SplitQueryArgs ($query_args = '') 
337 {
338     $split_args = split('&', $query_args);
339     $args = array();
340     while (list($key, $val) = each($split_args))
341         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
342             $args[$m[1]] = $m[2];
343     return $args;
344 }
345
346 function LinkPhpwikiURL($url, $text = '', $basepage) {
347     $args = array();
348     
349     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
350         return HTML::strong(array('class' => 'rawurl'),
351                             HTML::u(array('class' => 'baduri'),
352                                     _("BAD phpwiki: URL")));
353     }
354
355     if ($m[1])
356         $pagename = urldecode($m[1]);
357     $qargs = $m[2];
358     
359     if (empty($pagename) &&
360         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
361         // Convert old style links (to not break diff links in
362         // RecentChanges).
363         $pagename = urldecode($m[2]);
364         $args = array("action" => $m[1]);
365     }
366     else {
367         $args = SplitQueryArgs($qargs);
368     }
369
370     if (empty($pagename))
371         $pagename = $GLOBALS['request']->getArg('pagename');
372
373     if (isset($args['action']) && $args['action'] == 'browse')
374         unset($args['action']);
375     
376     /*FIXME:
377       if (empty($args['action']))
378       $class = 'wikilink';
379       else if (is_safe_action($args['action']))
380       $class = 'wikiaction';
381     */
382     if (empty($args['action']) || is_safe_action($args['action']))
383         $class = 'wikiaction';
384     else {
385         // Don't allow administrative links on unlocked pages.
386         $dbi = $GLOBALS['request']->getDbh();
387         $page = $dbi->getPage($basepage);
388         if (!$page->get('locked'))
389             return HTML::span(array('class' => 'wikiunsafe'),
390                               HTML::u(_("Lock page to enable link")));
391         $class = 'wikiadmin';
392     }
393     
394     if (!$text)
395         $text = HTML::span(array('class' => 'rawurl'), $url);
396
397     $wikipage = new WikiPageName($pagename);
398     if (!$wikipage->isValid()) {
399         global $Theme;
400         return $Theme->linkBadWikiWord($wikipage, $url);
401     }
402     
403     return HTML::a(array('href'  => WikiURL($pagename, $args),
404                          'class' => $class),
405                    $text);
406 }
407
408 /**
409  * A class to assist in parsing wiki pagenames.
410  *
411  * Now with subpages and anchors, parsing and passing around
412  * pagenames is more complicated.  This should help.
413  */
414 class WikiPageName
415 {
416     /** Short name for page.
417      *
418      * This is the value of $name passed to the constructor.
419      * (For use, e.g. as a default label for links to the page.)
420      */
421     var $shortName;
422
423     /** The full page name.
424      *
425      * This is the full name of the page (without anchor).
426      */
427     var $name;
428     
429     /** The anchor.
430      *
431      * This is the referenced anchor within the page, or the empty string.
432      */
433     var $anchor;
434     
435     /** Constructor
436      *
437      * @param mixed $name Page name.
438      * WikiDB_Page, WikiDB_PageRevision, or string.
439      * This can be a relative subpage name (like '/SubPage'),
440      * or can be the empty string to refer to the $basename.
441      *
442      * @param string $anchor For links to anchors in page.
443      *
444      * @param mixed $basename Page name from which to interpret
445      * relative or other non-fully-specified page names.
446      */
447     function WikiPageName($name, $basename=false, $anchor=false) {
448         if (is_string($name)) {
449             $this->shortName = $name;
450         
451             if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
452                 if ($basename)
453                     $name = $this->_pagename($basename) . $name;
454                 else
455                     $name = $this->_normalize_bad_pagename($name);
456             }
457         }
458         else {
459             $name = $this->_pagename($name);
460             $this->shortName = $name;
461         }
462
463         $this->name = $this->_check($name);
464         $this->anchor = (string)$anchor;
465     }
466
467     function getParent() {
468         $name = $this->name;
469         if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
470             return false;
471         return substr($name, 0, -strlen($tail));
472     }
473
474     function isValid($strict = false) {
475         if ($strict)
476             return !isset($this->_errors);
477         return (is_string($this->name) and $this->name != '');
478     }
479
480     function getWarnings() {
481         $warnings = array();
482         if (isset($this->_warnings))
483             $warnings = array_merge($warnings, $this->_warnings);
484         if (isset($this->_errors))
485             $warnings = array_merge($warnings, $this->_errors);
486         if (!$warnings)
487             return false;
488         
489         return sprintf(_("'%s': Bad page name: %s"),
490                        $this->shortName, join(', ', $warnings));
491     }
492     
493     function _pagename($page) {
494         if (isa($page, 'WikiDB_Page'))
495             return $page->getName();
496         elseif (isa($page, 'WikiDB_PageRevision'))
497             return $page->getPageName();
498         elseif (isa($page, 'WikiPageName'))
499             return $page->name;
500         if (!is_string($page)) {
501             trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
502                                   $page, gettype($page), get_class($page)),
503                           E_USER_NOTICE);
504         }
505         //assert(is_string($page));
506         return $page;
507     }
508
509     function _normalize_bad_pagename($name) {
510         trigger_error("Bad pagename: " . $name, E_USER_WARNING);
511
512         // Punt...  You really shouldn't get here.
513         if (empty($name)) {
514             global $request;
515             return $request->getArg('pagename');
516         }
517         assert($name[0] == SUBPAGE_SEPARATOR);
518         return substr($name, 1);
519     }
520
521
522     function _check($pagename) {
523         // Compress internal white-space to single space character.
524         $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
525         if ($pagename != $orig)
526             $this->_warnings[] = _("White space converted to single space");
527     
528         // Delete any control characters.
529         $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
530         if ($pagename != $orig)
531             $this->_errors[] = _("Control characters not allowed");
532
533         // Strip leading and trailing white-space.
534         $pagename = trim($pagename);
535
536         $orig = $pagename;
537         while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
538             $pagename = substr($pagename, 1);
539         if ($pagename != $orig)
540             $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
541
542         if (preg_match('/[:;]/', $pagename))
543             $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
544         
545         if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
546             $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
547             $this->_errors[] = _("too long");
548         }
549         
550
551         if ($pagename == '.' or $pagename == '..') {
552             $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
553             $pagename = '';
554         }
555         
556         return $pagename;
557     }
558 }
559
560 /**
561  * Convert old page markup to new-style markup.
562  *
563  * @param string $text Old-style wiki markup.
564  *
565  * @param string $markup_type
566  * One of: <dl>
567  * <dt><code>"block"</code>  <dd>Convert all markup.
568  * <dt><code>"inline"</code> <dd>Convert only inline markup.
569  * <dt><code>"links"</code>  <dd>Convert only link markup.
570  * </dl>
571  *
572  * @return string New-style wiki markup.
573  *
574  * @bugs Footnotes don't work quite as before (esp if there are
575  *   multiple references to the same footnote.  But close enough,
576  *   probably for now....
577  */
578 function ConvertOldMarkup ($text, $markup_type = "block") {
579
580     static $subs;
581     static $block_re;
582     
583     if (empty($subs)) {
584         /*****************************************************************
585          * Conversions for inline markup:
586          */
587
588         // escape tilde's
589         $orig[] = '/~/';
590         $repl[] = '~~';
591
592         // escape escaped brackets
593         $orig[] = '/\[\[/';
594         $repl[] = '~[';
595
596         // change ! escapes to ~'s.
597         global $WikiNameRegexp, $request;
598         //include_once('lib/interwiki.php');
599         $map = getInterwikiMap();
600         $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
601         $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
602         $bang_esc[] = $WikiNameRegexp;
603         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
604         $repl[] = '~\\1';
605
606         $subs["links"] = array($orig, $repl);
607
608         // Escape '<'s
609         //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
610         //$repl[] = '~<';
611         
612         // Convert footnote references.
613         $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
614         $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
615
616         // Convert old style emphases to HTML style emphasis.
617         $orig[] = '/__(.*?)__/';
618         $repl[] = '<strong>\\1</strong>';
619         $orig[] = "/''(.*?)''/";
620         $repl[] = '<em>\\1</em>';
621
622         // Escape nestled markup.
623         $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
624         $repl[] = '~\\0';
625         
626         // in old markup headings only allowed at beginning of line
627         $orig[] = '/!/';
628         $repl[] = '~!';
629
630         $subs["inline"] = array($orig, $repl);
631
632         /*****************************************************************
633          * Patterns which match block markup constructs which take
634          * special handling...
635          */
636
637         // Indented blocks
638         $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
639
640         // Tables
641         $blockpats[] = '\|(?:.*\n\|)*';
642
643         // List items
644         $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
645
646         // Footnote definitions
647         $blockpats[] = '\[\s*(\d+)\s*\]';
648
649         // Plugins
650         $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
651
652         // Section Title
653         $blockpats[] = '!{1,3}[^!]';
654
655         $block_re = ( '/\A((?:.|\n)*?)(^(?:'
656                       . join("|", $blockpats)
657                       . ').*$)\n?/m' );
658         
659     }
660     
661     if ($markup_type != "block") {
662         list ($orig, $repl) = $subs[$markup_type];
663         return preg_replace($orig, $repl, $text);
664     }
665     else {
666         list ($orig, $repl) = $subs['inline'];
667         $out = '';
668         while (preg_match($block_re, $text, $m)) {
669             $text = substr($text, strlen($m[0]));
670             list (,$leading_text, $block) = $m;
671             $suffix = "\n";
672             
673             if (strchr(" \t", $block[0])) {
674                 // Indented block
675                 $prefix = "<pre>\n";
676                 $suffix = "\n</pre>\n";
677             }
678             elseif ($block[0] == '|') {
679                 // Old-style table
680                 $prefix = "<?plugin OldStyleTable\n";
681                 $suffix = "\n?>\n";
682             }
683             elseif (strchr("#*;", $block[0])) {
684                 // Old-style list item
685                 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
686                 list (,$ind,$bullet) = $m;
687                 $block = substr($block, strlen($m[0]));
688                 
689                 $indent = str_repeat('     ', strlen($ind));
690                 if ($bullet[0] == ';') {
691                     //$term = ltrim(substr($bullet, 1));
692                     //return $indent . $term . "\n" . $indent . '     ';
693                     $prefix = $ind . $bullet;
694                 }
695                 else
696                     $prefix = $indent . $bullet . ' ';
697             }
698             elseif ($block[0] == '[') {
699                 // Footnote definition
700                 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
701                 $footnum = $m[1];
702                 $block = substr($block, strlen($m[0]));
703                 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
704             }
705             elseif ($block[0] == '<') {
706                 // Plugin.
707                 // HACK: no inline markup...
708                 $prefix = $block;
709                 $block = '';
710             }
711             elseif ($block[0] == '!') {
712                 // Section heading
713                 preg_match('/^!{1,3}/', $block, $m);
714                 $prefix = $m[0];
715                 $block = substr($block, strlen($m[0]));
716             }
717             else {
718                 // AAck!
719                 assert(0);
720             }
721
722             $out .= ( preg_replace($orig, $repl, $leading_text)
723                       . $prefix
724                       . preg_replace($orig, $repl, $block)
725                       . $suffix );
726         }
727         return $out . preg_replace($orig, $repl, $text);
728     }
729 }
730
731
732 /**
733  * Expand tabs in string.
734  *
735  * Converts all tabs to (the appropriate number of) spaces.
736  *
737  * @param string $str
738  * @param integer $tab_width
739  * @return string
740  */
741 function expand_tabs($str, $tab_width = 8) {
742     $split = split("\t", $str);
743     $tail = array_pop($split);
744     $expanded = "\n";
745     foreach ($split as $hunk) {
746         $expanded .= $hunk;
747         $pos = strlen(strrchr($expanded, "\n")) - 1;
748         $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
749     }
750     return substr($expanded, 1) . $tail;
751 }
752
753 /**
754  * Split WikiWords in page names.
755  *
756  * It has been deemed useful to split WikiWords (into "Wiki Words") in
757  * places like page titles. This is rumored to help search engines
758  * quite a bit.
759  *
760  * @param $page string The page name.
761  *
762  * @return string The split name.
763  */
764 function split_pagename ($page) {
765     
766     if (preg_match("/\s/", $page))
767         return $page;           // Already split --- don't split any more.
768     
769     // FIXME: this algorithm is Anglo-centric.
770     static $RE;
771     if (!isset($RE)) {
772         // This mess splits between a lower-case letter followed by
773         // either an upper-case or a numeral; except that it wont
774         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
775         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
776         // This the single-letter words 'I' and 'A' from any following
777         // capitalized words.
778         $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
779         $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
780         // Split numerals from following letters.
781         $RE[] = '/(\d)([[:alpha:]])/';
782         // Split at subpage seperators. TBD in Theme.php
783         $RE[] = "/([^${sep}]+)(${sep})/";
784         
785         foreach ($RE as $key)
786             $RE[$key] = pcre_fix_posix_classes($key);
787     }
788
789     foreach ($RE as $regexp) {
790         $page = preg_replace($regexp, '\\1 \\2', $page);
791     }
792     return $page;
793 }
794
795 function NoSuchRevision (&$request, $page, $version) {
796     $html = HTML(HTML::h2(_("Revision Not Found")),
797                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
798                              $version, WikiLink($page, 'auto'))));
799     include_once('lib/Template.php');
800     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
801     $request->finish();
802 }
803
804
805 /**
806  * Get time offset for local time zone.
807  *
808  * @param $time time_t Get offset for this time. Default: now.
809  * @param $no_colon boolean Don't put colon between hours and minutes.
810  * @return string Offset as a string in the format +HH:MM.
811  */
812 function TimezoneOffset ($time = false, $no_colon = false) {
813     if ($time === false)
814         $time = time();
815     $secs = date('Z', $time);
816
817     if ($secs < 0) {
818         $sign = '-';
819         $secs = -$secs;
820     }
821     else {
822         $sign = '+';
823     }
824     $colon = $no_colon ? '' : ':';
825     $mins = intval(($secs + 30) / 60);
826     return sprintf("%s%02d%s%02d",
827                    $sign, $mins / 60, $colon, $mins % 60);
828 }
829
830
831 /**
832  * Format time in ISO-8601 format.
833  *
834  * @param $time time_t Time.  Default: now.
835  * @return string Date and time in ISO-8601 format.
836  */
837 function Iso8601DateTime ($time = false) {
838     if ($time === false)
839         $time = time();
840     $tzoff = TimezoneOffset($time);
841     $date  = date('Y-m-d', $time);
842     $time  = date('H:i:s', $time);
843     return $date . 'T' . $time . $tzoff;
844 }
845
846 /**
847  * Format time in RFC-2822 format.
848  *
849  * @param $time time_t Time.  Default: now.
850  * @return string Date and time in RFC-2822 format.
851  */
852 function Rfc2822DateTime ($time = false) {
853     if ($time === false)
854         $time = time();
855     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
856 }
857
858 /**
859  * Format time in RFC-1123 format.
860  *
861  * @param $time time_t Time.  Default: now.
862  * @return string Date and time in RFC-1123 format.
863  */
864 function Rfc1123DateTime ($time = false) {
865     if ($time === false)
866         $time = time();
867     return gmdate('D, d M Y H:i:s \G\M\T', $time);
868 }
869
870 /** Parse date in RFC-1123 format.
871  *
872  * According to RFC 1123 we must accept dates in the following
873  * formats:
874  *
875  *   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
876  *   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
877  *   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
878  *
879  * (Though we're only allowed to generate dates in the first format.)
880  */
881 function ParseRfc1123DateTime ($timestr) {
882     $timestr = trim($timestr);
883     if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
884                    .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
885                    $timestr, $m)) {
886         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
887     }
888     elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
889                        .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
890                        $timestr, $m)) {
891         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
892         if ($year < 70) $year += 2000;
893         elseif ($year < 100) $year += 1900;
894     }
895     elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
896                        .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
897                        $timestr, $m)) {
898         list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
899     }
900     else {
901         // Parse failed.
902         return false;
903     }
904
905     $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
906     if ($time == -1)
907         return false;           // failed
908     return $time;
909 }
910
911 /**
912  * Format time to standard 'ctime' format.
913  *
914  * @param $time time_t Time.  Default: now.
915  * @return string Date and time.
916  */
917 function CTime ($time = false)
918 {
919     if ($time === false)
920         $time = time();
921     return date("D M j H:i:s Y", $time);
922 }
923
924
925 /**
926  * Format number as kilobytes or bytes.
927  * Short format is used for PageList
928  * Long format is used in PageInfo
929  *
930  * @param $bytes       int.  Default: 0.
931  * @param $longformat  bool. Default: false.
932  * @return class FormattedText (XmlElement.php).
933  */
934 function ByteFormatter ($bytes = 0, $longformat = false) {
935     if ($bytes < 0)
936         return fmt("-???");
937     if ($bytes < 1024) {
938         if (! $longformat)
939             $size = fmt("%s b", $bytes);
940         else
941             $size = fmt("%s bytes", $bytes);
942     }
943     else {
944         $kb = round($bytes / 1024, 1);
945         if (! $longformat)
946             $size = fmt("%s k", $kb);
947         else
948             $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
949     }
950     return $size;
951 }
952
953 /**
954  * Internationalized printf.
955  *
956  * This is essentially the same as PHP's built-in printf
957  * with the following exceptions:
958  * <ol>
959  * <li> It passes the format string through gettext().
960  * <li> It supports the argument reordering extensions.
961  * </ol>
962  *
963  * Example:
964  *
965  * In php code, use:
966  * <pre>
967  *    __printf("Differences between versions %s and %s of %s",
968  *             $new_link, $old_link, $page_link);
969  * </pre>
970  *
971  * Then in locale/po/de.po, one can reorder the printf arguments:
972  *
973  * <pre>
974  *    msgid "Differences between %s and %s of %s."
975  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
976  * </pre>
977  *
978  * (Note that while PHP tries to expand $vars within double-quotes,
979  * the values in msgstr undergo no such expansion, so the '$'s
980  * okay...)
981  *
982  * One shouldn't use reordered arguments in the default format string.
983  * Backslashes in the default string would be necessary to escape the
984  * '$'s, and they'll cause all kinds of trouble....
985  */ 
986 function __printf ($fmt) {
987     $args = func_get_args();
988     array_shift($args);
989     echo __vsprintf($fmt, $args);
990 }
991
992 /**
993  * Internationalized sprintf.
994  *
995  * This is essentially the same as PHP's built-in printf with the
996  * following exceptions:
997  *
998  * <ol>
999  * <li> It passes the format string through gettext().
1000  * <li> It supports the argument reordering extensions.
1001  * </ol>
1002  *
1003  * @see __printf
1004  */ 
1005 function __sprintf ($fmt) {
1006     $args = func_get_args();
1007     array_shift($args);
1008     return __vsprintf($fmt, $args);
1009 }
1010
1011 /**
1012  * Internationalized vsprintf.
1013  *
1014  * This is essentially the same as PHP's built-in printf with the
1015  * following exceptions:
1016  *
1017  * <ol>
1018  * <li> It passes the format string through gettext().
1019  * <li> It supports the argument reordering extensions.
1020  * </ol>
1021  *
1022  * @see __printf
1023  */ 
1024 function __vsprintf ($fmt, $args) {
1025     $fmt = gettext($fmt);
1026     // PHP's sprintf doesn't support variable with specifiers,
1027     // like sprintf("%*s", 10, "x"); --- so we won't either.
1028     
1029     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1030         // Format string has '%2$s' style argument reordering.
1031         // PHP doesn't support this.
1032         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1033             // literal variable name substitution only to keep locale
1034             // strings uncluttered
1035             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1036                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
1037         
1038         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1039         $newargs = array();
1040         
1041         // Reorder arguments appropriately.
1042         foreach($m[1] as $argnum) {
1043             if ($argnum < 1 || $argnum > count($args))
1044                 trigger_error(sprintf(_("%s: argument index out of range"), 
1045                                       $argnum), E_USER_WARNING);
1046             $newargs[] = $args[$argnum - 1];
1047         }
1048         $args = $newargs;
1049     }
1050     
1051     // Not all PHP's have vsprintf, so...
1052     array_unshift($args, $fmt);
1053     return call_user_func_array('sprintf', $args);
1054 }
1055
1056 function file_mtime ($filename) {
1057     if ($stat = stat($filename))
1058         return $stat[9];
1059     else 
1060         return false;
1061 }
1062
1063 function sort_file_mtime ($a, $b) {
1064     $ma = file_mtime($a);
1065     $mb = file_mtime($b);
1066     if (!$ma or !$mb or $ma == $mb) return 0;
1067     return ($ma > $mb) ? -1 : 1;
1068 }
1069
1070 class fileSet {
1071     /**
1072      * Build an array in $this->_fileList of files from $dirname.
1073      * Subdirectories are not traversed.
1074      *
1075      * (This was a function LoadDir in lib/loadsave.php)
1076      * See also http://www.php.net/manual/en/function.readdir.php
1077      */
1078     function getFiles($exclude=false,$sortby=false,$limit=false) {
1079         $list = $this->_fileList;
1080         if ($sortby) {
1081             switch (Pagelist::sortby($sortby,'db')) {
1082             case 'pagename ASC': break;
1083             case 'pagename DESC': 
1084                 $list = array_reverse($list); 
1085                 break;
1086             case 'mtime ASC': 
1087                 usort($list,'sort_file_mtime'); 
1088                 break;
1089             case 'mtime DESC': 
1090                 usort($list,'sort_file_mtime');
1091                 $list = array_reverse($list); 
1092                 break;
1093             }
1094         }
1095         if ($limit)
1096             return array_splice($list,0,$limit);
1097         return $list;
1098     }
1099
1100     function _filenameSelector($filename) {
1101         if (! $this->_pattern)
1102             return true;
1103         else {
1104             return glob_match ($this->_pattern, $filename, $this->_case);
1105         }
1106     }
1107
1108     function fileSet($directory, $filepattern = false) {
1109         $this->_fileList = array();
1110         $this->_pattern = $filepattern;
1111         $this->_case = !isWindows();
1112         $this->_pathsep = '/';
1113
1114         if (empty($directory)) {
1115             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1116                           E_USER_NOTICE);
1117             return; // early return
1118         }
1119
1120         @ $dir_handle = opendir($dir=$directory);
1121         if (empty($dir_handle)) {
1122             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1123                                   $dir), E_USER_NOTICE);
1124             return; // early return
1125         }
1126
1127         while ($filename = readdir($dir_handle)) {
1128             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1129                 continue;
1130             if ($this->_filenameSelector($filename)) {
1131                 array_push($this->_fileList, "$filename");
1132                 //trigger_error(sprintf(_("found file %s"), $filename),
1133                 //                      E_USER_NOTICE); //debugging
1134             }
1135         }
1136         closedir($dir_handle);
1137     }
1138 };
1139
1140 // File globbing
1141
1142 // expands a list containing regex's to its matching entries
1143 class ListRegexExpand {
1144     var $match, $list, $index, $case_sensitive;
1145     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1146         $this->match = str_replace('/','\/',$match);
1147         $this->list = &$list;
1148         $this->case_sensitive = $case_sensitive;        
1149         //$this->index = false;
1150     }
1151     function listMatchCallback ($item, $key) {
1152         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1153             unset($this->list[$this->index]);
1154             $this->list[] = $item;
1155         }
1156     }
1157     function expandRegex ($index, &$pages) {
1158         $this->index = $index;
1159         array_walk($pages, array($this, 'listMatchCallback'));
1160         return $this->list;
1161     }
1162 }
1163
1164 // convert fileglob to regex style
1165 function glob_to_pcre ($glob) {
1166     $re = preg_replace('/\./', '\\.', $glob);
1167     $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1168     if (!preg_match('/^[\?\*]/',$glob))
1169         $re = '^' . $re;
1170     if (!preg_match('/[\?\*]$/',$glob))
1171         $re = $re . '$';
1172     return $re;
1173 }
1174
1175 function glob_match ($glob, $against, $case_sensitive = true) {
1176     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1177 }
1178
1179 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1180     $list = explode(',',$input);
1181     // expand wildcards from list of $allnames
1182     if (preg_match('/[\?\*]/',$input)) {
1183         // Optimizing loop invariants:
1184         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1185         for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1186             $f = $list[$i];
1187             if (preg_match('/[\?\*]/',$f)) {
1188                 reset($allnames);
1189                 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1190                 $expand->expandRegex($i, $allnames);
1191             }
1192         }
1193     }
1194     return $list;
1195 }
1196
1197 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1198 function explodePageList($input, $perm=false, $sortby='pagename', $limit=false) {
1199     include_once("lib/PageList.php");
1200     return PageList::explodePageList($input,$perm,$sortby,$limit);
1201 }
1202
1203 // Class introspections
1204
1205 /** Determine whether object is of a specified type.
1206  *
1207  * @param $object object An object.
1208  * @param $class string Class name.
1209  * @return bool True iff $object is a $class
1210  * or a sub-type of $class. 
1211  */
1212 function isa ($object, $class) {
1213     $lclass = strtolower($class);
1214
1215     return is_object($object)
1216         && ( get_class($object) == strtolower($lclass)
1217              || is_subclass_of($object, $lclass) );
1218 }
1219
1220 /** Determine whether (possible) object has method.
1221  *
1222  * @param $object mixed Object
1223  * @param $method string Method name
1224  * @return bool True iff $object is an object with has method $method.
1225  */
1226 function can ($object, $method) {
1227     return is_object($object) && method_exists($object, strtolower($method));
1228 }
1229
1230 /** Determine whether a function is okay to use.
1231  *
1232  * Some providers (e.g. Lycos) disable some of PHP functions for
1233  * "security reasons."  This makes those functions, of course,
1234  * unusable, despite the fact the function_exists() says they
1235  * exist.
1236  *
1237  * This function test to see if a function exists and is not
1238  * disallowed by PHP's disable_functions config setting.
1239  *
1240  * @param string $function_name  Function name
1241  * @return bool  True iff function can be used.
1242  */
1243 function function_usable($function_name) {
1244     static $disabled;
1245     if (!is_array($disabled)) {
1246         $disabled = array();
1247         // Use get_cfg_var since ini_get() is one of the disabled functions
1248         // (on Lycos, at least.)
1249         $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1250         foreach ($split as $f)
1251             $disabled[strtolower($f)] = true;
1252     }
1253
1254     return ( function_exists($function_name)
1255              and ! isset($disabled[strtolower($function_name)])
1256              );
1257 }
1258     
1259     
1260 /** Hash a value.
1261  *
1262  * This is used for generating ETags.
1263  */
1264 function hash ($x) {
1265     if (is_scalar($x)) {
1266         return $x;
1267     }
1268     elseif (is_array($x)) {            
1269         ksort($x);
1270         return md5(serialize($x));
1271     }
1272     elseif (is_object($x)) {
1273         return $x->hash();
1274     }
1275     trigger_error("Can't hash $x", E_USER_ERROR);
1276 }
1277
1278     
1279 /**
1280  * Seed the random number generator.
1281  *
1282  * better_srand() ensures the randomizer is seeded only once.
1283  * 
1284  * How random do you want it? See:
1285  * http://www.php.net/manual/en/function.srand.php
1286  * http://www.php.net/manual/en/function.mt-srand.php
1287  */
1288 function better_srand($seed = '') {
1289     static $wascalled = FALSE;
1290     if (!$wascalled) {
1291         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1292         srand($seed);
1293         $wascalled = TRUE;
1294         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1295     }
1296 }
1297
1298 /**
1299  * Recursively count all non-empty elements 
1300  * in array of any dimension or mixed - i.e. 
1301  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1302  * See http://www.php.net/manual/en/function.count.php
1303  */
1304 function count_all($arg) {
1305     // skip if argument is empty
1306     if ($arg) {
1307         //print_r($arg); //debugging
1308         $count = 0;
1309         // not an array, return 1 (base case) 
1310         if(!is_array($arg))
1311             return 1;
1312         // else call recursively for all elements $arg
1313         foreach($arg as $key => $val)
1314             $count += count_all($val);
1315         return $count;
1316     }
1317 }
1318
1319 function isSubPage($pagename) {
1320     return (strstr($pagename, SUBPAGE_SEPARATOR));
1321 }
1322
1323 function subPageSlice($pagename, $pos) {
1324     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1325     $pages = array_slice($pages,$pos,1);
1326     return $pages[0];
1327 }
1328
1329 /**
1330  * Alert
1331  *
1332  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1333  * pop up...)
1334  *
1335  * FIXME:
1336  * This is a hackish and needs to be refactored.  However it would be nice to
1337  * unify all the different methods we use for showing Alerts and Dialogs.
1338  * (E.g. "Page deleted", login form, ...)
1339  */
1340 class Alert {
1341     /** Constructor
1342      *
1343      * @param object $request
1344      * @param mixed $head  Header ("title") for alert box.
1345      * @param mixed $body  The text in the alert box.
1346      * @param hash $buttons  An array mapping button labels to URLs.
1347      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1348      */
1349     function Alert($head, $body, $buttons=false) {
1350         if ($buttons === false)
1351             $buttons = array();
1352
1353         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1354         $this->_buttons = $buttons;
1355     }
1356
1357     /**
1358      * Show the alert box.
1359      */
1360     function show(&$request) {
1361         global $request;
1362
1363         $tokens = $this->_tokens;
1364         $tokens['BUTTONS'] = $this->_getButtons();
1365         
1366         $request->discardOutput();
1367         $tmpl = new Template('dialog', $request, $tokens);
1368         $tmpl->printXML();
1369         $request->finish();
1370     }
1371
1372
1373     function _getButtons() {
1374         global $request;
1375
1376         $buttons = $this->_buttons;
1377         if (!$buttons)
1378             $buttons = array(_("Okay") => $request->getURLtoSelf());
1379         
1380         global $Theme;
1381         foreach ($buttons as $label => $url)
1382             print "$label $url\n";
1383             $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1384         return new XmlContent($out);
1385     }
1386 }
1387
1388 // 1.3.8     => 1030.08
1389 // 1.3.9-p1  => 1030.091
1390 // 1.3.10pre => 1030.099
1391 function phpwiki_version() {
1392     static $PHPWIKI_VERSION;
1393     if (!isset($PHPWIKI_VERSION)) {
1394         $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1395         $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1396         $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1397         if (substr(PHPWIKI_VERSION,-3,3) == 'pre')
1398             $PHPWIKI_VERSION -= 0.001;
1399     }
1400     return $PHPWIKI_VERSION;
1401 }
1402
1403 function isWikiWord($word) {
1404     global $WikiNameRegexp;
1405     //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1406     return preg_match("/^$WikiNameRegexp\$/",$word);
1407 }
1408
1409 // needed to store serialized objects-values only (perm, pref)
1410 function obj2hash ($obj, $exclude = false, $fields = false) {
1411     $a = array();
1412     if (! $fields ) $fields = get_object_vars($obj);
1413     foreach ($fields as $key => $val) {
1414         if (is_array($exclude)) {
1415             if (in_array($key,$exclude)) continue;
1416         }
1417         $a[$key] = $val;
1418     }
1419     return $a;
1420 }
1421
1422 // $Log: not supported by cvs2svn $
1423 // Revision 1.178  2004/05/12 10:49:55  rurban
1424 // require_once fix for those libs which are loaded before FileFinder and
1425 //   its automatic include_path fix, and where require_once doesn't grok
1426 //   dirname(__FILE__) != './lib'
1427 // upgrade fix with PearDB
1428 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1429 //
1430 // Revision 1.177  2004/05/08 14:06:12  rurban
1431 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
1432 // minor stability and portability fixes
1433 //
1434 // Revision 1.176  2004/05/08 11:25:15  rurban
1435 // php-4.0.4 fixes
1436 //
1437 // Revision 1.175  2004/05/06 17:30:38  rurban
1438 // CategoryGroup: oops, dos2unix eol
1439 // improved phpwiki_version:
1440 //   pre -= .0001 (1.3.10pre: 1030.099)
1441 //   -p1 += .001 (1.3.9-p1: 1030.091)
1442 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1443 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1444 //   backend->backendType(), backend->database(),
1445 //   backend->listOfFields(),
1446 //   backend->listOfTables(),
1447 //
1448 // Revision 1.174  2004/05/06 12:02:05  rurban
1449 // fix sf.net bug#949002: [ Link | ] assertion
1450 //
1451 // Revision 1.173  2004/05/03 15:00:31  rurban
1452 // added more database upgrading: session.sess_ip, page.id autp_increment
1453 //
1454 // Revision 1.172  2004/04/26 20:44:34  rurban
1455 // locking table specific for better databases
1456 //
1457 // Revision 1.171  2004/04/19 23:13:03  zorloc
1458 // Connect the rest of PhpWiki to the IniConfig system.  Also the keyword regular expression is not a config setting
1459 //
1460 // Revision 1.170  2004/04/19 18:27:45  rurban
1461 // Prevent from some PHP5 warnings (ref args, no :: object init)
1462 //   php5 runs now through, just one wrong XmlElement object init missing
1463 // Removed unneccesary UpgradeUser lines
1464 // Changed WikiLink to omit version if current (RecentChanges)
1465 //
1466 // Revision 1.169  2004/04/15 21:29:48  rurban
1467 // allow [0] with new markup: link to page "0"
1468 //
1469 // Revision 1.168  2004/04/10 02:30:49  rurban
1470 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
1471 // Fixed "cannot setlocale..." (sf.net problem)
1472 //
1473 // Revision 1.167  2004/04/02 15:06:55  rurban
1474 // fixed a nasty ADODB_mysql session update bug
1475 // improved UserPreferences layout (tabled hints)
1476 // fixed UserPreferences auth handling
1477 // improved auth stability
1478 // improved old cookie handling: fixed deletion of old cookies with paths
1479 //
1480 // Revision 1.166  2004/04/01 15:57:10  rurban
1481 // simplified Sidebar theme: table, not absolute css positioning
1482 // added the new box methods.
1483 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
1484 //
1485 // Revision 1.165  2004/03/24 19:39:03  rurban
1486 // php5 workaround code (plus some interim debugging code in XmlElement)
1487 //   php5 doesn't work yet with the current XmlElement class constructors,
1488 //   WikiUserNew does work better than php4.
1489 // rewrote WikiUserNew user upgrading to ease php5 update
1490 // fixed pref handling in WikiUserNew
1491 // added Email Notification
1492 // added simple Email verification
1493 // removed emailVerify userpref subclass: just a email property
1494 // changed pref binary storage layout: numarray => hash of non default values
1495 // print optimize message only if really done.
1496 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1497 //   prefs should be stored in db or homepage, besides the current session.
1498 //
1499 // Revision 1.164  2004/03/18 21:41:09  rurban
1500 // fixed sqlite support
1501 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
1502 //
1503 // Revision 1.163  2004/03/17 18:41:49  rurban
1504 // just reformatting
1505 //
1506 // Revision 1.162  2004/03/16 15:43:08  rurban
1507 // make fileSet sortable to please PageList
1508 //
1509 // Revision 1.161  2004/03/12 15:48:07  rurban
1510 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1511 // simplified lib/stdlib.php:explodePageList
1512 //
1513 // Revision 1.160  2004/02/28 21:14:08  rurban
1514 // generally more PHPDOC docs
1515 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
1516 // fxied WikiUserNew pref handling: empty theme not stored, save only
1517 //   changed prefs, sql prefs improved, fixed password update,
1518 //   removed REPLACE sql (dangerous)
1519 // moved gettext init after the locale was guessed
1520 // + some minor changes
1521 //
1522 // Revision 1.158  2004/02/19 21:54:17  rurban
1523 // moved initerwiki code to PageType.php
1524 // re-enabled and fixed InlineImages support, now also for InterWiki Urls
1525 //      * [File:my_image.gif] inlines the image,
1526 //      * File:my_image.gif shows a plain inter-wiki link,
1527 //      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
1528 //      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
1529 //
1530 // Revision 1.157  2004/02/09 03:58:12  rurban
1531 // for now default DB_SESSION to false
1532 // PagePerm:
1533 //   * not existing perms will now query the parent, and not
1534 //     return the default perm
1535 //   * added pagePermissions func which returns the object per page
1536 //   * added getAccessDescription
1537 // WikiUserNew:
1538 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1539 //   * force init of authdbh in the 2 db classes
1540 // main:
1541 //   * fixed session handling (not triple auth request anymore)
1542 //   * don't store cookie prefs with sessions
1543 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1544 //
1545 // Revision 1.156  2004/01/26 09:17:49  rurban
1546 // * changed stored pref representation as before.
1547 //   the array of objects is 1) bigger and 2)
1548 //   less portable. If we would import packed pref
1549 //   objects and the object definition was changed, PHP would fail.
1550 //   This doesn't happen with an simple array of non-default values.
1551 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1552 //   understands the interim format of array of objects also.
1553 // * simplified $prefs->get() and fixed $prefs->set()
1554 // * added $user->_userid and class '_WikiUser' portability functions
1555 // * fixed $user object ->_level upgrading, mostly using sessions.
1556 //   this fixes yesterdays problems with loosing authorization level.
1557 // * fixed WikiUserNew::checkPass to return the _level
1558 // * fixed WikiUserNew::isSignedIn
1559 // * added explodePageList to class PageList, support sortby arg
1560 // * fixed UserPreferences for WikiUserNew
1561 // * fixed WikiPlugin for empty defaults array
1562 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1563 //   removed sort arg, support sortby arg
1564 //
1565 // Revision 1.155  2004/01/25 10:52:22  rurban
1566 // added sortby support to explodePageList() and UnfoldSubpages
1567 // fixes [ 758044 ] Plugin UnfoldSubpages does not sort (includes fix)
1568 //
1569 // Revision 1.154  2004/01/25 03:49:03  rurban
1570 // added isWikiWord() to avoid redundancy
1571 // added check_php_version() to check for older php versions.
1572 //   e.g. object::method calls, ...
1573 //
1574 // Revision 1.153  2003/11/30 18:43:18  carstenklapp
1575 // Fixed careless mistakes in my last optimization commit.
1576 //
1577 // Revision 1.152  2003/11/30 18:20:34  carstenklapp
1578 // Minor code optimization: reduce invariant loops
1579 //
1580 // Revision 1.151  2003/11/29 19:30:01  carstenklapp
1581 // New function ByteFormatter.
1582 //
1583 // Revision 1.150  2003/09/13 22:43:00  carstenklapp
1584 // New preference to hide LinkIcons.
1585 //
1586 // Revision 1.149  2003/03/26 19:37:08  dairiki
1587 // Fix "object to string conversion" bug with external image links.
1588 //
1589 // Revision 1.148  2003/03/25 21:03:02  dairiki
1590 // Cleanup debugging output.
1591 //
1592 // Revision 1.147  2003/03/13 20:17:05  dairiki
1593 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1594 //
1595 // Revision 1.146  2003/03/07 02:46:24  dairiki
1596 // function_usable(): New function.
1597 //
1598 // Revision 1.145  2003/03/04 01:55:05  dairiki
1599 // Fix to ensure absolute URL for logo in RSS recent changes.
1600 //
1601 // Revision 1.144  2003/02/26 00:39:30  dairiki
1602 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1603 // being displayed at incorrect times.
1604 //
1605 // Revision 1.143  2003/02/26 00:10:26  dairiki
1606 // More/better/different checks for bad page names.
1607 //
1608 // Revision 1.142  2003/02/25 22:19:46  dairiki
1609 // Add some sanity checking for pagenames.
1610 //
1611 // Revision 1.141  2003/02/22 20:49:55  dairiki
1612 // Fixes for "Call-time pass by reference has been deprecated" errors.
1613 //
1614 // Revision 1.140  2003/02/21 23:33:29  dairiki
1615 // Set alt="" on the link icon image tags.
1616 // (See SF bug #675141.)
1617 //
1618 // Revision 1.139  2003/02/21 22:16:27  dairiki
1619 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1620 // These have been obsolete for quite awhile (I hope).
1621 //
1622 // Revision 1.138  2003/02/21 04:12:36  dairiki
1623 // WikiPageName: fixes for new cached links.
1624 //
1625 // Alert: new class for displaying alerts.
1626 //
1627 // ExtractWikiPageLinks and friends are now gone.
1628 //
1629 // LinkBracketLink moved to InlineParser.php
1630 //
1631 // Revision 1.137  2003/02/18 23:13:40  dairiki
1632 // Wups again.  Typo fix.
1633 //
1634 // Revision 1.136  2003/02/18 21:52:07  dairiki
1635 // Fix so that one can still link to wiki pages with # in their names.
1636 // (This was made difficult by the introduction of named tags, since
1637 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1638 //
1639 // Now the ~ escape for page names should work: [Page ~#1].
1640 //
1641 // Revision 1.135  2003/02/18 19:17:04  dairiki
1642 // split_pagename():
1643 //     Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1644 //     Cleanup up subpage splitting code.
1645 //
1646 // Revision 1.134  2003/02/16 19:44:20  dairiki
1647 // New function hash().  This is a helper, primarily for generating
1648 // HTTP ETags.
1649 //
1650 // Revision 1.133  2003/02/16 04:50:09  dairiki
1651 // New functions:
1652 // Rfc1123DateTime(), ParseRfc1123DateTime()
1653 // for converting unix timestamps to and from strings.
1654 //
1655 // These functions produce and grok the time strings
1656 // in the format specified by RFC 2616 for use in HTTP headers
1657 // (like Last-Modified).
1658 //
1659 // Revision 1.132  2003/01/04 22:19:43  carstenklapp
1660 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1661 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1662 //
1663
1664 // (c-file-style: "gnu")
1665 // Local Variables:
1666 // mode: php
1667 // tab-width: 8
1668 // c-basic-offset: 4
1669 // c-hanging-comment-ender-p: nil
1670 // indent-tabs-mode: nil
1671 // End:   
1672 ?>