]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.144 2003-02-26 00:39:30 dairiki 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 {
69     if (!$str)
70         return 'empty.';
71     
72     return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
73                         "'x' . sprintf('%02x', ord('\\0')) . '.'",
74                         $str);
75 }
76     
77
78 /**
79  * Generates a valid URL for a given Wiki pagename.
80  * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
81  *                        If a WikiDB_Page object function will extract the name to link to.
82  *                        If a WikiDB_PageRevision object function will extract the name to link to.
83  * @param array $args 
84  * @param boolean $get_abs_url Default value is false.
85  * @return string The absolute URL to the page passed as $pagename.
86  */
87 function WikiURL($pagename, $args = '', $get_abs_url = false) {
88     $anchor = false;
89     
90     if (is_object($pagename)) {
91         if (isa($pagename, 'WikiDB_Page')) {
92             $pagename = $pagename->getName();
93         }
94         elseif (isa($pagename, 'WikiDB_PageRevision')) {
95             $page = $pagename->getPage();
96             $args['version'] = $pagename->getVersion();
97             $pagename = $page->getName();
98         }
99         elseif (isa($pagename, 'WikiPageName')) {
100             $anchor = $pagename->anchor;
101             $pagename = $pagename->name;
102         }
103     }
104     
105     if (is_array($args)) {
106         $enc_args = array();
107         foreach  ($args as $key => $val) {
108             if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
109               $enc_args[] = urlencode($key) . '=' . urlencode($val);
110         }
111         $args = join('&', $enc_args);
112     }
113
114     if (USE_PATH_INFO) {
115         $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
116         $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
117         if ($args)
118             $url .= "?$args";
119     }
120     else {
121         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
122         $url .= "?pagename=" . rawurlencode($pagename);
123         if ($args)
124             $url .= "&$args";
125     }
126     if ($anchor)
127         $url .= "#" . MangleXmlIdentifier($anchor);
128     return $url;
129 }
130
131 /**
132  * Generates icon in front of links.
133  *
134  * @param string $protocol_or_url URL or protocol to determine which icon to use.
135  *
136  * @return HtmlElement HtmlElement object that contains data to create img link to
137  * icon for use with url or protocol passed to the function. False if no img to be
138  * displayed.
139  */
140 function IconForLink($protocol_or_url) {
141     global $Theme;
142     if ($filename_suffix = false) {
143         // display apache style icon for file type instead of protocol icon
144         // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
145         // - document: html, htm, text, txt, rtf, pdf, doc
146         // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
147         // - audio: mp3,mp2,aiff,aif,au
148         // - multimedia: mpeg,mpg,mov,qt
149     } else {
150         list ($proto) = explode(':', $protocol_or_url, 2);
151         $src = $Theme->getLinkIconURL($proto);
152         if ($src)
153             return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
154         else
155             return false;
156     }
157 }
158
159 /**
160  * Glue icon in front of text.
161  *
162  * @param string $protocol_or_url Protocol or URL.  Used to determine the
163  * proper icon.
164  * @param string $text The text.
165  * @return XmlContent.
166  */
167 function PossiblyGlueIconToText($proto_or_url, $text) {
168     $icon = IconForLink($proto_or_url);
169     if ($icon) {
170         preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
171         list (, $first_word, $tail) = $m;
172         $text = HTML::span(array('style' => 'white-space: nowrap'),
173                            $icon, $first_word);
174         if ($tail)
175             $text = HTML($text, $tail);
176     }
177     return $text;
178 }
179
180 /**
181  * Determines if the url passed to function is safe, by detecting if the characters
182  * '<', '>', or '"' are present.
183  *
184  * @param string $url URL to check for unsafe characters.
185  * @return boolean True if same, false else.
186  */
187 function IsSafeURL($url) {
188     return !ereg('[<>"]', $url);
189 }
190
191 /**
192  * Generates an HtmlElement object to store data for a link.
193  *
194  * @param string $url URL that the link will point to.
195  * @param string $linktext Text to be displayed as link.
196  * @return HtmlElement HtmlElement object that contains data to construct an html link.
197  */
198 function LinkURL($url, $linktext = '') {
199     // FIXME: Is this needed (or sufficient?)
200     if(! IsSafeURL($url)) {
201         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
202                                      _("BAD URL -- remove all of <, >, \"")));
203     }
204     else {
205         if (!$linktext)
206             $linktext = preg_replace("/mailto:/A", "", $url);
207         
208         $link = HTML::a(array('href' => $url),
209                         PossiblyGlueIconToText($url, $linktext));
210         
211     }
212     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
213     return $link;
214 }
215
216
217 function LinkImage($url, $alt = false) {
218     // FIXME: Is this needed (or sufficient?)
219     if(! IsSafeURL($url)) {
220         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
221                                      _("BAD URL -- remove all of <, >, \"")));
222     }
223     else {
224         if (empty($alt))
225             $alt = $url;
226         $link = HTML::img(array('src' => $url, 'alt' => $alt));
227     }
228     $link->setAttr('class', 'inlineimage');
229     return $link;
230 }
231
232
233
234 class Stack {
235     var $items = array();
236     var $size = 0;
237     
238     function push($item) {
239         $this->items[$this->size] = $item;
240         $this->size++;
241         return true;
242     }  
243     
244     function pop() {
245         if ($this->size == 0) {
246             return false; // stack is empty
247         }  
248         $this->size--;
249         return $this->items[$this->size];
250     }  
251     
252     function cnt() {
253         return $this->size;
254     }  
255     
256     function top() {
257         if($this->size)
258             return $this->items[$this->size - 1];
259         else
260             return '';
261     }
262     
263 }  
264 // end class definition
265
266 function SplitQueryArgs ($query_args = '') 
267 {
268     $split_args = split('&', $query_args);
269     $args = array();
270     while (list($key, $val) = each($split_args))
271         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
272             $args[$m[1]] = $m[2];
273     return $args;
274 }
275
276 function LinkPhpwikiURL($url, $text = '', $basepage) {
277     $args = array();
278     
279     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
280         return HTML::strong(array('class' => 'rawurl'),
281                             HTML::u(array('class' => 'baduri'),
282                                     _("BAD phpwiki: URL")));
283     }
284
285     if ($m[1])
286         $pagename = urldecode($m[1]);
287     $qargs = $m[2];
288     
289     if (empty($pagename) &&
290         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
291         // Convert old style links (to not break diff links in
292         // RecentChanges).
293         $pagename = urldecode($m[2]);
294         $args = array("action" => $m[1]);
295     }
296     else {
297         $args = SplitQueryArgs($qargs);
298     }
299
300     if (empty($pagename))
301         $pagename = $GLOBALS['request']->getArg('pagename');
302
303     if (isset($args['action']) && $args['action'] == 'browse')
304         unset($args['action']);
305     
306     /*FIXME:
307       if (empty($args['action']))
308       $class = 'wikilink';
309       else if (is_safe_action($args['action']))
310       $class = 'wikiaction';
311     */
312     if (empty($args['action']) || is_safe_action($args['action']))
313         $class = 'wikiaction';
314     else {
315         // Don't allow administrative links on unlocked pages.
316         $dbi = $GLOBALS['request']->getDbh();
317         $page = $dbi->getPage($basepage);
318         if (!$page->get('locked'))
319             return HTML::span(array('class' => 'wikiunsafe'),
320                               HTML::u(_("Lock page to enable link")));
321         $class = 'wikiadmin';
322     }
323     
324     if (!$text)
325         $text = HTML::span(array('class' => 'rawurl'), $url);
326
327     $wikipage = new WikiPageName($pagename);
328     if (!$wikipage->isValid()) {
329         global $Theme;
330         return $Theme->linkBadWikiWord($wikipage, $url);
331     }
332     
333     return HTML::a(array('href'  => WikiURL($pagename, $args),
334                          'class' => $class),
335                    $text);
336 }
337
338 /**
339  * A class to assist in parsing wiki pagenames.
340  *
341  * Now with subpages and anchors, parsing and passing around
342  * pagenames is more complicated.  This should help.
343  */
344 class WikiPagename
345 {
346     /** Short name for page.
347      *
348      * This is the value of $name passed to the constructor.
349      * (For use, e.g. as a default label for links to the page.)
350      */
351     var $shortName;
352
353     /** The full page name.
354      *
355      * This is the full name of the page (without anchor).
356      */
357     var $name;
358     
359     /** The anchor.
360      *
361      * This is the referenced anchor within the page, or the empty string.
362      */
363     var $anchor;
364     
365     /** Constructor
366      *
367      * @param mixed $name Page name.
368      * WikiDB_Page, WikiDB_PageRevision, or string.
369      * This can be a relative subpage name (like '/SubPage'),
370      * or can be the empty string to refer to the $basename.
371      *
372      * @param string $anchor For links to anchors in page.
373      *
374      * @param mixed $basename Page name from which to interpret
375      * relative or other non-fully-specified page names.
376      */
377     function WikiPageName($name, $basename=false, $anchor=false) {
378         if (is_string($name)) {
379             $this->shortName = $name;
380         
381             if ($anchor === false and preg_match('/\A(.*)#(.*?)?\Z/', $name, $m))
382                 list(, $name, $anchor) = $m;
383             
384             if (empty($name) or $name[0] == SUBPAGE_SEPARATOR) {
385                 if ($basename)
386                     $name = $this->_pagename($basename) . $name;
387                 else
388                     $name = $this->_normalize_bad_pagename($name);
389             }
390         }
391         else {
392             $name = $this->_pagename($name);
393             $this->shortName = $name;
394         }
395
396         $this->name = $this->_check($name);
397         $this->anchor = (string)$anchor;
398     }
399
400     function getParent() {
401         $name = $this->name;
402         if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
403             return false;
404         return substr($name, 0, -strlen($tail));
405     }
406
407     function isValid($strict = false) {
408         if ($strict)
409             return !isset($this->_errors);
410         return !empty($this->name);
411     }
412
413     function getWarnings() {
414         $warnings = array();
415         if (isset($this->_warnings))
416             $warnings = array_merge($warnings, $this->_warnings);
417         if (isset($this->_errors))
418             $warnings = array_merge($warnings, $this->_errors);
419         if (!$warnings)
420             return false;
421         
422         return sprintf(_("'%s': Bad page name: %s"),
423                        $this->shortName, join(', ', $warnings));
424     }
425     
426     function _pagename($page) {
427         if (isa($page, 'WikiDB_Page'))
428             return $page->getName();
429         elseif (isa($page, 'WikiDB_PageRevision'))
430             return $page->getPageName();
431         elseif (isa($page, 'WikiPageName'))
432             return $page->name;
433         if (!is_string($page)) {
434             print "PAGE: " . gettype($page) . " " . get_class($page) . "<br>\n";
435         }
436         //assert(is_string($page));
437         return $page;
438     }
439
440     function _normalize_bad_pagename($name) {
441         trigger_error("Bad pagename: " . $name, E_USER_WARNING);
442
443         // Punt...  You really shouldn't get here.
444         if (empty($name)) {
445             global $request;
446             return $request->getArg('pagename');
447         }
448         assert($name[0] == SUBPAGE_SEPARATOR);
449         return substr($name, 1);
450     }
451
452
453     function _check($pagename) {
454         // Compress internal white-space to single space character.
455         $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
456         if ($pagename != $orig)
457             $this->_warnings[] = _("White space converted to single space");
458     
459         // Delete any control characters.
460         $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
461         if ($pagename != $orig)
462             $this->_errors[] = _("Control characters not allowed");
463
464         // Strip leading and trailing white-space.
465         $pagename = trim($pagename);
466
467         $orig = $pagename;
468         while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
469             $pagename = substr($pagename, 1);
470         if ($pagename != $orig)
471             $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
472
473         if (preg_match('/[:;]/', $pagename))
474             $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
475         
476         if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
477             $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
478             $this->_errors[] = _("too long");
479         }
480         
481
482         if ($pagename == '.' or $pagename == '..') {
483             $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
484             $pagename = '';
485         }
486         
487         return $pagename;
488     }
489 }
490
491 /**
492  * Convert old page markup to new-style markup.
493  *
494  * @param string $text Old-style wiki markup.
495  *
496  * @param string $markup_type
497  * One of: <dl>
498  * <dt><code>"block"</code>  <dd>Convert all markup.
499  * <dt><code>"inline"</code> <dd>Convert only inline markup.
500  * <dt><code>"links"</code>  <dd>Convert only link markup.
501  * </dl>
502  *
503  * @return string New-style wiki markup.
504  *
505  * @bugs Footnotes don't work quite as before (esp if there are
506  *   multiple references to the same footnote.  But close enough,
507  *   probably for now....
508  */
509 function ConvertOldMarkup ($text, $markup_type = "block") {
510
511     static $subs;
512     static $block_re;
513     
514     if (empty($subs)) {
515         /*****************************************************************
516          * Conversions for inline markup:
517          */
518
519         // escape tilde's
520         $orig[] = '/~/';
521         $repl[] = '~~';
522
523         // escape escaped brackets
524         $orig[] = '/\[\[/';
525         $repl[] = '~[';
526
527         // change ! escapes to ~'s.
528         global $AllowedProtocols, $WikiNameRegexp, $request;
529         include_once('lib/interwiki.php');
530         $map = InterWikiMap::GetMap($request);
531         $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
532         $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
533         $bang_esc[] = $WikiNameRegexp;
534         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
535         $repl[] = '~\\1';
536
537         $subs["links"] = array($orig, $repl);
538
539         // Escape '<'s
540         //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
541         //$repl[] = '~<';
542         
543         // Convert footnote references.
544         $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
545         $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
546
547         // Convert old style emphases to HTML style emphasis.
548         $orig[] = '/__(.*?)__/';
549         $repl[] = '<strong>\\1</strong>';
550         $orig[] = "/''(.*?)''/";
551         $repl[] = '<em>\\1</em>';
552
553         // Escape nestled markup.
554         $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
555         $repl[] = '~\\0';
556         
557         // in old markup headings only allowed at beginning of line
558         $orig[] = '/!/';
559         $repl[] = '~!';
560
561         $subs["inline"] = array($orig, $repl);
562
563         /*****************************************************************
564          * Patterns which match block markup constructs which take
565          * special handling...
566          */
567
568         // Indented blocks
569         $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
570
571         // Tables
572         $blockpats[] = '\|(?:.*\n\|)*';
573
574         // List items
575         $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
576
577         // Footnote definitions
578         $blockpats[] = '\[\s*(\d+)\s*\]';
579
580         // Plugins
581         $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
582
583         // Section Title
584         $blockpats[] = '!{1,3}[^!]';
585
586         $block_re = ( '/\A((?:.|\n)*?)(^(?:'
587                       . join("|", $blockpats)
588                       . ').*$)\n?/m' );
589         
590     }
591     
592     if ($markup_type != "block") {
593         list ($orig, $repl) = $subs[$markup_type];
594         return preg_replace($orig, $repl, $text);
595     }
596     else {
597         list ($orig, $repl) = $subs['inline'];
598         $out = '';
599         while (preg_match($block_re, $text, $m)) {
600             $text = substr($text, strlen($m[0]));
601             list (,$leading_text, $block) = $m;
602             $suffix = "\n";
603             
604             if (strchr(" \t", $block[0])) {
605                 // Indented block
606                 $prefix = "<pre>\n";
607                 $suffix = "\n</pre>\n";
608             }
609             elseif ($block[0] == '|') {
610                 // Old-style table
611                 $prefix = "<?plugin OldStyleTable\n";
612                 $suffix = "\n?>\n";
613             }
614             elseif (strchr("#*;", $block[0])) {
615                 // Old-style list item
616                 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
617                 list (,$ind,$bullet) = $m;
618                 $block = substr($block, strlen($m[0]));
619                 
620                 $indent = str_repeat('     ', strlen($ind));
621                 if ($bullet[0] == ';') {
622                     //$term = ltrim(substr($bullet, 1));
623                     //return $indent . $term . "\n" . $indent . '     ';
624                     $prefix = $ind . $bullet;
625                 }
626                 else
627                     $prefix = $indent . $bullet . ' ';
628             }
629             elseif ($block[0] == '[') {
630                 // Footnote definition
631                 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
632                 $footnum = $m[1];
633                 $block = substr($block, strlen($m[0]));
634                 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
635             }
636             elseif ($block[0] == '<') {
637                 // Plugin.
638                 // HACK: no inline markup...
639                 $prefix = $block;
640                 $block = '';
641             }
642             elseif ($block[0] == '!') {
643                 // Section heading
644                 preg_match('/^!{1,3}/', $block, $m);
645                 $prefix = $m[0];
646                 $block = substr($block, strlen($m[0]));
647             }
648             else {
649                 // AAck!
650                 assert(0);
651             }
652
653             $out .= ( preg_replace($orig, $repl, $leading_text)
654                       . $prefix
655                       . preg_replace($orig, $repl, $block)
656                       . $suffix );
657         }
658         return $out . preg_replace($orig, $repl, $text);
659     }
660 }
661
662
663 /**
664  * Expand tabs in string.
665  *
666  * Converts all tabs to (the appropriate number of) spaces.
667  *
668  * @param string $str
669  * @param integer $tab_width
670  * @return string
671  */
672 function expand_tabs($str, $tab_width = 8) {
673     $split = split("\t", $str);
674     $tail = array_pop($split);
675     $expanded = "\n";
676     foreach ($split as $hunk) {
677         $expanded .= $hunk;
678         $pos = strlen(strrchr($expanded, "\n")) - 1;
679         $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
680     }
681     return substr($expanded, 1) . $tail;
682 }
683
684 /**
685  * Split WikiWords in page names.
686  *
687  * It has been deemed useful to split WikiWords (into "Wiki Words") in
688  * places like page titles. This is rumored to help search engines
689  * quite a bit.
690  *
691  * @param $page string The page name.
692  *
693  * @return string The split name.
694  */
695 function split_pagename ($page) {
696     
697     if (preg_match("/\s/", $page))
698         return $page;           // Already split --- don't split any more.
699     
700     // FIXME: this algorithm is Anglo-centric.
701     static $RE;
702     if (!isset($RE)) {
703         // This mess splits between a lower-case letter followed by
704         // either an upper-case or a numeral; except that it wont
705         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
706         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
707         // This the single-letter words 'I' and 'A' from any following
708         // capitalized words.
709         $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
710         $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
711         // Split numerals from following letters.
712         $RE[] = '/(\d)([[:alpha:]])/';
713         
714         foreach ($RE as $key => $val)
715             $RE[$key] = pcre_fix_posix_classes($val);
716     }
717
718     foreach ($RE as $regexp) {
719         $page = preg_replace($regexp, '\\1 \\2', $page);
720     }
721     return $page;
722 }
723
724 function NoSuchRevision (&$request, $page, $version) {
725     $html = HTML(HTML::h2(_("Revision Not Found")),
726                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
727                              $version, WikiLink($page, 'auto'))));
728     include_once('lib/Template.php');
729     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
730     $request->finish();
731 }
732
733
734 /**
735  * Get time offset for local time zone.
736  *
737  * @param $time time_t Get offset for this time. Default: now.
738  * @param $no_colon boolean Don't put colon between hours and minutes.
739  * @return string Offset as a string in the format +HH:MM.
740  */
741 function TimezoneOffset ($time = false, $no_colon = false) {
742     if ($time === false)
743         $time = time();
744     $secs = date('Z', $time);
745
746     if ($secs < 0) {
747         $sign = '-';
748         $secs = -$secs;
749     }
750     else {
751         $sign = '+';
752     }
753     $colon = $no_colon ? '' : ':';
754     $mins = intval(($secs + 30) / 60);
755     return sprintf("%s%02d%s%02d",
756                    $sign, $mins / 60, $colon, $mins % 60);
757 }
758
759
760 /**
761  * Format time in ISO-8601 format.
762  *
763  * @param $time time_t Time.  Default: now.
764  * @return string Date and time in ISO-8601 format.
765  */
766 function Iso8601DateTime ($time = false) {
767     if ($time === false)
768         $time = time();
769     $tzoff = TimezoneOffset($time);
770     $date  = date('Y-m-d', $time);
771     $time  = date('H:i:s', $time);
772     return $date . 'T' . $time . $tzoff;
773 }
774
775 /**
776  * Format time in RFC-2822 format.
777  *
778  * @param $time time_t Time.  Default: now.
779  * @return string Date and time in RFC-2822 format.
780  */
781 function Rfc2822DateTime ($time = false) {
782     if ($time === false)
783         $time = time();
784     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
785 }
786
787 /**
788  * Format time in RFC-1123 format.
789  *
790  * @param $time time_t Time.  Default: now.
791  * @return string Date and time in RFC-1123 format.
792  */
793 function Rfc1123DateTime ($time = false) {
794     if ($time === false)
795         $time = time();
796     return gmdate('D, d M Y H:i:s \G\M\T', $time);
797 }
798
799 /** Parse date in RFC-1123 format.
800  *
801  * According to RFC 1123 we must accept dates in the following
802  * formats:
803  *
804  *   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
805  *   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
806  *   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
807  *
808  * (Though we're only allowed to generate dates in the first format.)
809  */
810 function ParseRfc1123DateTime ($timestr) {
811     $timestr = trim($timestr);
812     if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
813                    .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
814                    $timestr, $m)) {
815         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
816     }
817     elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
818                        .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
819                        $timestr, $m)) {
820         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
821         if ($year < 70) $year += 2000;
822         elseif ($year < 100) $year += 1900;
823     }
824     elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
825                        .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
826                        $timestr, $m)) {
827         list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
828     }
829     else {
830         // Parse failed.
831         return false;
832     }
833
834     $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
835     if ($time == -1)
836         return false;           // failed
837     return $time;
838 }
839
840 /**
841  * Format time to standard 'ctime' format.
842  *
843  * @param $time time_t Time.  Default: now.
844  * @return string Date and time.
845  */
846 function CTime ($time = false)
847 {
848     if ($time === false)
849         $time = time();
850     return date("D M j H:i:s Y", $time);
851 }
852
853
854
855 /**
856  * Internationalized printf.
857  *
858  * This is essentially the same as PHP's built-in printf
859  * with the following exceptions:
860  * <ol>
861  * <li> It passes the format string through gettext().
862  * <li> It supports the argument reordering extensions.
863  * </ol>
864  *
865  * Example:
866  *
867  * In php code, use:
868  * <pre>
869  *    __printf("Differences between versions %s and %s of %s",
870  *             $new_link, $old_link, $page_link);
871  * </pre>
872  *
873  * Then in locale/po/de.po, one can reorder the printf arguments:
874  *
875  * <pre>
876  *    msgid "Differences between %s and %s of %s."
877  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
878  * </pre>
879  *
880  * (Note that while PHP tries to expand $vars within double-quotes,
881  * the values in msgstr undergo no such expansion, so the '$'s
882  * okay...)
883  *
884  * One shouldn't use reordered arguments in the default format string.
885  * Backslashes in the default string would be necessary to escape the
886  * '$'s, and they'll cause all kinds of trouble....
887  */ 
888 function __printf ($fmt) {
889     $args = func_get_args();
890     array_shift($args);
891     echo __vsprintf($fmt, $args);
892 }
893
894 /**
895  * Internationalized sprintf.
896  *
897  * This is essentially the same as PHP's built-in printf with the
898  * following exceptions:
899  *
900  * <ol>
901  * <li> It passes the format string through gettext().
902  * <li> It supports the argument reordering extensions.
903  * </ol>
904  *
905  * @see __printf
906  */ 
907 function __sprintf ($fmt) {
908     $args = func_get_args();
909     array_shift($args);
910     return __vsprintf($fmt, $args);
911 }
912
913 /**
914  * Internationalized vsprintf.
915  *
916  * This is essentially the same as PHP's built-in printf with the
917  * following exceptions:
918  *
919  * <ol>
920  * <li> It passes the format string through gettext().
921  * <li> It supports the argument reordering extensions.
922  * </ol>
923  *
924  * @see __printf
925  */ 
926 function __vsprintf ($fmt, $args) {
927     $fmt = gettext($fmt);
928     // PHP's sprintf doesn't support variable with specifiers,
929     // like sprintf("%*s", 10, "x"); --- so we won't either.
930     
931     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
932         // Format string has '%2$s' style argument reordering.
933         // PHP doesn't support this.
934         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
935             // literal variable name substitution only to keep locale
936             // strings uncluttered
937             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
938                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
939         
940         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
941         $newargs = array();
942         
943         // Reorder arguments appropriately.
944         foreach($m[1] as $argnum) {
945             if ($argnum < 1 || $argnum > count($args))
946                 trigger_error(sprintf(_("%s: argument index out of range"), 
947                                       $argnum), E_USER_WARNING);
948             $newargs[] = $args[$argnum - 1];
949         }
950         $args = $newargs;
951     }
952     
953     // Not all PHP's have vsprintf, so...
954     array_unshift($args, $fmt);
955     return call_user_func_array('sprintf', $args);
956 }
957
958
959 class fileSet {
960     /**
961      * Build an array in $this->_fileList of files from $dirname.
962      * Subdirectories are not traversed.
963      *
964      * (This was a function LoadDir in lib/loadsave.php)
965      * See also http://www.php.net/manual/en/function.readdir.php
966      */
967     function getFiles() {
968         return $this->_fileList;
969     }
970
971     function _filenameSelector($filename) {
972         if (! $this->_pattern)
973             return true;
974         else {
975             return glob_match ($this->_pattern, $filename, $this->_case);
976         }
977     }
978
979     function fileSet($directory, $filepattern = false) {
980         $this->_fileList = array();
981         $this->_pattern = $filepattern;
982         $this->_case = !isWindows();
983         $this->_pathsep = '/';
984
985         if (empty($directory)) {
986             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
987                           E_USER_NOTICE);
988             return; // early return
989         }
990
991         @ $dir_handle = opendir($dir=$directory);
992         if (empty($dir_handle)) {
993             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
994                                   $dir), E_USER_NOTICE);
995             return; // early return
996         }
997
998         while ($filename = readdir($dir_handle)) {
999             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1000                 continue;
1001             if ($this->_filenameSelector($filename)) {
1002                 array_push($this->_fileList, "$filename");
1003                 //trigger_error(sprintf(_("found file %s"), $filename),
1004                 //                      E_USER_NOTICE); //debugging
1005             }
1006         }
1007         closedir($dir_handle);
1008     }
1009 };
1010
1011 // File globbing
1012
1013 // expands a list containing regex's to its matching entries
1014 class ListRegexExpand {
1015     var $match, $list, $index, $case_sensitive;
1016     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1017         $this->match = str_replace('/','\/',$match);
1018         $this->list = &$list;
1019         $this->case_sensitive = $case_sensitive;        
1020     }
1021     function listMatchCallback ($item, $key) {
1022         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1023             unset($this->list[$this->index]);
1024             $this->list[] = $item;
1025         }
1026     }
1027     function expandRegex ($index, &$pages) {
1028         $this->index = $index;
1029         array_walk($pages, array($this, 'listMatchCallback'));
1030         return $this->list;
1031     }
1032 }
1033
1034 // convert fileglob to regex style
1035 function glob_to_pcre ($glob) {
1036     $re = preg_replace('/\./', '\\.', $glob);
1037     $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1038     if (!preg_match('/^[\?\*]/',$glob))
1039         $re = '^' . $re;
1040     if (!preg_match('/[\?\*]$/',$glob))
1041         $re = $re . '$';
1042     return $re;
1043 }
1044
1045 function glob_match ($glob, $against, $case_sensitive = true) {
1046     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1047 }
1048
1049 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1050     $list = explode(',',$input);
1051     // expand wildcards from list of $allnames
1052     if (preg_match('/[\?\*]/',$input)) {
1053         for ($i = 0; $i < sizeof($list); $i++) {
1054             $f = $list[$i];
1055             if (preg_match('/[\?\*]/',$f)) {
1056                 reset($allnames);
1057                 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1058                 $expand->expandRegex($i, $allnames);
1059             }
1060         }
1061     }
1062     return $list;
1063 }
1064
1065 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1066
1067 function explodePageList($input, $perm = false) {
1068     // expand wildcards from list of all pages
1069     if (preg_match('/[\?\*]/',$input)) {
1070         $dbi = $GLOBALS['request']->_dbi;
1071         $allPagehandles = $dbi->getAllPages($perm);
1072         while ($pagehandle = $allPagehandles->next()) {
1073             $allPages[] = $pagehandle->getName();
1074         }
1075         return explodeList($input, $allPages);
1076     } else {
1077         return explode(',',$input);
1078     }
1079 }
1080
1081 // Class introspections
1082
1083 /** Determine whether object is of a specified type.
1084  *
1085  * @param $object object An object.
1086  * @param $class string Class name.
1087  * @return bool True iff $object is a $class
1088  * or a sub-type of $class. 
1089  */
1090 function isa ($object, $class) 
1091 {
1092     $lclass = strtolower($class);
1093
1094     return is_object($object)
1095         && ( get_class($object) == strtolower($lclass)
1096              || is_subclass_of($object, $lclass) );
1097 }
1098
1099 /** Determine whether (possible) object has method.
1100  *
1101  * @param $object mixed Object
1102  * @param $method string Method name
1103  * @return bool True iff $object is an object with has method $method.
1104  */
1105 function can ($object, $method) 
1106 {
1107     return is_object($object) && method_exists($object, strtolower($method));
1108 }
1109
1110 /** Hash a value.
1111  *
1112  * This is used for generating ETags.
1113  */
1114 function hash ($x) {
1115     if (is_scalar($x)) {
1116         return $x;
1117     }
1118     elseif (is_array($x)) {            
1119         ksort($x);
1120         return md5(serialize($x));
1121     }
1122     elseif (is_object($x)) {
1123         return $x->hash();
1124     }
1125     trigger_error("Can't hash $x", E_USER_ERROR);
1126 }
1127
1128     
1129 /**
1130  * Seed the random number generator.
1131  *
1132  * better_srand() ensures the randomizer is seeded only once.
1133  * 
1134  * How random do you want it? See:
1135  * http://www.php.net/manual/en/function.srand.php
1136  * http://www.php.net/manual/en/function.mt-srand.php
1137  */
1138 function better_srand($seed = '') {
1139     static $wascalled = FALSE;
1140     if (!$wascalled) {
1141         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1142         srand($seed);
1143         $wascalled = TRUE;
1144         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1145     }
1146 }
1147
1148 /**
1149  * Recursively count all non-empty elements 
1150  * in array of any dimension or mixed - i.e. 
1151  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1152  * See http://www.php.net/manual/en/function.count.php
1153  */
1154 function count_all($arg) {
1155     // skip if argument is empty
1156     if ($arg) {
1157         //print_r($arg); //debugging
1158         $count = 0;
1159         // not an array, return 1 (base case) 
1160         if(!is_array($arg))
1161             return 1;
1162         // else call recursively for all elements $arg
1163         foreach($arg as $key => $val)
1164             $count += count_all($val);
1165         return $count;
1166     }
1167 }
1168
1169 function isSubPage($pagename) {
1170     return (strstr($pagename, SUBPAGE_SEPARATOR));
1171 }
1172
1173 function subPageSlice($pagename, $pos) {
1174     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1175     $pages = array_slice($pages,$pos,1);
1176     return $pages[0];
1177 }
1178
1179 /**
1180  * Alert
1181  *
1182  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1183  * pop up...)
1184  *
1185  * FIXME:
1186  * This is a hackish and needs to be refactored.  However it would be nice to
1187  * unify all the different methods we use for showing Alerts and Dialogs.
1188  * (E.g. "Page deleted", login form, ...)
1189  */
1190 class Alert {
1191     /** Constructor
1192      *
1193      * @param object $request
1194      * @param mixed $head  Header ("title") for alert box.
1195      * @param mixed $body  The text in the alert box.
1196      * @param hash $buttons  An array mapping button labels to URLs.
1197      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1198      */
1199     function Alert($head, $body, $buttons=false) {
1200         if ($buttons === false)
1201             $buttons = array();
1202
1203         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1204         $this->_buttons = $buttons;
1205     }
1206
1207     /**
1208      * Show the alert box.
1209      */
1210     function show(&$request) {
1211         global $request;
1212
1213         $tokens = $this->_tokens;
1214         $tokens['BUTTONS'] = $this->_getButtons();
1215         
1216         $request->discardOutput();
1217         $tmpl = new Template('dialog', $request, $tokens);
1218         $tmpl->printXML();
1219         $request->finish();
1220     }
1221
1222
1223     function _getButtons() {
1224         global $request;
1225
1226         $buttons = $this->_buttons;
1227         if (!$buttons)
1228             $buttons = array(_("Okay") => $request->getURLtoSelf());
1229         
1230         global $Theme;
1231         foreach ($buttons as $label => $url)
1232             print "$label $url\n";
1233             $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1234         return new XmlContent($out);
1235     }
1236 }
1237
1238                       
1239         
1240 // $Log: not supported by cvs2svn $
1241 // Revision 1.143  2003/02/26 00:10:26  dairiki
1242 // More/better/different checks for bad page names.
1243 //
1244 // Revision 1.142  2003/02/25 22:19:46  dairiki
1245 // Add some sanity checking for pagenames.
1246 //
1247 // Revision 1.141  2003/02/22 20:49:55  dairiki
1248 // Fixes for "Call-time pass by reference has been deprecated" errors.
1249 //
1250 // Revision 1.140  2003/02/21 23:33:29  dairiki
1251 // Set alt="" on the link icon image tags.
1252 // (See SF bug #675141.)
1253 //
1254 // Revision 1.139  2003/02/21 22:16:27  dairiki
1255 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1256 // These have been obsolete for quite awhile (I hope).
1257 //
1258 // Revision 1.138  2003/02/21 04:12:36  dairiki
1259 // WikiPageName: fixes for new cached links.
1260 //
1261 // Alert: new class for displaying alerts.
1262 //
1263 // ExtractWikiPageLinks and friends are now gone.
1264 //
1265 // LinkBracketLink moved to InlineParser.php
1266 //
1267 // Revision 1.137  2003/02/18 23:13:40  dairiki
1268 // Wups again.  Typo fix.
1269 //
1270 // Revision 1.136  2003/02/18 21:52:07  dairiki
1271 // Fix so that one can still link to wiki pages with # in their names.
1272 // (This was made difficult by the introduction of named tags, since
1273 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1274 //
1275 // Now the ~ escape for page names should work: [Page ~#1].
1276 //
1277 // Revision 1.135  2003/02/18 19:17:04  dairiki
1278 // split_pagename():
1279 //     Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1280 //     Cleanup up subpage splitting code.
1281 //
1282 // Revision 1.134  2003/02/16 19:44:20  dairiki
1283 // New function hash().  This is a helper, primarily for generating
1284 // HTTP ETags.
1285 //
1286 // Revision 1.133  2003/02/16 04:50:09  dairiki
1287 // New functions:
1288 // Rfc1123DateTime(), ParseRfc1123DateTime()
1289 // for converting unix timestamps to and from strings.
1290 //
1291 // These functions produce and grok the time strings
1292 // in the format specified by RFC 2616 for use in HTTP headers
1293 // (like Last-Modified).
1294 //
1295 // Revision 1.132  2003/01/04 22:19:43  carstenklapp
1296 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1297 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1298 //
1299
1300 // (c-file-style: "gnu")
1301 // Local Variables:
1302 // mode: php
1303 // tab-width: 8
1304 // c-basic-offset: 4
1305 // c-hanging-comment-ender-p: nil
1306 // indent-tabs-mode: nil
1307 // End:   
1308 ?>