]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Added some PHPDoc comments
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.127 2002-09-24 01:12:28 zorloc 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     MakeWikiForm ($pagename, $args, $class, $button_text)
11     SplitQueryArgs ($query_args)
12     LinkPhpwikiURL($url, $text)
13     LinkBracketLink($bracketlink)
14     ExtractWikiPageLinks($content)
15     ConvertOldMarkup($content)
16     
17     class Stack { push($item), pop(), cnt(), top() }
18
19     split_pagename ($page)
20     NoSuchRevision ($request, $page, $version)
21     TimezoneOffset ($time, $no_colon)
22     Iso8601DateTime ($time)
23     Rfc2822DateTime ($time)
24     CTime ($time)
25     __printf ($fmt)
26     __sprintf ($fmt)
27     __vsprintf ($fmt, $args)
28     better_srand($seed = '')
29     count_all($arg)
30     isSubPage($pagename)
31     subPageSlice($pagename, $pos)
32     explodePageList($input, $perm = false)
33
34   function: LinkInterWikiLink($link, $linktext)
35   moved to: lib/interwiki.php
36   function: linkExistingWikiWord($wikiword, $linktext, $version)
37   moved to: lib/Theme.php
38   function: LinkUnknownWikiWord($wikiword, $linktext)
39   moved to: lib/Theme.php
40   function: UpdateRecentChanges($dbi, $pagename, $isnewpage) 
41   gone see: lib/plugin/RecentChanges.php
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->fullPagename;
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 * @param string $protocol_or_url URL or protocol to determine which icon to use.
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 * Determines if the url passed to function is safe, by detecting if the characters
159 * '<', '>', or '"' are present.
160 * @param string $url URL to check for unsafe characters.
161 * @return boolean True if same, false else.
162 */
163 function IsSafeURL($url) {
164     return !ereg('[<>"]', $url);
165 }
166
167 /**
168 * Generates an HtmlElement object to store data for a link.
169 * @param string $url URL that the link will point to.
170 * @param string $linktext Text to be displayed as link.
171 * @return HtmlElement HtmlElement object that contains data to construct an html link.
172 */
173 function LinkURL($url, $linktext = '') {
174     // FIXME: Is this needed (or sufficient?)
175     if(! IsSafeURL($url)) {
176         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
177                                      _("BAD URL -- remove all of <, >, \"")));
178     }
179     else {
180         if (!$linktext)
181             $linktext = preg_replace("/mailto:/A", "", $url);
182         
183         $link = HTML::a(array('href' => $url),
184                         IconForLink($url), $linktext);
185         
186     }
187     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
188     return $link;
189 }
190
191
192 function LinkImage($url, $alt = false) {
193     // FIXME: Is this needed (or sufficient?)
194     if(! IsSafeURL($url)) {
195         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
196                                      _("BAD URL -- remove all of <, >, \"")));
197     }
198     else {
199         if (empty($alt))
200             $alt = $url;
201         $link = HTML::img(array('src' => $url, 'alt' => $alt));
202     }
203     $link->setAttr('class', 'inlineimage');
204     return $link;
205 }
206
207
208
209 class Stack {
210     var $items = array();
211     var $size = 0;
212     
213     function push($item) {
214         $this->items[$this->size] = $item;
215         $this->size++;
216         return true;
217     }  
218     
219     function pop() {
220         if ($this->size == 0) {
221             return false; // stack is empty
222         }  
223         $this->size--;
224         return $this->items[$this->size];
225     }  
226     
227     function cnt() {
228         return $this->size;
229     }  
230     
231     function top() {
232         if($this->size)
233             return $this->items[$this->size - 1];
234         else
235             return '';
236     }
237     
238 }  
239 // end class definition
240
241
242 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
243     // HACK: so as to not completely break old PhpWikiAdministration pages.
244     trigger_error("MagicPhpWikiURL forms are no longer supported.  "
245                   . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
246
247     global $request;
248     $loader = new WikiPluginLoader;
249     @$action = (string)$args['action'];
250     return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
251 }
252
253 function SplitQueryArgs ($query_args = '') 
254 {
255     $split_args = split('&', $query_args);
256     $args = array();
257     while (list($key, $val) = each($split_args))
258         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
259             $args[$m[1]] = $m[2];
260     return $args;
261 }
262
263 function LinkPhpwikiURL($url, $text = '') {
264     $args = array();
265     
266     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
267         return HTML::strong(array('class' => 'rawurl'),
268                             HTML::u(array('class' => 'baduri'),
269                                     _("BAD phpwiki: URL")));
270     }
271
272     if ($m[1])
273         $pagename = urldecode($m[1]);
274     $qargs = $m[2];
275     
276     if (empty($pagename) &&
277         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
278         // Convert old style links (to not break diff links in
279         // RecentChanges).
280         $pagename = urldecode($m[2]);
281         $args = array("action" => $m[1]);
282     }
283     else {
284         $args = SplitQueryArgs($qargs);
285     }
286
287     if (empty($pagename))
288         $pagename = $GLOBALS['request']->getArg('pagename');
289
290     if (isset($args['action']) && $args['action'] == 'browse')
291         unset($args['action']);
292     
293     /*FIXME:
294       if (empty($args['action']))
295       $class = 'wikilink';
296       else if (is_safe_action($args['action']))
297       $class = 'wikiaction';
298     */
299     if (empty($args['action']) || is_safe_action($args['action']))
300         $class = 'wikiaction';
301     else {
302         // Don't allow administrative links on unlocked pages.
303         $page = $GLOBALS['request']->getPage();
304         if (!$page->get('locked'))
305             return HTML::span(array('class' => 'wikiunsafe'),
306                               HTML::u(_("Lock page to enable link")));
307         $class = 'wikiadmin';
308     }
309     
310     // FIXME: ug, don't like this
311     if (preg_match('/=\d*\(/', $qargs))
312         return MakeWikiForm($pagename, $args, $class, $text);
313     if (!$text)
314         $text = HTML::span(array('class' => 'rawurl'), $url);
315
316     return HTML::a(array('href'  => WikiURL($pagename, $args),
317                          'class' => $class),
318                    $text);
319 }
320
321 /**
322  * A class to assist in parsing wiki pagenames.
323  *
324  * Now with subpages and anchors, parsing and passing around
325  * pagenames is more complicated.  This should help.
326  */
327 class WikiPagename
328 {
329     /** Short name for page.
330      *
331      * This is the value of $name passed to the constructor.
332      */
333     var $shortName;
334
335     /** The full page name.
336      *
337      * This is the full name of the page (without anchor).
338      */
339     var $fullPagename;
340     
341     /** The anchor.
342      *
343      * This is the referenced anchor within the page, or the empty string.
344      */
345     var $anchor;
346     
347     /** Constructor
348      *
349      * @param WikiRequest $request
350      * @param string $name Page name.
351      * This can be a relative subpage name (like '/SubPage'), and can also
352      * include an anchor (e.g. 'SandBox#anchorname' or just '#anchor').
353      */
354     function WikiPageName($request, $name) {
355         $this->shortName = $name;
356
357         if ($name[0] == SUBPAGE_SEPARATOR or $name[0] == '#')
358             $name = $request->getArg('pagename') . $name;
359
360         if (strstr($name, '#')) {
361             list($this->fullPagename, $this->anchor) = split('#', $name, 2);
362         }
363         else {
364             $this->fullPagename = $name;
365             $this->anchor = '';
366         }
367         
368
369         $dbi = $request->getDbh();
370         $this->_exists = $dbi->isWikiPage($this->fullPagename);
371     }
372
373     /**
374      * Determine whether page 'exists'.
375      *
376      * @return boolean True if page exists with non-default content.
377      */
378     function exists() {
379         return $this->_exists;
380     }
381 }
382
383 function LinkBracketLink($bracketlink) {
384     global $request, $AllowedProtocols, $InlineImages;
385
386     include_once("lib/interwiki.php");
387     $intermap = InterWikiMap::GetMap($request);
388     
389     // $bracketlink will start and end with brackets; in between will
390     // be either a page name, a URL or both separated by a pipe.
391     
392     // strip brackets and leading space
393     preg_match('/(\#?) \[\s* (?: ([^|]*?) \s* (\|) )? \s* (.+?) \s*\]/x', $bracketlink, $matches);
394     list (, $hash, $label, $bar, $link) = $matches;
395
396     // if label looks like a url to an image, we want an image link.
397     if (preg_match("/($InlineImages)$/i", $label)) {
398         $imgurl = $label;
399         if (! preg_match("#^($AllowedProtocols):#", $imgurl)) {
400             // linkname like 'images/next.gif'.
401             global $Theme;
402             $imgurl = $Theme->getImageURL($linkname);
403         }
404         $label = LinkImage($imgurl, $link);
405     }
406
407     if ($hash) {
408         // It's an anchor, not a link...
409         $id = MangleXmlIdentifier($link);
410         return HTML::a(array('name' => $id, 'id' => $id),
411                        $bar ? $label : $link);
412     }
413
414     $wikipage = new WikiPageName($request, $link);
415     if ($wikipage->exists()) {
416         return WikiLink($wikipage, 'known', $label);
417     }
418     elseif (preg_match("#^($AllowedProtocols):#", $link)) {
419         // if it's an image, embed it; otherwise, it's a regular link
420         if (preg_match("/($InlineImages)$/i", $link))
421             // no image link, just the src. see [img|link] above
422             return LinkImage($link, $label);
423         else
424             return LinkURL($link, $label);
425     }
426     elseif (preg_match("/^phpwiki:/", $link))
427         return LinkPhpwikiURL($link, $label);
428     elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link))
429         return $intermap->link($link, $label);
430     else {
431         return WikiLink($wikipage, 'unknown', $label);
432     }
433 }
434
435 /**
436  * Extract internal links from wiki page.
437  *
438  * @param mixed $content The raw wiki-text, either as
439  * an array of lines or as one big string.
440  *
441  * @return array List of the names of pages linked to.
442  */
443 function ExtractWikiPageLinks($content) {
444     list ($wikilinks,) = ExtractLinks($content);
445     return $wikilinks;
446 }      
447
448 /**
449  * Extract external links from a wiki page.
450  *
451  * @param mixed $content The raw wiki-text, either as
452  * an array of lines or as one big string.
453  *
454  * @return array List of the names of pages linked to.
455  */
456 function ExtractExternalLinks($content) {
457     list (, $urls) = ExtractLinks($content);
458     return $urls;
459 }      
460
461 /**
462  * Extract links from wiki page.
463  *
464  * FIXME: this should be done by the transform code.
465  *
466  * @param mixed $content The raw wiki-text, either as
467  * an array of lines or as one big string.
468  *
469  * @return array List of two arrays.  The first contains
470  * the internal links (names of pages linked to), the second
471  * contains external URLs linked to.
472  */
473 function ExtractLinks($content) {
474     include_once('lib/interwiki.php');
475     global $request, $WikiNameRegexp, $AllowedProtocols;
476     
477     if (is_string($content))
478         $content = explode("\n", $content);
479     
480     $wikilinks = array();
481     $urls = array();
482     
483     foreach ($content as $line) {
484         // remove plugin code
485         $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
486         // remove escaped '['
487         $line = str_replace('[[', ' ', $line);
488         // remove footnotes
489         $line = preg_replace('/\[\d+\]/', ' ', $line);
490         
491         // bracket links (only type wiki-* is of interest)
492         $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
493                                           $line, $brktlinks);
494         for ($i = 0; $i < $numBracketLinks; $i++) {
495             $link = LinkBracketLink($brktlinks[0][$i]);
496             $class = $link->getAttr('class');
497             if (preg_match('/^(named-)?wiki(unknown)?$/', $class)) {
498                 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
499                     $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
500                 } else {
501                     $wikilinks[$brktlinks[2][$i]] = 1;
502                 }
503             }
504             elseif (preg_match('/^(namedurl|rawurl|(named-)?interwiki)$/', $class)) {
505                 $urls[$brktlinks[2][$i]] = 1;
506             }
507             $line = str_replace($brktlinks[0][$i], '', $line);
508         }
509         
510         // Raw URLs
511         preg_match_all("/!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]/",
512                        $line, $link);
513         foreach ($link[0] as $url) {
514             if ($url[0] <> '!') {
515                 $urls[$url] = 1;
516             }
517             $line = str_replace($url, '', $line);
518         }
519
520         // Interwiki links
521         $map = InterWikiMap::GetMap($request);
522         $regexp = pcre_fix_posix_classes("!?(?<![[:alnum:]])") 
523             . $map->getRegexp() . ":[^\\s.,;?()]+";
524         preg_match_all("/$regexp/", $line, $link);
525         foreach ($link[0] as $interlink) {
526             if ($interlink[0] <> '!') {
527                 $link = $map->link($interlink);
528                 $urls[$link->getAttr('href')] = 1;
529             }
530             $line = str_replace($interlink, '', $line);
531         }
532
533         // BumpyText old-style wiki links
534         if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
535             for ($i = 0; isset($link[0][$i]); $i++) {
536                 if($link[0][$i][0] <> '!') {
537                     if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
538                         $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
539                     } else {
540                         $wikilinks[$link[0][$i]] = 1;
541                     }
542                 }
543             }
544         }
545     }
546     return array(array_keys($wikilinks), array_keys($urls));
547 }      
548
549
550 /**
551  * Convert old page markup to new-style markup.
552  *
553  * @param string $text Old-style wiki markup.
554  *
555  * @param string $markup_type
556  * One of: <dl>
557  * <dt><code>"block"</code>  <dd>Convert all markup.
558  * <dt><code>"inline"</code> <dd>Convert only inline markup.
559  * <dt><code>"links"</code>  <dd>Convert only link markup.
560  * </dl>
561  *
562  * @return string New-style wiki markup.
563  *
564  * @bugs Footnotes don't work quite as before (esp if there are
565  *   multiple references to the same footnote.  But close enough,
566  *   probably for now....
567  */
568 function ConvertOldMarkup ($text, $markup_type = "block") {
569
570     static $subs;
571     
572     if (empty($subs)) {
573         /*****************************************************************
574          * Conversions for inline markup:
575          */
576
577         // escape tilde's
578         $orig[] = '/~/';
579         $repl[] = '~~';
580
581         // escape escaped brackets
582         $orig[] = '/\[\[/';
583         $repl[] = '~[';
584
585         // change ! escapes to ~'s.
586         global $AllowedProtocols, $WikiNameRegexp, $request;
587         include_once('lib/interwiki.php');
588         $map = InterWikiMap::GetMap($request);
589         $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
590         $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
591         $bang_esc[] = $WikiNameRegexp;
592         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
593         $repl[] = '~\\1';
594
595         $subs["links"] = array($orig, $repl);
596
597         // Escape '<'s
598         //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
599         //$repl[] = '~<';
600         
601         // Convert footnote references.
602         $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
603         $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
604
605         // Convert old style emphases to HTML style emphasis.
606         $orig[] = '/__(.*?)__/';
607         $repl[] = '<strong>\\1</strong>';
608         $orig[] = "/''(.*?)''/";
609         $repl[] = '<em>\\1</em>';
610
611
612         $subs["inline"] = array($orig, $repl);
613
614         // Escape nestled markup. (two versions: inline & block)
615         $subs["inline"][0][] = '/^(?<=^|\s)[=_*](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
616         $subs["inline"][1][] = '/~\\0/';
617         $orig[] = '/^.*?(?:(?<=^|\s)[=_*](?=\S)|(?<=\S)[=_*](?=\s|$)).*$/me';
618         $repl[] = "_EscapeNestledMarkup('\\0')";
619             
620         /*****************************************************************
621          * Conversions for block markup
622          */
623         // convert indented blocks to <pre></pre>.
624         $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
625         $repl[] = "<pre>\n\\0</pre>\n";
626
627         // convert tables
628         $orig[] = '/(?:^\|.*\n)+/m';
629         $repl[] = "<?plugin OldStyleTable\n\\0?>\n";
630
631         // convert lists
632         $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
633         $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
634
635         // convert footnote definitions
636         $orig[] = '/^\[\s*(\d+)\s*\]/m';
637         $repl[] = '#[|ftnt_\\1]~[[\\1|#ftnt_ref_\\1]~]';
638
639         // in old markup headings only allowed at beginning of line
640         //$orig[] = '/(?<=[^!])!/';
641         $orig[] = '/([^\n!])!/';
642         $repl[] = '\\1~!';
643
644         $subs["block"] = array($orig, $repl);
645     }
646     
647     list ($orig, $repl) = $subs[$markup_type];
648     if ($markup_type == "block" and substr($text,-1) != "\n")
649         $text .= "\n";
650     return preg_replace($orig, $repl, $text);
651 }
652
653 function _ConvertOldListMarkup ($ind, $bullet) {
654     $indent = str_repeat('     ', strlen($ind));
655     if ($bullet[0] == ';') {
656         //$term = ltrim(substr($bullet, 1));
657         //return $indent . $term . "\n" . $indent . '     ';
658         return $ind . $bullet;
659     }
660     else
661         return $indent . $bullet . ' ';
662 }
663
664 function _EscapeNestledMarkup ($line) {
665     if (!preg_match('/^<\?plugin.*\?>/', $line))
666         $line = preg_replace('/[=_]|(?<!^|[*#;])\*/', '~\\0', $line);
667     return $line;
668 }
669
670
671 /**
672  * Expand tabs in string.
673  *
674  * Converts all tabs to (the appropriate number of) spaces.
675  *
676  * @param string $str
677  * @param integer $tab_width
678  * @return string
679  */
680 function expand_tabs($str, $tab_width = 8) {
681     $split = split("\t", $str);
682     $tail = array_pop($split);
683     $expanded = "\n";
684     foreach ($split as $hunk) {
685         $expanded .= $hunk;
686         $pos = strlen(strrchr($expanded, "\n")) - 1;
687         $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
688     }
689     return substr($expanded, 1) . $tail;
690 }
691
692 /**
693  * Split WikiWords in page names.
694  *
695  * It has been deemed useful to split WikiWords (into "Wiki Words") in
696  * places like page titles. This is rumored to help search engines
697  * quite a bit.
698  *
699  * @param $page string The page name.
700  *
701  * @return string The split name.
702  */
703 function split_pagename ($page) {
704     
705     if (preg_match("/\s/", $page))
706         return $page;           // Already split --- don't split any more.
707     
708     // FIXME: this algorithm is Anglo-centric.
709     static $RE;
710     if (!isset($RE)) {
711         // This mess splits between a lower-case letter followed by
712         // either an upper-case or a numeral; except that it wont
713         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
714         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
715         // This the single-letter words 'I' and 'A' from any following
716         // capitalized words.
717         $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
718         // Split numerals from following letters.
719         $RE[] = '/(\d)([[:alpha:]])/';
720         
721         foreach ($RE as $key => $val)
722             $RE[$key] = pcre_fix_posix_classes($val);
723     }
724     if (isSubPage($page)) {
725         // FIXME: is this needed?
726         $pages = explode(SUBPAGE_SEPARATOR,$page);
727         $new_page = $pages[0] ? split_pagename($pages[0]) : '';
728         for ($i=1; $i < sizeof($pages); $i++) {
729             $new_page .=  (SUBPAGE_SEPARATOR . ($pages[$i] ? split_pagename($pages[$i]) : ''));
730         }
731         return $new_page;
732     } else {
733         foreach ($RE as $regexp) {
734             $page = preg_replace($regexp, '\\1 \\2', $page);
735         }
736         return $page;
737     }
738 }
739
740 function NoSuchRevision (&$request, $page, $version) {
741     $html = HTML(HTML::h2(_("Revision Not Found")),
742                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
743                              $version, WikiLink($page, 'auto'))));
744     include_once('lib/Template.php');
745     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
746     $request->finish();
747 }
748
749
750 /**
751  * Get time offset for local time zone.
752  *
753  * @param $time time_t Get offset for this time. Default: now.
754  * @param $no_colon boolean Don't put colon between hours and minutes.
755  * @return string Offset as a string in the format +HH:MM.
756  */
757 function TimezoneOffset ($time = false, $no_colon = false) {
758     if ($time === false)
759         $time = time();
760     $secs = date('Z', $time);
761
762     if ($secs < 0) {
763         $sign = '-';
764         $secs = -$secs;
765     }
766     else {
767         $sign = '+';
768     }
769     $colon = $no_colon ? '' : ':';
770     $mins = intval(($secs + 30) / 60);
771     return sprintf("%s%02d%s%02d",
772                    $sign, $mins / 60, $colon, $mins % 60);
773 }
774
775
776 /**
777  * Format time in ISO-8601 format.
778  *
779  * @param $time time_t Time.  Default: now.
780  * @return string Date and time in ISO-8601 format.
781  */
782 function Iso8601DateTime ($time = false) {
783     if ($time === false)
784         $time = time();
785     $tzoff = TimezoneOffset($time);
786     $date  = date('Y-m-d', $time);
787     $time  = date('H:i:s', $time);
788     return $date . 'T' . $time . $tzoff;
789 }
790
791 /**
792  * Format time in RFC-2822 format.
793  *
794  * @param $time time_t Time.  Default: now.
795  * @return string Date and time in RFC-2822 format.
796  */
797 function Rfc2822DateTime ($time = false) {
798     if ($time === false)
799         $time = time();
800     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
801 }
802
803 /**
804  * Format time to standard 'ctime' format.
805  *
806  * @param $time time_t Time.  Default: now.
807  * @return string Date and time.
808  */
809 function CTime ($time = false)
810 {
811     if ($time === false)
812         $time = time();
813     return date("D M j H:i:s Y", $time);
814 }
815
816
817
818 /**
819  * Internationalized printf.
820  *
821  * This is essentially the same as PHP's built-in printf
822  * with the following exceptions:
823  * <ol>
824  * <li> It passes the format string through gettext().
825  * <li> It supports the argument reordering extensions.
826  * </ol>
827  *
828  * Example:
829  *
830  * In php code, use:
831  * <pre>
832  *    __printf("Differences between versions %s and %s of %s",
833  *             $new_link, $old_link, $page_link);
834  * </pre>
835  *
836  * Then in locale/po/de.po, one can reorder the printf arguments:
837  *
838  * <pre>
839  *    msgid "Differences between %s and %s of %s."
840  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
841  * </pre>
842  *
843  * (Note that while PHP tries to expand $vars within double-quotes,
844  * the values in msgstr undergo no such expansion, so the '$'s
845  * okay...)
846  *
847  * One shouldn't use reordered arguments in the default format string.
848  * Backslashes in the default string would be necessary to escape the
849  * '$'s, and they'll cause all kinds of trouble....
850  */ 
851 function __printf ($fmt) {
852     $args = func_get_args();
853     array_shift($args);
854     echo __vsprintf($fmt, $args);
855 }
856
857 /**
858  * Internationalized sprintf.
859  *
860  * This is essentially the same as PHP's built-in printf with the
861  * following exceptions:
862  *
863  * <ol>
864  * <li> It passes the format string through gettext().
865  * <li> It supports the argument reordering extensions.
866  * </ol>
867  *
868  * @see __printf
869  */ 
870 function __sprintf ($fmt) {
871     $args = func_get_args();
872     array_shift($args);
873     return __vsprintf($fmt, $args);
874 }
875
876 /**
877  * Internationalized vsprintf.
878  *
879  * This is essentially the same as PHP's built-in printf with the
880  * following exceptions:
881  *
882  * <ol>
883  * <li> It passes the format string through gettext().
884  * <li> It supports the argument reordering extensions.
885  * </ol>
886  *
887  * @see __printf
888  */ 
889 function __vsprintf ($fmt, $args) {
890     $fmt = gettext($fmt);
891     // PHP's sprintf doesn't support variable with specifiers,
892     // like sprintf("%*s", 10, "x"); --- so we won't either.
893     
894     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
895         // Format string has '%2$s' style argument reordering.
896         // PHP doesn't support this.
897         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
898             // literal variable name substitution only to keep locale
899             // strings uncluttered
900             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
901                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
902         
903         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
904         $newargs = array();
905         
906         // Reorder arguments appropriately.
907         foreach($m[1] as $argnum) {
908             if ($argnum < 1 || $argnum > count($args))
909                 trigger_error(sprintf(_("%s: argument index out of range"), 
910                                       $argnum), E_USER_WARNING);
911             $newargs[] = $args[$argnum - 1];
912         }
913         $args = $newargs;
914     }
915     
916     // Not all PHP's have vsprintf, so...
917     array_unshift($args, $fmt);
918     return call_user_func_array('sprintf', $args);
919 }
920
921
922 class fileSet {
923     /**
924      * Build an array in $this->_fileList of files from $dirname.
925      * Subdirectories are not traversed.
926      *
927      * (This was a function LoadDir in lib/loadsave.php)
928      * See also http://www.php.net/manual/en/function.readdir.php
929      */
930     function getFiles() {
931         return $this->_fileList;
932     }
933
934     function _filenameSelector($filename) {
935         if (! $this->_pattern)
936             return true;
937         else {
938             return glob_match ($this->_pattern, $filename, $this->_case);
939         }
940     }
941
942     function fileSet($directory, $filepattern = false) {
943         $this->_fileList = array();
944         $this->_pattern = $filepattern;
945         $this->_case = !isWindows();
946         $this->_pathsep = '/';
947
948         if (empty($directory)) {
949             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
950                           E_USER_NOTICE);
951             return; // early return
952         }
953
954         @ $dir_handle = opendir($dir=$directory);
955         if (empty($dir_handle)) {
956             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
957                                   $dir), E_USER_NOTICE);
958             return; // early return
959         }
960
961         while ($filename = readdir($dir_handle)) {
962             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
963                 continue;
964             if ($this->_filenameSelector($filename)) {
965                 array_push($this->_fileList, "$filename");
966                 //trigger_error(sprintf(_("found file %s"), $filename),
967                 //                      E_USER_NOTICE); //debugging
968             }
969         }
970         closedir($dir_handle);
971     }
972 };
973
974 // File globbing
975
976 // expands a list containing regex's to its matching entries
977 class ListRegexExpand {
978     var $match, $list, $index, $case_sensitive;
979     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
980         $this->match = str_replace('/','\/',$match);
981         $this->list = &$list;
982         $this->case_sensitive = $case_sensitive;        
983     }
984     function listMatchCallback ($item, $key) {
985         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
986             unset($this->list[$this->index]);
987             $this->list[] = $item;
988         }
989     }
990     function expandRegex ($index, &$pages) {
991         $this->index = $index;
992         array_walk($pages, array($this, 'listMatchCallback'));
993         return $this->list;
994     }
995 }
996
997 // convert fileglob to regex style
998 function glob_to_pcre ($glob) {
999     $re = preg_replace('/\./', '\\.', $glob);
1000     $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1001     if (!preg_match('/^[\?\*]/',$glob))
1002         $re = '^' . $re;
1003     if (!preg_match('/[\?\*]$/',$glob))
1004         $re = $re . '$';
1005     return $re;
1006 }
1007
1008 function glob_match ($glob, $against, $case_sensitive = true) {
1009     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1010 }
1011
1012 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1013     $list = explode(',',$input);
1014     // expand wildcards from list of $allnames
1015     if (preg_match('/[\?\*]/',$input)) {
1016         for ($i = 0; $i <= sizeof($list); $i++) {
1017             $f = $list[$i];
1018             if (preg_match('/[\?\*]/',$f)) {
1019                 reset($allnames);
1020                 $expand = new ListRegexExpand(&$list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1021                 $expand->expandRegex($i, &$allnames);
1022             }
1023         }
1024     }
1025     return $list;
1026 }
1027
1028 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1029
1030 function explodePageList($input, $perm = false) {
1031     // expand wildcards from list of all pages
1032     if (preg_match('/[\?\*]/',$input)) {
1033         $dbi = $GLOBALS['request']->_dbi;
1034         $allPagehandles = $dbi->getAllPages($perm);
1035         while ($pagehandle = $allPagehandles->next()) {
1036             $allPages[] = $pagehandle->getName();
1037         }
1038         return explodeList($input, &$allPages);
1039     } else {
1040         return explode(',',$input);
1041     }
1042 }
1043
1044 // Class introspections
1045
1046 /** Determine whether object is of a specified type.
1047  *
1048  * @param $object object An object.
1049  * @param $class string Class name.
1050  * @return bool True iff $object is a $class
1051  * or a sub-type of $class. 
1052  */
1053 function isa ($object, $class) 
1054 {
1055     $lclass = strtolower($class);
1056
1057     return is_object($object)
1058         && ( get_class($object) == strtolower($lclass)
1059              || is_subclass_of($object, $lclass) );
1060 }
1061
1062 /** Determine whether (possible) object has method.
1063  *
1064  * @param $object mixed Object
1065  * @param $method string Method name
1066  * @return bool True iff $object is an object with has method $method.
1067  */
1068 function can ($object, $method) 
1069 {
1070     return is_object($object) && method_exists($object, strtolower($method));
1071 }
1072
1073 /**
1074  * Seed the random number generator.
1075  *
1076  * better_srand() ensures the randomizer is seeded only once.
1077  * 
1078  * How random do you want it? See:
1079  * http://www.php.net/manual/en/function.srand.php
1080  * http://www.php.net/manual/en/function.mt-srand.php
1081  */
1082 function better_srand($seed = '') {
1083     static $wascalled = FALSE;
1084     if (!$wascalled) {
1085         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1086         srand($seed);
1087         $wascalled = TRUE;
1088         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1089     }
1090 }
1091
1092 /**
1093  * Recursively count all non-empty elements 
1094  * in array of any dimension or mixed - i.e. 
1095  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1096  * See http://www.php.net/manual/en/function.count.php
1097  */
1098 function count_all($arg) {
1099     // skip if argument is empty
1100     if ($arg) {
1101         //print_r($arg); //debugging
1102         $count = 0;
1103         // not an array, return 1 (base case) 
1104         if(!is_array($arg))
1105             return 1;
1106         // else call recursively for all elements $arg
1107         foreach($arg as $key => $val)
1108             $count += count_all($val);
1109         return $count;
1110     }
1111 }
1112
1113 function isSubPage($pagename) {
1114     return (strstr($pagename, SUBPAGE_SEPARATOR));
1115 }
1116
1117 function subPageSlice($pagename, $pos) {
1118     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1119     $pages = array_slice($pages,$pos,1);
1120     return $pages[0];
1121 }
1122
1123
1124 // (c-file-style: "gnu")
1125 // Local Variables:
1126 // mode: php
1127 // tab-width: 8
1128 // c-basic-offset: 4
1129 // c-hanging-comment-ender-p: nil
1130 // indent-tabs-mode: nil
1131 // End:   
1132 ?>