]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
I was starting to hack together a counter part to ExtractWikiPageLinks()
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.120 2002-09-15 05:45:09 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     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 function WikiURL($pagename, $args = '', $get_abs_url = false) {
46     if (is_object($pagename)) {
47         if (isa($pagename, 'WikiDB_Page')) {
48             $pagename = $pagename->getName();
49         }
50         elseif (isa($pagename, 'WikiDB_PageRevision')) {
51             $page = $pagename->getPage();
52             $args['version'] = $pagename->getVersion();
53             $pagename = $page->getName();
54         }
55     }
56     
57     if (is_array($args)) {
58         $enc_args = array();
59         foreach  ($args as $key => $val) {
60             if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
61               $enc_args[] = urlencode($key) . '=' . urlencode($val);
62         }
63         $args = join('&', $enc_args);
64     }
65
66     if (USE_PATH_INFO) {
67         $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
68         $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
69         if ($args)
70             $url .= "?$args";
71     }
72     else {
73         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
74         $url .= "?pagename=" . rawurlencode($pagename);
75         if ($args)
76             $url .= "&$args";
77     }
78     return $url;
79 }
80
81 function IconForLink($protocol_or_url) {
82     global $Theme;
83     if ($filename_suffix = false) {
84         // display apache style icon for file type instead of protocol icon
85         // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
86         // - document: html, htm, text, txt, rtf, pdf, doc
87         // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
88         // - audio: mp3,mp2,aiff,aif,au
89         // - multimedia: mpeg,mpg,mov,qt
90     } else {
91         list ($proto) = explode(':', $protocol_or_url, 2);
92         $src = $Theme->getLinkIconURL($proto);
93         if ($src)
94             return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
95         else
96             return false;
97     }
98 }
99
100 function LinkURL($url, $linktext = '') {
101     // FIXME: Is this needed (or sufficient?)
102     if(ereg("[<>\"]", $url)) {
103         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
104                                      _("BAD URL -- remove all of <, >, \"")));
105     }
106     else {
107         if (!$linktext)
108             $linktext = preg_replace("/mailto:/A", "", $url);
109         
110         $link = HTML::a(array('href' => $url),
111                         IconForLink($url), $linktext);
112         
113     }
114     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
115     return $link;
116 }
117
118
119 function LinkImage($url, $alt = false) {
120     // FIXME: Is this needed (or sufficient?)
121     if(ereg("[<>\"]", $url)) {
122         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
123                                      _("BAD URL -- remove all of <, >, \"")));
124     }
125     else {
126         if (empty($alt))
127             $alt = $url;
128         $link = HTML::img(array('src' => $url, 'alt' => $alt));
129     }
130     $link->setAttr('class', 'inlineimage');
131     return $link;
132 }
133
134
135
136 class Stack {
137     var $items = array();
138     var $size = 0;
139     
140     function push($item) {
141         $this->items[$this->size] = $item;
142         $this->size++;
143         return true;
144     }  
145     
146     function pop() {
147         if ($this->size == 0) {
148             return false; // stack is empty
149         }  
150         $this->size--;
151         return $this->items[$this->size];
152     }  
153     
154     function cnt() {
155         return $this->size;
156     }  
157     
158     function top() {
159         if($this->size)
160             return $this->items[$this->size - 1];
161         else
162             return '';
163     }
164     
165 }  
166 // end class definition
167
168
169 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
170     // HACK: so as to not completely break old PhpWikiAdministration pages.
171     trigger_error("MagicPhpWikiURL forms are no longer supported.  "
172                   . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
173
174     global $request;
175     $loader = new WikiPluginLoader;
176     @$action = (string)$args['action'];
177     return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
178 }
179
180 function SplitQueryArgs ($query_args = '') 
181 {
182     $split_args = split('&', $query_args);
183     $args = array();
184     while (list($key, $val) = each($split_args))
185         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
186             $args[$m[1]] = $m[2];
187     return $args;
188 }
189
190 function LinkPhpwikiURL($url, $text = '') {
191     $args = array();
192     
193     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
194         return HTML::strong(array('class' => 'rawurl'),
195                             HTML::u(array('class' => 'baduri'),
196                                     _("BAD phpwiki: URL")));
197     }
198
199     if ($m[1])
200         $pagename = urldecode($m[1]);
201     $qargs = $m[2];
202     
203     if (empty($pagename) &&
204         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
205         // Convert old style links (to not break diff links in
206         // RecentChanges).
207         $pagename = urldecode($m[2]);
208         $args = array("action" => $m[1]);
209     }
210     else {
211         $args = SplitQueryArgs($qargs);
212     }
213
214     if (empty($pagename))
215         $pagename = $GLOBALS['request']->getArg('pagename');
216
217     if (isset($args['action']) && $args['action'] == 'browse')
218         unset($args['action']);
219     
220     /*FIXME:
221       if (empty($args['action']))
222       $class = 'wikilink';
223       else if (is_safe_action($args['action']))
224       $class = 'wikiaction';
225     */
226     if (empty($args['action']) || is_safe_action($args['action']))
227         $class = 'wikiaction';
228     else {
229         // Don't allow administrative links on unlocked pages.
230         $page = $GLOBALS['request']->getPage();
231         if (!$page->get('locked'))
232             return HTML::span(array('class' => 'wikiunsafe'),
233                               HTML::u(_("Lock page to enable link")));
234         $class = 'wikiadmin';
235     }
236     
237     // FIXME: ug, don't like this
238     if (preg_match('/=\d*\(/', $qargs))
239         return MakeWikiForm($pagename, $args, $class, $text);
240     if (!$text)
241         $text = HTML::span(array('class' => 'rawurl'), $url);
242
243     return HTML::a(array('href'  => WikiURL($pagename, $args),
244                          'class' => $class),
245                    $text);
246 }
247
248 function LinkBracketLink($bracketlink) {
249     global $request, $AllowedProtocols, $InlineImages;
250
251     include_once("lib/interwiki.php");
252     $intermap = InterWikiMap::GetMap($request);
253     
254     // $bracketlink will start and end with brackets; in between will
255     // be either a page name, a URL or both separated by a pipe.
256     
257     // strip brackets and leading space
258     preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
259     // match the contents 
260     preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
261     
262     if (isset($matches[3])) {
263         // named link of the form  "[some link name | http://blippy.com/]"
264         $URL = trim($matches[3]);
265         $linkname = trim($matches[1]);
266     } else {
267         // unnamed link of the form "[http://blippy.com/] or [wiki page]"
268         $URL = trim($matches[1]);
269         $linkname = false;
270     }
271
272     $dbi = $request->getDbh();
273     if (substr($URL,0,1) == SUBPAGE_SEPARATOR) { // relative link to page below
274         if (!$linkname) $linkname = $URL;
275         $URL = $request->getArg('pagename') . $URL;
276     }
277     if ($dbi->isWikiPage($URL)) {
278         // if it's an image, it's an named image link [img|link]
279         if (preg_match("/($InlineImages)$/i", $linkname))
280             if (preg_match("#^($AllowedProtocols):#", $URL)) {
281                 return WikiLink($URL, 'known', LinkImage($linkname,$URL));
282             } 
283             else {
284                 // linkname like 'images/next.gif'.
285                 global $Theme;
286                 return WikiLink($URL, 'known', LinkImage($Theme->getImageURL($linkname),$URL));
287             }
288         else {
289             return WikiLink($URL, 'known', $linkname);
290         }
291     }
292     elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
293         // if it's an image, embed it; otherwise, it's a regular link
294         if (preg_match("/($InlineImages)$/i", $URL))
295             // no image link, just the src. see [img|link] above
296             return LinkImage($URL, $linkname);
297         else
298             return LinkURL($URL, $linkname);
299     }
300     elseif (preg_match("/^phpwiki:/", $URL))
301         return LinkPhpwikiURL($URL, $linkname);
302     elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
303         return $intermap->link($URL, $linkname);
304     else {
305         return WikiLink($URL, 'unknown', $linkname);
306     }
307     
308 }
309
310 /**
311  * Extract internal links from wiki page.
312  *
313  * @param mixed $content The raw wiki-text, either as
314  * an array of lines or as one big string.
315  *
316  * @return array List of the names of pages linked to.
317  */
318 function ExtractWikiPageLinks($content) {
319     list ($wikilinks,) = ExtractLinks($content);
320     return $wikilinks;
321 }      
322
323 /**
324  * Extract external links from a wiki page.
325  *
326  * @param mixed $content The raw wiki-text, either as
327  * an array of lines or as one big string.
328  *
329  * @return array List of the names of pages linked to.
330  */
331 function ExtractExternalLinks($content) {
332     list (, $urls) = ExtractLinks($content);
333     return $urls;
334 }      
335
336 /**
337  * Extract links from wiki page.
338  *
339  * FIXME: this should be done by the transform code.
340  *
341  * @param mixed $content The raw wiki-text, either as
342  * an array of lines or as one big string.
343  *
344  * @return array List of two arrays.  The first contains
345  * the internal links (names of pages linked to), the second
346  * contains external URLs linked to.
347  */
348 function ExtractLinks($content) {
349     include_once('lib/interwiki.php');
350     global $request, $WikiNameRegexp, $AllowedProtocols;
351     
352     if (is_string($content))
353         $content = explode("\n", $content);
354     
355     $wikilinks = array();
356     $urls = array();
357     
358     foreach ($content as $line) {
359         // remove plugin code
360         $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
361         // remove escaped '['
362         $line = str_replace('[[', ' ', $line);
363         // remove footnotes
364         $line = preg_replace('/\[\d+\]/', ' ', $line);
365         
366         // bracket links (only type wiki-* is of interest)
367         $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
368                                           $line, $brktlinks);
369         for ($i = 0; $i < $numBracketLinks; $i++) {
370             $link = LinkBracketLink($brktlinks[0][$i]);
371             $class = $link->getAttr('class');
372             if (preg_match('/^(named-)?wiki(unknown)?$/', $class)) {
373                 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
374                     $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
375                 } else {
376                     $wikilinks[$brktlinks[2][$i]] = 1;
377                 }
378             }
379             elseif (preg_match('/^(namedurl|rawurl|(named-)?interwiki)$/', $class)) {
380                 $urls[$brktlinks[2][$i]] = 1;
381             }
382             $line = str_replace($brktlinks[0][$i], '', $line);
383         }
384         
385         // Raw URLs
386         preg_match_all("/!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]/",
387                        $line, $link);
388         foreach ($link[0] as $url) {
389             if ($url[0] <> '!') {
390                 $urls[$url] = 1;
391             }
392             $line = str_replace($url, '', $line);
393         }
394
395         // Interwiki links
396         $map = InterWikiMap::GetMap($request);
397         $regexp = pcre_fix_posix_classes("!?(?<![[:alnum:]])") 
398             . $map->getRegexp() . ":[^\\s.,;?()]+";
399         preg_match_all("/$regexp/", $line, $link);
400         foreach ($link[0] as $interlink) {
401             if ($interlink[0] <> '!') {
402                 $link = $map->link($interlink);
403                 $urls[$link->getAttr('href')] = 1;
404             }
405             $line = str_replace($interlink, '', $line);
406         }
407
408         // BumpyText old-style wiki links
409         if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
410             for ($i = 0; isset($link[0][$i]); $i++) {
411                 if($link[0][$i][0] <> '!') {
412                     if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
413                         $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
414                     } else {
415                         $wikilinks[$link[0][$i]] = 1;
416                     }
417                 }
418             }
419         }
420     }
421     return array(array_keys($wikilinks), array_keys($urls));
422 }      
423
424
425 /**
426  * Convert old page markup to new-style markup.
427  *
428  * @param $text string Old-style wiki markup.
429  *
430  * @param $just_links bool Only convert old-style links.
431  * (Really this only converts escaped old-style links.)
432  *
433  * @return string New-style wiki markup.
434  *
435  * @bugs FIXME: footnotes and old-style tables are known to be broken.
436  */
437 function ConvertOldMarkup ($text, $just_links = false) {
438
439     static $orig, $repl, $link_orig, $link_repl;
440
441     if (empty($orig)) {
442         /*****************************************************************
443          * Conversions for inline markup:
444          */
445
446         // escape tilde's
447         $orig[] = '/~/';
448         $repl[] = '~~';
449
450         // escape escaped brackets
451         $orig[] = '/\[\[/';
452         $repl[] = '~[';
453
454         // change ! escapes to ~'s.
455         global $AllowedProtocols, $WikiNameRegexp, $request;
456         include_once('lib/interwiki.php');
457         $map = InterWikiMap::GetMap($request);
458         $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
459         $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
460         $bang_esc[] = $WikiNameRegexp;
461         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
462         $repl[] = '~\\1';
463
464
465         $link_orig = $orig;
466         $link_repl = $repl;
467         
468         /*****************************************************************
469          * Conversions for block markup
470          */
471         // convert indented blocks to <pre></pre>.
472         $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
473         $repl[] = "<pre>\n\\0</pre>\n";
474
475         // convert lists
476         $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
477         $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
478     }
479     
480
481     if ($just_links)
482         return preg_replace($link_orig, $link_repl, $text);
483     else
484         return preg_replace($orig, $repl, $text);
485 }
486
487 function _ConvertOldListMarkup ($indent, $bullet) {
488     $indent = str_repeat('     ', strlen($indent));
489     if ($bullet[0] == ';') {
490         $term = ltrim(substr($bullet, 1));
491         return $indent . $term . "\n" . $indent . '     ';
492     }
493     else
494         return $indent . $bullet . ' ';
495 }
496
497
498
499 /**
500  * Split WikiWords in page names.
501  *
502  * It has been deemed useful to split WikiWords (into "Wiki Words") in
503  * places like page titles. This is rumored to help search engines
504  * quite a bit.
505  *
506  * @param $page string The page name.
507  *
508  * @return string The split name.
509  */
510 function split_pagename ($page) {
511     
512     if (preg_match("/\s/", $page))
513         return $page;           // Already split --- don't split any more.
514     
515     // FIXME: this algorithm is Anglo-centric.
516     static $RE;
517     if (!isset($RE)) {
518         // This mess splits between a lower-case letter followed by
519         // either an upper-case or a numeral; except that it wont
520         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
521         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
522         // This the single-letter words 'I' and 'A' from any following
523         // capitalized words.
524         $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
525         // Split numerals from following letters.
526         $RE[] = '/(\d)([[:alpha:]])/';
527         
528         foreach ($RE as $key => $val)
529             $RE[$key] = pcre_fix_posix_classes($val);
530     }
531     if (isSubPage($page)) {
532         $pages = explode(SUBPAGE_SEPARATOR,$page);
533         $new_page = $pages[0] ? split_pagename($pages[0]) : '';
534         for ($i=1; $i < sizeof($pages); $i++) {
535             $new_page .=  (SUBPAGE_SEPARATOR . ($pages[$i] ? split_pagename($pages[$i]) : ''));
536         }
537         return $new_page;
538     } else {
539         foreach ($RE as $regexp) {
540             $page = preg_replace($regexp, '\\1 \\2', $page);
541         }
542         return $page;
543     }
544 }
545
546 function NoSuchRevision (&$request, $page, $version) {
547     $html = HTML(HTML::h2(_("Revision Not Found")),
548                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
549                              $version, WikiLink($page, 'auto'))));
550     include_once('lib/Template.php');
551     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
552     $request->finish();
553 }
554
555
556 /**
557  * Get time offset for local time zone.
558  *
559  * @param $time time_t Get offset for this time. Default: now.
560  * @param $no_colon boolean Don't put colon between hours and minutes.
561  * @return string Offset as a string in the format +HH:MM.
562  */
563 function TimezoneOffset ($time = false, $no_colon = false) {
564     if ($time === false)
565         $time = time();
566     $secs = date('Z', $time);
567
568     if ($secs < 0) {
569         $sign = '-';
570         $secs = -$secs;
571     }
572     else {
573         $sign = '+';
574     }
575     $colon = $no_colon ? '' : ':';
576     $mins = intval(($secs + 30) / 60);
577     return sprintf("%s%02d%s%02d",
578                    $sign, $mins / 60, $colon, $mins % 60);
579 }
580
581
582 /**
583  * Format time in ISO-8601 format.
584  *
585  * @param $time time_t Time.  Default: now.
586  * @return string Date and time in ISO-8601 format.
587  */
588 function Iso8601DateTime ($time = false) {
589     if ($time === false)
590         $time = time();
591     $tzoff = TimezoneOffset($time);
592     $date  = date('Y-m-d', $time);
593     $time  = date('H:i:s', $time);
594     return $date . 'T' . $time . $tzoff;
595 }
596
597 /**
598  * Format time in RFC-2822 format.
599  *
600  * @param $time time_t Time.  Default: now.
601  * @return string Date and time in RFC-2822 format.
602  */
603 function Rfc2822DateTime ($time = false) {
604     if ($time === false)
605         $time = time();
606     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
607 }
608
609 /**
610  * Format time to standard 'ctime' format.
611  *
612  * @param $time time_t Time.  Default: now.
613  * @return string Date and time.
614  */
615 function CTime ($time = false)
616 {
617     if ($time === false)
618         $time = time();
619     return date("D M j H:i:s Y", $time);
620 }
621
622
623
624 /**
625  * Internationalized printf.
626  *
627  * This is essentially the same as PHP's built-in printf
628  * with the following exceptions:
629  * <ol>
630  * <li> It passes the format string through gettext().
631  * <li> It supports the argument reordering extensions.
632  * </ol>
633  *
634  * Example:
635  *
636  * In php code, use:
637  * <pre>
638  *    __printf("Differences between versions %s and %s of %s",
639  *             $new_link, $old_link, $page_link);
640  * </pre>
641  *
642  * Then in locale/po/de.po, one can reorder the printf arguments:
643  *
644  * <pre>
645  *    msgid "Differences between %s and %s of %s."
646  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
647  * </pre>
648  *
649  * (Note that while PHP tries to expand $vars within double-quotes,
650  * the values in msgstr undergo no such expansion, so the '$'s
651  * okay...)
652  *
653  * One shouldn't use reordered arguments in the default format string.
654  * Backslashes in the default string would be necessary to escape the
655  * '$'s, and they'll cause all kinds of trouble....
656  */ 
657 function __printf ($fmt) {
658     $args = func_get_args();
659     array_shift($args);
660     echo __vsprintf($fmt, $args);
661 }
662
663 /**
664  * Internationalized sprintf.
665  *
666  * This is essentially the same as PHP's built-in printf with the
667  * following exceptions:
668  *
669  * <ol>
670  * <li> It passes the format string through gettext().
671  * <li> It supports the argument reordering extensions.
672  * </ol>
673  *
674  * @see __printf
675  */ 
676 function __sprintf ($fmt) {
677     $args = func_get_args();
678     array_shift($args);
679     return __vsprintf($fmt, $args);
680 }
681
682 /**
683  * Internationalized vsprintf.
684  *
685  * This is essentially the same as PHP's built-in printf with the
686  * following exceptions:
687  *
688  * <ol>
689  * <li> It passes the format string through gettext().
690  * <li> It supports the argument reordering extensions.
691  * </ol>
692  *
693  * @see __printf
694  */ 
695 function __vsprintf ($fmt, $args) {
696     $fmt = gettext($fmt);
697     // PHP's sprintf doesn't support variable with specifiers,
698     // like sprintf("%*s", 10, "x"); --- so we won't either.
699     
700     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
701         // Format string has '%2$s' style argument reordering.
702         // PHP doesn't support this.
703         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
704             // literal variable name substitution only to keep locale
705             // strings uncluttered
706             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
707                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
708         
709         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
710         $newargs = array();
711         
712         // Reorder arguments appropriately.
713         foreach($m[1] as $argnum) {
714             if ($argnum < 1 || $argnum > count($args))
715                 trigger_error(sprintf(_("%s: argument index out of range"), 
716                                       $argnum), E_USER_WARNING);
717             $newargs[] = $args[$argnum - 1];
718         }
719         $args = $newargs;
720     }
721     
722     // Not all PHP's have vsprintf, so...
723     array_unshift($args, $fmt);
724     return call_user_func_array('sprintf', $args);
725 }
726
727
728 class fileSet {
729     /**
730      * Build an array in $this->_fileList of files from $dirname.
731      * Subdirectories are not traversed.
732      *
733      * (This was a function LoadDir in lib/loadsave.php)
734      * See also http://www.php.net/manual/en/function.readdir.php
735      */
736     function getFiles() {
737         return $this->_fileList;
738     }
739
740     function _filenameSelector($filename) {
741         if (! $this->_pattern)
742             return true;
743         else {
744             return glob_match ($this->_pattern, $filename, $this->_case);
745         }
746     }
747
748     function fileSet($directory, $filepattern = false) {
749         $this->_fileList = array();
750         $this->_pattern = $filepattern;
751         $this->_case = !isWindows();
752         $this->_pathsep = '/';
753
754         if (empty($directory)) {
755             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
756                           E_USER_NOTICE);
757             return; // early return
758         }
759
760         @ $dir_handle = opendir($dir=$directory);
761         if (empty($dir_handle)) {
762             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
763                                   $dir), E_USER_NOTICE);
764             return; // early return
765         }
766
767         while ($filename = readdir($dir_handle)) {
768             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
769                 continue;
770             if ($this->_filenameSelector($filename)) {
771                 array_push($this->_fileList, "$filename");
772                 //trigger_error(sprintf(_("found file %s"), $filename),
773                 //                      E_USER_NOTICE); //debugging
774             }
775         }
776         closedir($dir_handle);
777     }
778 };
779
780 // File globbing
781
782 // expands a list containing regex's to its matching entries
783 class ListRegexExpand {
784     var $match, $list, $index, $case_sensitive;
785     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
786         $this->match = str_replace('/','\/',$match);
787         $this->list = &$list;
788         $this->case_sensitive = $case_sensitive;        
789     }
790     function listMatchCallback ($item, $key) {
791         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
792             unset($this->list[$this->index]);
793             $this->list[] = $item;
794         }
795     }
796     function expandRegex ($index, &$pages) {
797         $this->index = $index;
798         array_walk($pages, array($this, 'listMatchCallback'));
799         return $this->list;
800     }
801 }
802
803 // convert fileglob to regex style
804 function glob_to_pcre ($glob) {
805     $re = preg_replace('/\./', '\\.', $glob);
806     $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
807     if (!preg_match('/^[\?\*]/',$glob))
808         $re = '^' . $re;
809     if (!preg_match('/[\?\*]$/',$glob))
810         $re = $re . '$';
811     return $re;
812 }
813
814 function glob_match ($glob, $against, $case_sensitive = true) {
815     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
816 }
817
818 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
819     $list = explode(',',$input);
820     // expand wildcards from list of $allnames
821     if (preg_match('/[\?\*]/',$input)) {
822         for ($i = 0; $i <= sizeof($list); $i++) {
823             $f = $list[$i];
824             if (preg_match('/[\?\*]/',$f)) {
825                 reset($allnames);
826                 $expand = new ListRegexExpand(&$list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
827                 $expand->expandRegex($i, &$allnames);
828             }
829         }
830     }
831     return $list;
832 }
833
834 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
835
836 function explodePageList($input, $perm = false) {
837     // expand wildcards from list of all pages
838     if (preg_match('/[\?\*]/',$input)) {
839         $dbi = $GLOBALS['request']->_dbi;
840         $allPagehandles = $dbi->getAllPages($perm);
841         while ($pagehandle = $allPagehandles->next()) {
842             $allPages[] = $pagehandle->getName();
843         }
844         return explodeList($input, &$allPages);
845     } else {
846         return explode(',',$input);
847     }
848 }
849
850 // Class introspections
851
852 /** Determine whether object is of a specified type.
853  *
854  * @param $object object An object.
855  * @param $class string Class name.
856  * @return bool True iff $object is a $class
857  * or a sub-type of $class. 
858  */
859 function isa ($object, $class) 
860 {
861     $lclass = strtolower($class);
862
863     return is_object($object)
864         && ( get_class($object) == strtolower($lclass)
865              || is_subclass_of($object, $lclass) );
866 }
867
868 /** Determine whether (possible) object has method.
869  *
870  * @param $object mixed Object
871  * @param $method string Method name
872  * @return bool True iff $object is an object with has method $method.
873  */
874 function can ($object, $method) 
875 {
876     return is_object($object) && method_exists($object, strtolower($method));
877 }
878
879 /**
880  * Seed the random number generator.
881  *
882  * better_srand() ensures the randomizer is seeded only once.
883  * 
884  * How random do you want it? See:
885  * http://www.php.net/manual/en/function.srand.php
886  * http://www.php.net/manual/en/function.mt-srand.php
887  */
888 function better_srand($seed = '') {
889     static $wascalled = FALSE;
890     if (!$wascalled) {
891         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
892         srand($seed);
893         $wascalled = TRUE;
894         //trigger_error("new random seed", E_USER_NOTICE); //debugging
895     }
896 }
897
898 /**
899  * Recursively count all non-empty elements 
900  * in array of any dimension or mixed - i.e. 
901  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
902  * See http://www.php.net/manual/en/function.count.php
903  */
904 function count_all($arg) {
905     // skip if argument is empty
906     if ($arg) {
907         //print_r($arg); //debugging
908         $count = 0;
909         // not an array, return 1 (base case) 
910         if(!is_array($arg))
911             return 1;
912         // else call recursively for all elements $arg
913         foreach($arg as $key => $val)
914             $count += count_all($val);
915         return $count;
916     }
917 }
918
919 function isSubPage($pagename) {
920     return (strstr($pagename, SUBPAGE_SEPARATOR));
921 }
922
923 function subPageSlice($pagename, $pos) {
924     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
925     $pages = array_slice($pages,$pos,1);
926     return $pages[0];
927 }
928
929
930 // (c-file-style: "gnu")
931 // Local Variables:
932 // mode: php
933 // tab-width: 8
934 // c-basic-offset: 4
935 // c-hanging-comment-ender-p: nil
936 // indent-tabs-mode: nil
937 // End:   
938 ?>