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