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