1 <?php //rcs_id('$Id: stdlib.php,v 1.127 2002-09-24 01:12:28 zorloc Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
6 IconForLink($protocol_or_url)
7 LinkURL($url, $linktext)
10 MakeWikiForm ($pagename, $args, $class, $button_text)
11 SplitQueryArgs ($query_args)
12 LinkPhpwikiURL($url, $text)
13 LinkBracketLink($bracketlink)
14 ExtractWikiPageLinks($content)
15 ConvertOldMarkup($content)
17 class Stack { push($item), pop(), cnt(), top() }
19 split_pagename ($page)
20 NoSuchRevision ($request, $page, $version)
21 TimezoneOffset ($time, $no_colon)
22 Iso8601DateTime ($time)
23 Rfc2822DateTime ($time)
27 __vsprintf ($fmt, $args)
28 better_srand($seed = '')
31 subPageSlice($pagename, $pos)
32 explodePageList($input, $perm = false)
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
45 * Convert string to a valid XML identifier.
47 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
49 * We would like to have, e.g. named anchors within wiki pages
50 * names like "Table of Contents" --- clearly not a valid XML
51 * fragment identifier.
53 * This function implements a one-to-one map from {any string}
54 * to {valid XML identifiers}.
57 * converting all bytes not in [A-Za-z0-9:_-],
58 * and any leading byte not in [A-Za-z] to 'xbb.',
59 * where 'bb' is the hexadecimal representation of the
62 * As a special case, the empty string is converted to 'empty.'
67 function MangleXmlIdentifier($str)
72 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
73 "'x' . sprintf('%02x', ord('\\0')) . '.'",
79 * Generates a valid URL for a given Wiki pagename.
80 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
81 * If a WikiDB_Page object function will extract the name to link to.
82 * If a WikiDB_PageRevision object function will extract the name to link to.
84 * @param boolean $get_abs_url Default value is false.
85 * @return string The absolute URL to the page passed as $pagename.
87 function WikiURL($pagename, $args = '', $get_abs_url = false) {
90 if (is_object($pagename)) {
91 if (isa($pagename, 'WikiDB_Page')) {
92 $pagename = $pagename->getName();
94 elseif (isa($pagename, 'WikiDB_PageRevision')) {
95 $page = $pagename->getPage();
96 $args['version'] = $pagename->getVersion();
97 $pagename = $page->getName();
99 elseif (isa($pagename, 'WikiPageName')) {
100 $anchor = $pagename->anchor;
101 $pagename = $pagename->fullPagename;
105 if (is_array($args)) {
107 foreach ($args as $key => $val) {
108 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
109 $enc_args[] = urlencode($key) . '=' . urlencode($val);
111 $args = join('&', $enc_args);
115 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
116 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
121 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
122 $url .= "?pagename=" . rawurlencode($pagename);
127 $url .= "#" . MangleXmlIdentifier($anchor);
132 * Generates icon in front of links.
133 * @param string $protocol_or_url URL or protocol to determine which icon to use.
134 * @return HtmlElement HtmlElement object that contains data to create img link to
135 * icon for use with url or protocol passed to the function. False if no img to be
138 function IconForLink($protocol_or_url) {
140 if ($filename_suffix = false) {
141 // display apache style icon for file type instead of protocol icon
142 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
143 // - document: html, htm, text, txt, rtf, pdf, doc
144 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
145 // - audio: mp3,mp2,aiff,aif,au
146 // - multimedia: mpeg,mpg,mov,qt
148 list ($proto) = explode(':', $protocol_or_url, 2);
149 $src = $Theme->getLinkIconURL($proto);
151 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
158 * Determines if the url passed to function is safe, by detecting if the characters
159 * '<', '>', or '"' are present.
160 * @param string $url URL to check for unsafe characters.
161 * @return boolean True if same, false else.
163 function IsSafeURL($url) {
164 return !ereg('[<>"]', $url);
168 * Generates an HtmlElement object to store data for a link.
169 * @param string $url URL that the link will point to.
170 * @param string $linktext Text to be displayed as link.
171 * @return HtmlElement HtmlElement object that contains data to construct an html link.
173 function LinkURL($url, $linktext = '') {
174 // FIXME: Is this needed (or sufficient?)
175 if(! IsSafeURL($url)) {
176 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
177 _("BAD URL -- remove all of <, >, \"")));
181 $linktext = preg_replace("/mailto:/A", "", $url);
183 $link = HTML::a(array('href' => $url),
184 IconForLink($url), $linktext);
187 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
192 function LinkImage($url, $alt = false) {
193 // FIXME: Is this needed (or sufficient?)
194 if(! IsSafeURL($url)) {
195 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
196 _("BAD URL -- remove all of <, >, \"")));
201 $link = HTML::img(array('src' => $url, 'alt' => $alt));
203 $link->setAttr('class', 'inlineimage');
210 var $items = array();
213 function push($item) {
214 $this->items[$this->size] = $item;
220 if ($this->size == 0) {
221 return false; // stack is empty
224 return $this->items[$this->size];
233 return $this->items[$this->size - 1];
239 // end class definition
242 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
243 // HACK: so as to not completely break old PhpWikiAdministration pages.
244 trigger_error("MagicPhpWikiURL forms are no longer supported. "
245 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
248 $loader = new WikiPluginLoader;
249 @$action = (string)$args['action'];
250 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
253 function SplitQueryArgs ($query_args = '')
255 $split_args = split('&', $query_args);
257 while (list($key, $val) = each($split_args))
258 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
259 $args[$m[1]] = $m[2];
263 function LinkPhpwikiURL($url, $text = '') {
266 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
267 return HTML::strong(array('class' => 'rawurl'),
268 HTML::u(array('class' => 'baduri'),
269 _("BAD phpwiki: URL")));
273 $pagename = urldecode($m[1]);
276 if (empty($pagename) &&
277 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
278 // Convert old style links (to not break diff links in
280 $pagename = urldecode($m[2]);
281 $args = array("action" => $m[1]);
284 $args = SplitQueryArgs($qargs);
287 if (empty($pagename))
288 $pagename = $GLOBALS['request']->getArg('pagename');
290 if (isset($args['action']) && $args['action'] == 'browse')
291 unset($args['action']);
294 if (empty($args['action']))
296 else if (is_safe_action($args['action']))
297 $class = 'wikiaction';
299 if (empty($args['action']) || is_safe_action($args['action']))
300 $class = 'wikiaction';
302 // Don't allow administrative links on unlocked pages.
303 $page = $GLOBALS['request']->getPage();
304 if (!$page->get('locked'))
305 return HTML::span(array('class' => 'wikiunsafe'),
306 HTML::u(_("Lock page to enable link")));
307 $class = 'wikiadmin';
310 // FIXME: ug, don't like this
311 if (preg_match('/=\d*\(/', $qargs))
312 return MakeWikiForm($pagename, $args, $class, $text);
314 $text = HTML::span(array('class' => 'rawurl'), $url);
316 return HTML::a(array('href' => WikiURL($pagename, $args),
322 * A class to assist in parsing wiki pagenames.
324 * Now with subpages and anchors, parsing and passing around
325 * pagenames is more complicated. This should help.
329 /** Short name for page.
331 * This is the value of $name passed to the constructor.
335 /** The full page name.
337 * This is the full name of the page (without anchor).
343 * This is the referenced anchor within the page, or the empty string.
349 * @param WikiRequest $request
350 * @param string $name Page name.
351 * This can be a relative subpage name (like '/SubPage'), and can also
352 * include an anchor (e.g. 'SandBox#anchorname' or just '#anchor').
354 function WikiPageName($request, $name) {
355 $this->shortName = $name;
357 if ($name[0] == SUBPAGE_SEPARATOR or $name[0] == '#')
358 $name = $request->getArg('pagename') . $name;
360 if (strstr($name, '#')) {
361 list($this->fullPagename, $this->anchor) = split('#', $name, 2);
364 $this->fullPagename = $name;
369 $dbi = $request->getDbh();
370 $this->_exists = $dbi->isWikiPage($this->fullPagename);
374 * Determine whether page 'exists'.
376 * @return boolean True if page exists with non-default content.
379 return $this->_exists;
383 function LinkBracketLink($bracketlink) {
384 global $request, $AllowedProtocols, $InlineImages;
386 include_once("lib/interwiki.php");
387 $intermap = InterWikiMap::GetMap($request);
389 // $bracketlink will start and end with brackets; in between will
390 // be either a page name, a URL or both separated by a pipe.
392 // strip brackets and leading space
393 preg_match('/(\#?) \[\s* (?: ([^|]*?) \s* (\|) )? \s* (.+?) \s*\]/x', $bracketlink, $matches);
394 list (, $hash, $label, $bar, $link) = $matches;
396 // if label looks like a url to an image, we want an image link.
397 if (preg_match("/($InlineImages)$/i", $label)) {
399 if (! preg_match("#^($AllowedProtocols):#", $imgurl)) {
400 // linkname like 'images/next.gif'.
402 $imgurl = $Theme->getImageURL($linkname);
404 $label = LinkImage($imgurl, $link);
408 // It's an anchor, not a link...
409 $id = MangleXmlIdentifier($link);
410 return HTML::a(array('name' => $id, 'id' => $id),
411 $bar ? $label : $link);
414 $wikipage = new WikiPageName($request, $link);
415 if ($wikipage->exists()) {
416 return WikiLink($wikipage, 'known', $label);
418 elseif (preg_match("#^($AllowedProtocols):#", $link)) {
419 // if it's an image, embed it; otherwise, it's a regular link
420 if (preg_match("/($InlineImages)$/i", $link))
421 // no image link, just the src. see [img|link] above
422 return LinkImage($link, $label);
424 return LinkURL($link, $label);
426 elseif (preg_match("/^phpwiki:/", $link))
427 return LinkPhpwikiURL($link, $label);
428 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link))
429 return $intermap->link($link, $label);
431 return WikiLink($wikipage, 'unknown', $label);
436 * Extract internal links from wiki page.
438 * @param mixed $content The raw wiki-text, either as
439 * an array of lines or as one big string.
441 * @return array List of the names of pages linked to.
443 function ExtractWikiPageLinks($content) {
444 list ($wikilinks,) = ExtractLinks($content);
449 * Extract external links from a wiki page.
451 * @param mixed $content The raw wiki-text, either as
452 * an array of lines or as one big string.
454 * @return array List of the names of pages linked to.
456 function ExtractExternalLinks($content) {
457 list (, $urls) = ExtractLinks($content);
462 * Extract links from wiki page.
464 * FIXME: this should be done by the transform code.
466 * @param mixed $content The raw wiki-text, either as
467 * an array of lines or as one big string.
469 * @return array List of two arrays. The first contains
470 * the internal links (names of pages linked to), the second
471 * contains external URLs linked to.
473 function ExtractLinks($content) {
474 include_once('lib/interwiki.php');
475 global $request, $WikiNameRegexp, $AllowedProtocols;
477 if (is_string($content))
478 $content = explode("\n", $content);
480 $wikilinks = array();
483 foreach ($content as $line) {
484 // remove plugin code
485 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
486 // remove escaped '['
487 $line = str_replace('[[', ' ', $line);
489 $line = preg_replace('/\[\d+\]/', ' ', $line);
491 // bracket links (only type wiki-* is of interest)
492 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
494 for ($i = 0; $i < $numBracketLinks; $i++) {
495 $link = LinkBracketLink($brktlinks[0][$i]);
496 $class = $link->getAttr('class');
497 if (preg_match('/^(named-)?wiki(unknown)?$/', $class)) {
498 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
499 $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
501 $wikilinks[$brktlinks[2][$i]] = 1;
504 elseif (preg_match('/^(namedurl|rawurl|(named-)?interwiki)$/', $class)) {
505 $urls[$brktlinks[2][$i]] = 1;
507 $line = str_replace($brktlinks[0][$i], '', $line);
511 preg_match_all("/!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]/",
513 foreach ($link[0] as $url) {
514 if ($url[0] <> '!') {
517 $line = str_replace($url, '', $line);
521 $map = InterWikiMap::GetMap($request);
522 $regexp = pcre_fix_posix_classes("!?(?<![[:alnum:]])")
523 . $map->getRegexp() . ":[^\\s.,;?()]+";
524 preg_match_all("/$regexp/", $line, $link);
525 foreach ($link[0] as $interlink) {
526 if ($interlink[0] <> '!') {
527 $link = $map->link($interlink);
528 $urls[$link->getAttr('href')] = 1;
530 $line = str_replace($interlink, '', $line);
533 // BumpyText old-style wiki links
534 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
535 for ($i = 0; isset($link[0][$i]); $i++) {
536 if($link[0][$i][0] <> '!') {
537 if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
538 $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
540 $wikilinks[$link[0][$i]] = 1;
546 return array(array_keys($wikilinks), array_keys($urls));
551 * Convert old page markup to new-style markup.
553 * @param string $text Old-style wiki markup.
555 * @param string $markup_type
557 * <dt><code>"block"</code> <dd>Convert all markup.
558 * <dt><code>"inline"</code> <dd>Convert only inline markup.
559 * <dt><code>"links"</code> <dd>Convert only link markup.
562 * @return string New-style wiki markup.
564 * @bugs Footnotes don't work quite as before (esp if there are
565 * multiple references to the same footnote. But close enough,
566 * probably for now....
568 function ConvertOldMarkup ($text, $markup_type = "block") {
573 /*****************************************************************
574 * Conversions for inline markup:
581 // escape escaped brackets
585 // change ! escapes to ~'s.
586 global $AllowedProtocols, $WikiNameRegexp, $request;
587 include_once('lib/interwiki.php');
588 $map = InterWikiMap::GetMap($request);
589 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
590 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
591 $bang_esc[] = $WikiNameRegexp;
592 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
595 $subs["links"] = array($orig, $repl);
598 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
601 // Convert footnote references.
602 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
603 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
605 // Convert old style emphases to HTML style emphasis.
606 $orig[] = '/__(.*?)__/';
607 $repl[] = '<strong>\\1</strong>';
608 $orig[] = "/''(.*?)''/";
609 $repl[] = '<em>\\1</em>';
612 $subs["inline"] = array($orig, $repl);
614 // Escape nestled markup. (two versions: inline & block)
615 $subs["inline"][0][] = '/^(?<=^|\s)[=_*](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
616 $subs["inline"][1][] = '/~\\0/';
617 $orig[] = '/^.*?(?:(?<=^|\s)[=_*](?=\S)|(?<=\S)[=_*](?=\s|$)).*$/me';
618 $repl[] = "_EscapeNestledMarkup('\\0')";
620 /*****************************************************************
621 * Conversions for block markup
623 // convert indented blocks to <pre></pre>.
624 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
625 $repl[] = "<pre>\n\\0</pre>\n";
628 $orig[] = '/(?:^\|.*\n)+/m';
629 $repl[] = "<?plugin OldStyleTable\n\\0?>\n";
632 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
633 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
635 // convert footnote definitions
636 $orig[] = '/^\[\s*(\d+)\s*\]/m';
637 $repl[] = '#[|ftnt_\\1]~[[\\1|#ftnt_ref_\\1]~]';
639 // in old markup headings only allowed at beginning of line
640 //$orig[] = '/(?<=[^!])!/';
641 $orig[] = '/([^\n!])!/';
644 $subs["block"] = array($orig, $repl);
647 list ($orig, $repl) = $subs[$markup_type];
648 if ($markup_type == "block" and substr($text,-1) != "\n")
650 return preg_replace($orig, $repl, $text);
653 function _ConvertOldListMarkup ($ind, $bullet) {
654 $indent = str_repeat(' ', strlen($ind));
655 if ($bullet[0] == ';') {
656 //$term = ltrim(substr($bullet, 1));
657 //return $indent . $term . "\n" . $indent . ' ';
658 return $ind . $bullet;
661 return $indent . $bullet . ' ';
664 function _EscapeNestledMarkup ($line) {
665 if (!preg_match('/^<\?plugin.*\?>/', $line))
666 $line = preg_replace('/[=_]|(?<!^|[*#;])\*/', '~\\0', $line);
672 * Expand tabs in string.
674 * Converts all tabs to (the appropriate number of) spaces.
677 * @param integer $tab_width
680 function expand_tabs($str, $tab_width = 8) {
681 $split = split("\t", $str);
682 $tail = array_pop($split);
684 foreach ($split as $hunk) {
686 $pos = strlen(strrchr($expanded, "\n")) - 1;
687 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
689 return substr($expanded, 1) . $tail;
693 * Split WikiWords in page names.
695 * It has been deemed useful to split WikiWords (into "Wiki Words") in
696 * places like page titles. This is rumored to help search engines
699 * @param $page string The page name.
701 * @return string The split name.
703 function split_pagename ($page) {
705 if (preg_match("/\s/", $page))
706 return $page; // Already split --- don't split any more.
708 // FIXME: this algorithm is Anglo-centric.
711 // This mess splits between a lower-case letter followed by
712 // either an upper-case or a numeral; except that it wont
713 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
714 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
715 // This the single-letter words 'I' and 'A' from any following
716 // capitalized words.
717 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
718 // Split numerals from following letters.
719 $RE[] = '/(\d)([[:alpha:]])/';
721 foreach ($RE as $key => $val)
722 $RE[$key] = pcre_fix_posix_classes($val);
724 if (isSubPage($page)) {
725 // FIXME: is this needed?
726 $pages = explode(SUBPAGE_SEPARATOR,$page);
727 $new_page = $pages[0] ? split_pagename($pages[0]) : '';
728 for ($i=1; $i < sizeof($pages); $i++) {
729 $new_page .= (SUBPAGE_SEPARATOR . ($pages[$i] ? split_pagename($pages[$i]) : ''));
733 foreach ($RE as $regexp) {
734 $page = preg_replace($regexp, '\\1 \\2', $page);
740 function NoSuchRevision (&$request, $page, $version) {
741 $html = HTML(HTML::h2(_("Revision Not Found")),
742 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
743 $version, WikiLink($page, 'auto'))));
744 include_once('lib/Template.php');
745 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
751 * Get time offset for local time zone.
753 * @param $time time_t Get offset for this time. Default: now.
754 * @param $no_colon boolean Don't put colon between hours and minutes.
755 * @return string Offset as a string in the format +HH:MM.
757 function TimezoneOffset ($time = false, $no_colon = false) {
760 $secs = date('Z', $time);
769 $colon = $no_colon ? '' : ':';
770 $mins = intval(($secs + 30) / 60);
771 return sprintf("%s%02d%s%02d",
772 $sign, $mins / 60, $colon, $mins % 60);
777 * Format time in ISO-8601 format.
779 * @param $time time_t Time. Default: now.
780 * @return string Date and time in ISO-8601 format.
782 function Iso8601DateTime ($time = false) {
785 $tzoff = TimezoneOffset($time);
786 $date = date('Y-m-d', $time);
787 $time = date('H:i:s', $time);
788 return $date . 'T' . $time . $tzoff;
792 * Format time in RFC-2822 format.
794 * @param $time time_t Time. Default: now.
795 * @return string Date and time in RFC-2822 format.
797 function Rfc2822DateTime ($time = false) {
800 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
804 * Format time to standard 'ctime' format.
806 * @param $time time_t Time. Default: now.
807 * @return string Date and time.
809 function CTime ($time = false)
813 return date("D M j H:i:s Y", $time);
819 * Internationalized printf.
821 * This is essentially the same as PHP's built-in printf
822 * with the following exceptions:
824 * <li> It passes the format string through gettext().
825 * <li> It supports the argument reordering extensions.
832 * __printf("Differences between versions %s and %s of %s",
833 * $new_link, $old_link, $page_link);
836 * Then in locale/po/de.po, one can reorder the printf arguments:
839 * msgid "Differences between %s and %s of %s."
840 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
843 * (Note that while PHP tries to expand $vars within double-quotes,
844 * the values in msgstr undergo no such expansion, so the '$'s
847 * One shouldn't use reordered arguments in the default format string.
848 * Backslashes in the default string would be necessary to escape the
849 * '$'s, and they'll cause all kinds of trouble....
851 function __printf ($fmt) {
852 $args = func_get_args();
854 echo __vsprintf($fmt, $args);
858 * Internationalized sprintf.
860 * This is essentially the same as PHP's built-in printf with the
861 * following exceptions:
864 * <li> It passes the format string through gettext().
865 * <li> It supports the argument reordering extensions.
870 function __sprintf ($fmt) {
871 $args = func_get_args();
873 return __vsprintf($fmt, $args);
877 * Internationalized vsprintf.
879 * This is essentially the same as PHP's built-in printf with the
880 * following exceptions:
883 * <li> It passes the format string through gettext().
884 * <li> It supports the argument reordering extensions.
889 function __vsprintf ($fmt, $args) {
890 $fmt = gettext($fmt);
891 // PHP's sprintf doesn't support variable with specifiers,
892 // like sprintf("%*s", 10, "x"); --- so we won't either.
894 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
895 // Format string has '%2$s' style argument reordering.
896 // PHP doesn't support this.
897 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
898 // literal variable name substitution only to keep locale
899 // strings uncluttered
900 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
901 '%1\$s','%s'), E_USER_WARNING); //php+locale error
903 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
906 // Reorder arguments appropriately.
907 foreach($m[1] as $argnum) {
908 if ($argnum < 1 || $argnum > count($args))
909 trigger_error(sprintf(_("%s: argument index out of range"),
910 $argnum), E_USER_WARNING);
911 $newargs[] = $args[$argnum - 1];
916 // Not all PHP's have vsprintf, so...
917 array_unshift($args, $fmt);
918 return call_user_func_array('sprintf', $args);
924 * Build an array in $this->_fileList of files from $dirname.
925 * Subdirectories are not traversed.
927 * (This was a function LoadDir in lib/loadsave.php)
928 * See also http://www.php.net/manual/en/function.readdir.php
930 function getFiles() {
931 return $this->_fileList;
934 function _filenameSelector($filename) {
935 if (! $this->_pattern)
938 return glob_match ($this->_pattern, $filename, $this->_case);
942 function fileSet($directory, $filepattern = false) {
943 $this->_fileList = array();
944 $this->_pattern = $filepattern;
945 $this->_case = !isWindows();
946 $this->_pathsep = '/';
948 if (empty($directory)) {
949 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
951 return; // early return
954 @ $dir_handle = opendir($dir=$directory);
955 if (empty($dir_handle)) {
956 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
957 $dir), E_USER_NOTICE);
958 return; // early return
961 while ($filename = readdir($dir_handle)) {
962 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
964 if ($this->_filenameSelector($filename)) {
965 array_push($this->_fileList, "$filename");
966 //trigger_error(sprintf(_("found file %s"), $filename),
967 // E_USER_NOTICE); //debugging
970 closedir($dir_handle);
976 // expands a list containing regex's to its matching entries
977 class ListRegexExpand {
978 var $match, $list, $index, $case_sensitive;
979 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
980 $this->match = str_replace('/','\/',$match);
981 $this->list = &$list;
982 $this->case_sensitive = $case_sensitive;
984 function listMatchCallback ($item, $key) {
985 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
986 unset($this->list[$this->index]);
987 $this->list[] = $item;
990 function expandRegex ($index, &$pages) {
991 $this->index = $index;
992 array_walk($pages, array($this, 'listMatchCallback'));
997 // convert fileglob to regex style
998 function glob_to_pcre ($glob) {
999 $re = preg_replace('/\./', '\\.', $glob);
1000 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1001 if (!preg_match('/^[\?\*]/',$glob))
1003 if (!preg_match('/[\?\*]$/',$glob))
1008 function glob_match ($glob, $against, $case_sensitive = true) {
1009 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1012 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1013 $list = explode(',',$input);
1014 // expand wildcards from list of $allnames
1015 if (preg_match('/[\?\*]/',$input)) {
1016 for ($i = 0; $i <= sizeof($list); $i++) {
1018 if (preg_match('/[\?\*]/',$f)) {
1020 $expand = new ListRegexExpand(&$list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1021 $expand->expandRegex($i, &$allnames);
1028 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1030 function explodePageList($input, $perm = false) {
1031 // expand wildcards from list of all pages
1032 if (preg_match('/[\?\*]/',$input)) {
1033 $dbi = $GLOBALS['request']->_dbi;
1034 $allPagehandles = $dbi->getAllPages($perm);
1035 while ($pagehandle = $allPagehandles->next()) {
1036 $allPages[] = $pagehandle->getName();
1038 return explodeList($input, &$allPages);
1040 return explode(',',$input);
1044 // Class introspections
1046 /** Determine whether object is of a specified type.
1048 * @param $object object An object.
1049 * @param $class string Class name.
1050 * @return bool True iff $object is a $class
1051 * or a sub-type of $class.
1053 function isa ($object, $class)
1055 $lclass = strtolower($class);
1057 return is_object($object)
1058 && ( get_class($object) == strtolower($lclass)
1059 || is_subclass_of($object, $lclass) );
1062 /** Determine whether (possible) object has method.
1064 * @param $object mixed Object
1065 * @param $method string Method name
1066 * @return bool True iff $object is an object with has method $method.
1068 function can ($object, $method)
1070 return is_object($object) && method_exists($object, strtolower($method));
1074 * Seed the random number generator.
1076 * better_srand() ensures the randomizer is seeded only once.
1078 * How random do you want it? See:
1079 * http://www.php.net/manual/en/function.srand.php
1080 * http://www.php.net/manual/en/function.mt-srand.php
1082 function better_srand($seed = '') {
1083 static $wascalled = FALSE;
1085 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1088 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1093 * Recursively count all non-empty elements
1094 * in array of any dimension or mixed - i.e.
1095 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1096 * See http://www.php.net/manual/en/function.count.php
1098 function count_all($arg) {
1099 // skip if argument is empty
1101 //print_r($arg); //debugging
1103 // not an array, return 1 (base case)
1106 // else call recursively for all elements $arg
1107 foreach($arg as $key => $val)
1108 $count += count_all($val);
1113 function isSubPage($pagename) {
1114 return (strstr($pagename, SUBPAGE_SEPARATOR));
1117 function subPageSlice($pagename, $pos) {
1118 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1119 $pages = array_slice($pages,$pos,1);
1124 // (c-file-style: "gnu")
1128 // c-basic-offset: 4
1129 // c-hanging-comment-ender-p: nil
1130 // indent-tabs-mode: nil