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