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