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