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