]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Fix for backlinks to pages with digits in their names bug.
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.119 2002-09-14 22:58:06 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 /* FIXME: this should be done by the transform code */
311 function ExtractWikiPageLinks($content) {
312     global $WikiNameRegexp;
313     
314     if (is_string($content))
315         $content = explode("\n", $content);
316     
317     $wikilinks = array();
318     foreach ($content as $line) {
319         // remove plugin code
320         $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
321         // remove escaped '['
322         $line = str_replace('[[', ' ', $line);
323         // remove footnotes
324         $line = preg_replace('/\[\d+\]/', ' ', $line);
325         
326         // bracket links (only type wiki-* is of interest)
327         $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
328                                           $line, $brktlinks);
329         for ($i = 0; $i < $numBracketLinks; $i++) {
330             $link = LinkBracketLink($brktlinks[0][$i]);
331             if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
332                 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
333                     global $request;
334                     $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
335                 } else {
336                     $wikilinks[$brktlinks[2][$i]] = 1;
337                 }
338             
339             $brktlink = preg_quote($brktlinks[0][$i]);
340             $line = preg_replace("|$brktlink|", '', $line);
341         }
342         
343         // BumpyText old-style wiki links
344         if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
345             for ($i = 0; isset($link[0][$i]); $i++) {
346                 if($link[0][$i][0] <> '!') {
347                     if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
348                         global $request;
349                         $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
350                     } else {
351                         $wikilinks[$link[0][$i]] = 1;
352                     }
353                 }
354             }
355         }
356     }
357     return array_keys($wikilinks);
358 }      
359
360 /**
361  * Convert old page markup to new-style markup.
362  *
363  * @param $text string Old-style wiki markup.
364  *
365  * @param $just_links bool Only convert old-style links.
366  * (Really this only converts escaped old-style links.)
367  *
368  * @return string New-style wiki markup.
369  *
370  * @bugs FIXME: footnotes and old-style tables are known to be broken.
371  */
372 function ConvertOldMarkup ($text, $just_links = false) {
373
374     static $orig, $repl, $link_orig, $link_repl;
375
376     if (empty($orig)) {
377         /*****************************************************************
378          * Conversions for inline markup:
379          */
380
381         // escape tilde's
382         $orig[] = '/~/';
383         $repl[] = '~~';
384
385         // escape escaped brackets
386         $orig[] = '/\[\[/';
387         $repl[] = '~[';
388
389         // change ! escapes to ~'s.
390         global $AllowedProtocols, $WikiNameRegexp, $request;
391         include_once('lib/interwiki.php');
392         $map = InterWikiMap::GetMap($request);
393         $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
394         $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
395         $bang_esc[] = $WikiNameRegexp;
396         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
397         $repl[] = '~\\1';
398
399
400         $link_orig = $orig;
401         $link_repl = $repl;
402         
403         /*****************************************************************
404          * Conversions for block markup
405          */
406         // convert indented blocks to <pre></pre>.
407         $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
408         $repl[] = "<pre>\n\\0</pre>\n";
409
410         // convert lists
411         $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
412         $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
413     }
414     
415
416     if ($just_links)
417         return preg_replace($link_orig, $link_repl, $text);
418     else
419         return preg_replace($orig, $repl, $text);
420 }
421
422 function _ConvertOldListMarkup ($indent, $bullet) {
423     $indent = str_repeat('     ', strlen($indent));
424     if ($bullet[0] == ';') {
425         $term = ltrim(substr($bullet, 1));
426         return $indent . $term . "\n" . $indent . '     ';
427     }
428     else
429         return $indent . $bullet . ' ';
430 }
431
432
433
434 /**
435  * Split WikiWords in page names.
436  *
437  * It has been deemed useful to split WikiWords (into "Wiki Words") in
438  * places like page titles. This is rumored to help search engines
439  * quite a bit.
440  *
441  * @param $page string The page name.
442  *
443  * @return string The split name.
444  */
445 function split_pagename ($page) {
446     
447     if (preg_match("/\s/", $page))
448         return $page;           // Already split --- don't split any more.
449     
450     // FIXME: this algorithm is Anglo-centric.
451     static $RE;
452     if (!isset($RE)) {
453         // This mess splits between a lower-case letter followed by
454         // either an upper-case or a numeral; except that it wont
455         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
456         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
457         // This the single-letter words 'I' and 'A' from any following
458         // capitalized words.
459         $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
460         // Split numerals from following letters.
461         $RE[] = '/(\d)([[:alpha:]])/';
462         
463         foreach ($RE as $key => $val)
464             $RE[$key] = pcre_fix_posix_classes($val);
465     }
466     if (isSubPage($page)) {
467         $pages = explode(SUBPAGE_SEPARATOR,$page);
468         $new_page = $pages[0] ? split_pagename($pages[0]) : '';
469         for ($i=1; $i < sizeof($pages); $i++) {
470             $new_page .=  (SUBPAGE_SEPARATOR . ($pages[$i] ? split_pagename($pages[$i]) : ''));
471         }
472         return $new_page;
473     } else {
474         foreach ($RE as $regexp) {
475             $page = preg_replace($regexp, '\\1 \\2', $page);
476         }
477         return $page;
478     }
479 }
480
481 function NoSuchRevision (&$request, $page, $version) {
482     $html = HTML(HTML::h2(_("Revision Not Found")),
483                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
484                              $version, WikiLink($page, 'auto'))));
485     include_once('lib/Template.php');
486     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
487     $request->finish();
488 }
489
490
491 /**
492  * Get time offset for local time zone.
493  *
494  * @param $time time_t Get offset for this time. Default: now.
495  * @param $no_colon boolean Don't put colon between hours and minutes.
496  * @return string Offset as a string in the format +HH:MM.
497  */
498 function TimezoneOffset ($time = false, $no_colon = false) {
499     if ($time === false)
500         $time = time();
501     $secs = date('Z', $time);
502
503     if ($secs < 0) {
504         $sign = '-';
505         $secs = -$secs;
506     }
507     else {
508         $sign = '+';
509     }
510     $colon = $no_colon ? '' : ':';
511     $mins = intval(($secs + 30) / 60);
512     return sprintf("%s%02d%s%02d",
513                    $sign, $mins / 60, $colon, $mins % 60);
514 }
515
516
517 /**
518  * Format time in ISO-8601 format.
519  *
520  * @param $time time_t Time.  Default: now.
521  * @return string Date and time in ISO-8601 format.
522  */
523 function Iso8601DateTime ($time = false) {
524     if ($time === false)
525         $time = time();
526     $tzoff = TimezoneOffset($time);
527     $date  = date('Y-m-d', $time);
528     $time  = date('H:i:s', $time);
529     return $date . 'T' . $time . $tzoff;
530 }
531
532 /**
533  * Format time in RFC-2822 format.
534  *
535  * @param $time time_t Time.  Default: now.
536  * @return string Date and time in RFC-2822 format.
537  */
538 function Rfc2822DateTime ($time = false) {
539     if ($time === false)
540         $time = time();
541     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
542 }
543
544 /**
545  * Format time to standard 'ctime' format.
546  *
547  * @param $time time_t Time.  Default: now.
548  * @return string Date and time.
549  */
550 function CTime ($time = false)
551 {
552     if ($time === false)
553         $time = time();
554     return date("D M j H:i:s Y", $time);
555 }
556
557
558
559 /**
560  * Internationalized printf.
561  *
562  * This is essentially the same as PHP's built-in printf
563  * with the following exceptions:
564  * <ol>
565  * <li> It passes the format string through gettext().
566  * <li> It supports the argument reordering extensions.
567  * </ol>
568  *
569  * Example:
570  *
571  * In php code, use:
572  * <pre>
573  *    __printf("Differences between versions %s and %s of %s",
574  *             $new_link, $old_link, $page_link);
575  * </pre>
576  *
577  * Then in locale/po/de.po, one can reorder the printf arguments:
578  *
579  * <pre>
580  *    msgid "Differences between %s and %s of %s."
581  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
582  * </pre>
583  *
584  * (Note that while PHP tries to expand $vars within double-quotes,
585  * the values in msgstr undergo no such expansion, so the '$'s
586  * okay...)
587  *
588  * One shouldn't use reordered arguments in the default format string.
589  * Backslashes in the default string would be necessary to escape the
590  * '$'s, and they'll cause all kinds of trouble....
591  */ 
592 function __printf ($fmt) {
593     $args = func_get_args();
594     array_shift($args);
595     echo __vsprintf($fmt, $args);
596 }
597
598 /**
599  * Internationalized sprintf.
600  *
601  * This is essentially the same as PHP's built-in printf with the
602  * following exceptions:
603  *
604  * <ol>
605  * <li> It passes the format string through gettext().
606  * <li> It supports the argument reordering extensions.
607  * </ol>
608  *
609  * @see __printf
610  */ 
611 function __sprintf ($fmt) {
612     $args = func_get_args();
613     array_shift($args);
614     return __vsprintf($fmt, $args);
615 }
616
617 /**
618  * Internationalized vsprintf.
619  *
620  * This is essentially the same as PHP's built-in printf with the
621  * following exceptions:
622  *
623  * <ol>
624  * <li> It passes the format string through gettext().
625  * <li> It supports the argument reordering extensions.
626  * </ol>
627  *
628  * @see __printf
629  */ 
630 function __vsprintf ($fmt, $args) {
631     $fmt = gettext($fmt);
632     // PHP's sprintf doesn't support variable with specifiers,
633     // like sprintf("%*s", 10, "x"); --- so we won't either.
634     
635     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
636         // Format string has '%2$s' style argument reordering.
637         // PHP doesn't support this.
638         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
639             // literal variable name substitution only to keep locale
640             // strings uncluttered
641             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
642                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
643         
644         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
645         $newargs = array();
646         
647         // Reorder arguments appropriately.
648         foreach($m[1] as $argnum) {
649             if ($argnum < 1 || $argnum > count($args))
650                 trigger_error(sprintf(_("%s: argument index out of range"), 
651                                       $argnum), E_USER_WARNING);
652             $newargs[] = $args[$argnum - 1];
653         }
654         $args = $newargs;
655     }
656     
657     // Not all PHP's have vsprintf, so...
658     array_unshift($args, $fmt);
659     return call_user_func_array('sprintf', $args);
660 }
661
662
663 class fileSet {
664     /**
665      * Build an array in $this->_fileList of files from $dirname.
666      * Subdirectories are not traversed.
667      *
668      * (This was a function LoadDir in lib/loadsave.php)
669      * See also http://www.php.net/manual/en/function.readdir.php
670      */
671     function getFiles() {
672         return $this->_fileList;
673     }
674
675     function _filenameSelector($filename) {
676         if (! $this->_pattern)
677             return true;
678         else {
679             return glob_match ($this->_pattern, $filename, $this->_case);
680         }
681     }
682
683     function fileSet($directory, $filepattern = false) {
684         $this->_fileList = array();
685         $this->_pattern = $filepattern;
686         $this->_case = !isWindows();
687         $this->_pathsep = '/';
688
689         if (empty($directory)) {
690             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
691                           E_USER_NOTICE);
692             return; // early return
693         }
694
695         @ $dir_handle = opendir($dir=$directory);
696         if (empty($dir_handle)) {
697             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
698                                   $dir), E_USER_NOTICE);
699             return; // early return
700         }
701
702         while ($filename = readdir($dir_handle)) {
703             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
704                 continue;
705             if ($this->_filenameSelector($filename)) {
706                 array_push($this->_fileList, "$filename");
707                 //trigger_error(sprintf(_("found file %s"), $filename),
708                 //                      E_USER_NOTICE); //debugging
709             }
710         }
711         closedir($dir_handle);
712     }
713 };
714
715 // File globbing
716
717 // expands a list containing regex's to its matching entries
718 class ListRegexExpand {
719     var $match, $list, $index, $case_sensitive;
720     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
721         $this->match = str_replace('/','\/',$match);
722         $this->list = &$list;
723         $this->case_sensitive = $case_sensitive;        
724     }
725     function listMatchCallback ($item, $key) {
726         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
727             unset($this->list[$this->index]);
728             $this->list[] = $item;
729         }
730     }
731     function expandRegex ($index, &$pages) {
732         $this->index = $index;
733         array_walk($pages, array($this, 'listMatchCallback'));
734         return $this->list;
735     }
736 }
737
738 // convert fileglob to regex style
739 function glob_to_pcre ($glob) {
740     $re = preg_replace('/\./', '\\.', $glob);
741     $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
742     if (!preg_match('/^[\?\*]/',$glob))
743         $re = '^' . $re;
744     if (!preg_match('/[\?\*]$/',$glob))
745         $re = $re . '$';
746     return $re;
747 }
748
749 function glob_match ($glob, $against, $case_sensitive = true) {
750     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
751 }
752
753 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
754     $list = explode(',',$input);
755     // expand wildcards from list of $allnames
756     if (preg_match('/[\?\*]/',$input)) {
757         for ($i = 0; $i <= sizeof($list); $i++) {
758             $f = $list[$i];
759             if (preg_match('/[\?\*]/',$f)) {
760                 reset($allnames);
761                 $expand = new ListRegexExpand(&$list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
762                 $expand->expandRegex($i, &$allnames);
763             }
764         }
765     }
766     return $list;
767 }
768
769 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
770
771 function explodePageList($input, $perm = false) {
772     // expand wildcards from list of all pages
773     if (preg_match('/[\?\*]/',$input)) {
774         $dbi = $GLOBALS['request']->_dbi;
775         $allPagehandles = $dbi->getAllPages($perm);
776         while ($pagehandle = $allPagehandles->next()) {
777             $allPages[] = $pagehandle->getName();
778         }
779         return explodeList($input, &$allPages);
780     } else {
781         return explode(',',$input);
782     }
783 }
784
785 // Class introspections
786
787 /** Determine whether object is of a specified type.
788  *
789  * @param $object object An object.
790  * @param $class string Class name.
791  * @return bool True iff $object is a $class
792  * or a sub-type of $class. 
793  */
794 function isa ($object, $class) 
795 {
796     $lclass = strtolower($class);
797
798     return is_object($object)
799         && ( get_class($object) == strtolower($lclass)
800              || is_subclass_of($object, $lclass) );
801 }
802
803 /** Determine whether (possible) object has method.
804  *
805  * @param $object mixed Object
806  * @param $method string Method name
807  * @return bool True iff $object is an object with has method $method.
808  */
809 function can ($object, $method) 
810 {
811     return is_object($object) && method_exists($object, strtolower($method));
812 }
813
814 /**
815  * Seed the random number generator.
816  *
817  * better_srand() ensures the randomizer is seeded only once.
818  * 
819  * How random do you want it? See:
820  * http://www.php.net/manual/en/function.srand.php
821  * http://www.php.net/manual/en/function.mt-srand.php
822  */
823 function better_srand($seed = '') {
824     static $wascalled = FALSE;
825     if (!$wascalled) {
826         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
827         srand($seed);
828         $wascalled = TRUE;
829         //trigger_error("new random seed", E_USER_NOTICE); //debugging
830     }
831 }
832
833 /**
834  * Recursively count all non-empty elements 
835  * in array of any dimension or mixed - i.e. 
836  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
837  * See http://www.php.net/manual/en/function.count.php
838  */
839 function count_all($arg) {
840     // skip if argument is empty
841     if ($arg) {
842         //print_r($arg); //debugging
843         $count = 0;
844         // not an array, return 1 (base case) 
845         if(!is_array($arg))
846             return 1;
847         // else call recursively for all elements $arg
848         foreach($arg as $key => $val)
849             $count += count_all($val);
850         return $count;
851     }
852 }
853
854 function isSubPage($pagename) {
855     return (strstr($pagename, SUBPAGE_SEPARATOR));
856 }
857
858 function subPageSlice($pagename, $pos) {
859     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
860     $pages = array_slice($pages,$pos,1);
861     return $pages[0];
862 }
863
864
865 // (c-file-style: "gnu")
866 // Local Variables:
867 // mode: php
868 // tab-width: 8
869 // c-basic-offset: 4
870 // c-hanging-comment-ender-p: nil
871 // indent-tabs-mode: nil
872 // End:   
873 ?>