1 <?php //rcs_id('$Id: stdlib.php,v 1.149 2003-03-26 19:37:08 dairiki Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
6 IconForLink($protocol_or_url)
7 LinkURL($url, $linktext)
10 SplitQueryArgs ($query_args)
11 LinkPhpwikiURL($url, $text)
12 ConvertOldMarkup($content)
14 class Stack { push($item), pop(), cnt(), top() }
16 split_pagename ($page)
17 NoSuchRevision ($request, $page, $version)
18 TimezoneOffset ($time, $no_colon)
19 Iso8601DateTime ($time)
20 Rfc2822DateTime ($time)
24 __vsprintf ($fmt, $args)
25 better_srand($seed = '')
28 subPageSlice($pagename, $pos)
29 explodePageList($input, $perm = false)
31 function: LinkInterWikiLink($link, $linktext)
32 moved to: lib/interwiki.php
33 function: linkExistingWikiWord($wikiword, $linktext, $version)
34 moved to: lib/Theme.php
35 function: LinkUnknownWikiWord($wikiword, $linktext)
36 moved to: lib/Theme.php
37 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
38 gone see: lib/plugin/RecentChanges.php
41 define('MAX_PAGENAME_LENGTH', 100);
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->name;
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);
131 /** Convert relative URL to absolute URL.
133 * This converts a relative URL to one of PhpWiki's support files
134 * to an absolute one.
137 * @return string Absolute URL
139 function AbsoluteURL ($url) {
140 if (preg_match('/^https?:/', $url))
142 if ($url[0] != '/') {
143 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
144 while ($base != '/' and substr($url, 0, 3) == "../") {
145 $url = substr($url, 3);
146 $base = dirname($base);
152 return SERVER_URL . $url;
156 * Generates icon in front of links.
158 * @param string $protocol_or_url URL or protocol to determine which icon to use.
160 * @return HtmlElement HtmlElement object that contains data to create img link to
161 * icon for use with url or protocol passed to the function. False if no img to be
164 function IconForLink($protocol_or_url) {
166 if ($filename_suffix = false) {
167 // display apache style icon for file type instead of protocol icon
168 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
169 // - document: html, htm, text, txt, rtf, pdf, doc
170 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
171 // - audio: mp3,mp2,aiff,aif,au
172 // - multimedia: mpeg,mpg,mov,qt
174 list ($proto) = explode(':', $protocol_or_url, 2);
175 $src = $Theme->getLinkIconURL($proto);
177 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
184 * Glue icon in front of text.
186 * @param string $protocol_or_url Protocol or URL. Used to determine the
188 * @param string $text The text.
189 * @return XmlContent.
191 function PossiblyGlueIconToText($proto_or_url, $text) {
192 $icon = IconForLink($proto_or_url);
194 if (!is_object($text)) {
195 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
196 list (, $first_word, $tail) = $m;
203 $text = HTML::span(array('style' => 'white-space: nowrap'),
206 $text = HTML($text, $tail);
212 * Determines if the url passed to function is safe, by detecting if the characters
213 * '<', '>', or '"' are present.
215 * @param string $url URL to check for unsafe characters.
216 * @return boolean True if same, false else.
218 function IsSafeURL($url) {
219 return !ereg('[<>"]', $url);
223 * Generates an HtmlElement object to store data for a link.
225 * @param string $url URL that the link will point to.
226 * @param string $linktext Text to be displayed as link.
227 * @return HtmlElement HtmlElement object that contains data to construct an html link.
229 function LinkURL($url, $linktext = '') {
230 // FIXME: Is this needed (or sufficient?)
231 if(! IsSafeURL($url)) {
232 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
233 _("BAD URL -- remove all of <, >, \"")));
237 $linktext = preg_replace("/mailto:/A", "", $url);
239 $link = HTML::a(array('href' => $url),
240 PossiblyGlueIconToText($url, $linktext));
243 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
248 function LinkImage($url, $alt = false) {
249 // FIXME: Is this needed (or sufficient?)
250 if(! IsSafeURL($url)) {
251 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
252 _("BAD URL -- remove all of <, >, \"")));
257 $link = HTML::img(array('src' => $url, 'alt' => $alt));
259 $link->setAttr('class', 'inlineimage');
266 var $items = array();
269 function push($item) {
270 $this->items[$this->size] = $item;
276 if ($this->size == 0) {
277 return false; // stack is empty
280 return $this->items[$this->size];
289 return $this->items[$this->size - 1];
295 // end class definition
297 function SplitQueryArgs ($query_args = '')
299 $split_args = split('&', $query_args);
301 while (list($key, $val) = each($split_args))
302 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
303 $args[$m[1]] = $m[2];
307 function LinkPhpwikiURL($url, $text = '', $basepage) {
310 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
311 return HTML::strong(array('class' => 'rawurl'),
312 HTML::u(array('class' => 'baduri'),
313 _("BAD phpwiki: URL")));
317 $pagename = urldecode($m[1]);
320 if (empty($pagename) &&
321 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
322 // Convert old style links (to not break diff links in
324 $pagename = urldecode($m[2]);
325 $args = array("action" => $m[1]);
328 $args = SplitQueryArgs($qargs);
331 if (empty($pagename))
332 $pagename = $GLOBALS['request']->getArg('pagename');
334 if (isset($args['action']) && $args['action'] == 'browse')
335 unset($args['action']);
338 if (empty($args['action']))
340 else if (is_safe_action($args['action']))
341 $class = 'wikiaction';
343 if (empty($args['action']) || is_safe_action($args['action']))
344 $class = 'wikiaction';
346 // Don't allow administrative links on unlocked pages.
347 $dbi = $GLOBALS['request']->getDbh();
348 $page = $dbi->getPage($basepage);
349 if (!$page->get('locked'))
350 return HTML::span(array('class' => 'wikiunsafe'),
351 HTML::u(_("Lock page to enable link")));
352 $class = 'wikiadmin';
356 $text = HTML::span(array('class' => 'rawurl'), $url);
358 $wikipage = new WikiPageName($pagename);
359 if (!$wikipage->isValid()) {
361 return $Theme->linkBadWikiWord($wikipage, $url);
364 return HTML::a(array('href' => WikiURL($pagename, $args),
370 * A class to assist in parsing wiki pagenames.
372 * Now with subpages and anchors, parsing and passing around
373 * pagenames is more complicated. This should help.
377 /** Short name for page.
379 * This is the value of $name passed to the constructor.
380 * (For use, e.g. as a default label for links to the page.)
384 /** The full page name.
386 * This is the full name of the page (without anchor).
392 * This is the referenced anchor within the page, or the empty string.
398 * @param mixed $name Page name.
399 * WikiDB_Page, WikiDB_PageRevision, or string.
400 * This can be a relative subpage name (like '/SubPage'),
401 * or can be the empty string to refer to the $basename.
403 * @param string $anchor For links to anchors in page.
405 * @param mixed $basename Page name from which to interpret
406 * relative or other non-fully-specified page names.
408 function WikiPageName($name, $basename=false, $anchor=false) {
409 if (is_string($name)) {
410 $this->shortName = $name;
412 if (empty($name) or $name[0] == SUBPAGE_SEPARATOR) {
414 $name = $this->_pagename($basename) . $name;
416 $name = $this->_normalize_bad_pagename($name);
420 $name = $this->_pagename($name);
421 $this->shortName = $name;
424 $this->name = $this->_check($name);
425 $this->anchor = (string)$anchor;
428 function getParent() {
430 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
432 return substr($name, 0, -strlen($tail));
435 function isValid($strict = false) {
437 return !isset($this->_errors);
438 return !empty($this->name);
441 function getWarnings() {
443 if (isset($this->_warnings))
444 $warnings = array_merge($warnings, $this->_warnings);
445 if (isset($this->_errors))
446 $warnings = array_merge($warnings, $this->_errors);
450 return sprintf(_("'%s': Bad page name: %s"),
451 $this->shortName, join(', ', $warnings));
454 function _pagename($page) {
455 if (isa($page, 'WikiDB_Page'))
456 return $page->getName();
457 elseif (isa($page, 'WikiDB_PageRevision'))
458 return $page->getPageName();
459 elseif (isa($page, 'WikiPageName'))
461 if (!is_string($page)) {
462 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
463 $page, gettype($page), get_class($page)),
466 //assert(is_string($page));
470 function _normalize_bad_pagename($name) {
471 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
473 // Punt... You really shouldn't get here.
476 return $request->getArg('pagename');
478 assert($name[0] == SUBPAGE_SEPARATOR);
479 return substr($name, 1);
483 function _check($pagename) {
484 // Compress internal white-space to single space character.
485 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
486 if ($pagename != $orig)
487 $this->_warnings[] = _("White space converted to single space");
489 // Delete any control characters.
490 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
491 if ($pagename != $orig)
492 $this->_errors[] = _("Control characters not allowed");
494 // Strip leading and trailing white-space.
495 $pagename = trim($pagename);
498 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
499 $pagename = substr($pagename, 1);
500 if ($pagename != $orig)
501 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
503 if (preg_match('/[:;]/', $pagename))
504 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
506 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
507 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
508 $this->_errors[] = _("too long");
512 if ($pagename == '.' or $pagename == '..') {
513 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
522 * Convert old page markup to new-style markup.
524 * @param string $text Old-style wiki markup.
526 * @param string $markup_type
528 * <dt><code>"block"</code> <dd>Convert all markup.
529 * <dt><code>"inline"</code> <dd>Convert only inline markup.
530 * <dt><code>"links"</code> <dd>Convert only link markup.
533 * @return string New-style wiki markup.
535 * @bugs Footnotes don't work quite as before (esp if there are
536 * multiple references to the same footnote. But close enough,
537 * probably for now....
539 function ConvertOldMarkup ($text, $markup_type = "block") {
545 /*****************************************************************
546 * Conversions for inline markup:
553 // escape escaped brackets
557 // change ! escapes to ~'s.
558 global $AllowedProtocols, $WikiNameRegexp, $request;
559 include_once('lib/interwiki.php');
560 $map = InterWikiMap::GetMap($request);
561 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
562 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
563 $bang_esc[] = $WikiNameRegexp;
564 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
567 $subs["links"] = array($orig, $repl);
570 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
573 // Convert footnote references.
574 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
575 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
577 // Convert old style emphases to HTML style emphasis.
578 $orig[] = '/__(.*?)__/';
579 $repl[] = '<strong>\\1</strong>';
580 $orig[] = "/''(.*?)''/";
581 $repl[] = '<em>\\1</em>';
583 // Escape nestled markup.
584 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
587 // in old markup headings only allowed at beginning of line
591 $subs["inline"] = array($orig, $repl);
593 /*****************************************************************
594 * Patterns which match block markup constructs which take
595 * special handling...
599 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
602 $blockpats[] = '\|(?:.*\n\|)*';
605 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
607 // Footnote definitions
608 $blockpats[] = '\[\s*(\d+)\s*\]';
611 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
614 $blockpats[] = '!{1,3}[^!]';
616 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
617 . join("|", $blockpats)
622 if ($markup_type != "block") {
623 list ($orig, $repl) = $subs[$markup_type];
624 return preg_replace($orig, $repl, $text);
627 list ($orig, $repl) = $subs['inline'];
629 while (preg_match($block_re, $text, $m)) {
630 $text = substr($text, strlen($m[0]));
631 list (,$leading_text, $block) = $m;
634 if (strchr(" \t", $block[0])) {
637 $suffix = "\n</pre>\n";
639 elseif ($block[0] == '|') {
641 $prefix = "<?plugin OldStyleTable\n";
644 elseif (strchr("#*;", $block[0])) {
645 // Old-style list item
646 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
647 list (,$ind,$bullet) = $m;
648 $block = substr($block, strlen($m[0]));
650 $indent = str_repeat(' ', strlen($ind));
651 if ($bullet[0] == ';') {
652 //$term = ltrim(substr($bullet, 1));
653 //return $indent . $term . "\n" . $indent . ' ';
654 $prefix = $ind . $bullet;
657 $prefix = $indent . $bullet . ' ';
659 elseif ($block[0] == '[') {
660 // Footnote definition
661 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
663 $block = substr($block, strlen($m[0]));
664 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
666 elseif ($block[0] == '<') {
668 // HACK: no inline markup...
672 elseif ($block[0] == '!') {
674 preg_match('/^!{1,3}/', $block, $m);
676 $block = substr($block, strlen($m[0]));
683 $out .= ( preg_replace($orig, $repl, $leading_text)
685 . preg_replace($orig, $repl, $block)
688 return $out . preg_replace($orig, $repl, $text);
694 * Expand tabs in string.
696 * Converts all tabs to (the appropriate number of) spaces.
699 * @param integer $tab_width
702 function expand_tabs($str, $tab_width = 8) {
703 $split = split("\t", $str);
704 $tail = array_pop($split);
706 foreach ($split as $hunk) {
708 $pos = strlen(strrchr($expanded, "\n")) - 1;
709 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
711 return substr($expanded, 1) . $tail;
715 * Split WikiWords in page names.
717 * It has been deemed useful to split WikiWords (into "Wiki Words") in
718 * places like page titles. This is rumored to help search engines
721 * @param $page string The page name.
723 * @return string The split name.
725 function split_pagename ($page) {
727 if (preg_match("/\s/", $page))
728 return $page; // Already split --- don't split any more.
730 // FIXME: this algorithm is Anglo-centric.
733 // This mess splits between a lower-case letter followed by
734 // either an upper-case or a numeral; except that it wont
735 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
736 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
737 // This the single-letter words 'I' and 'A' from any following
738 // capitalized words.
739 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
740 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
741 // Split numerals from following letters.
742 $RE[] = '/(\d)([[:alpha:]])/';
744 foreach ($RE as $key => $val)
745 $RE[$key] = pcre_fix_posix_classes($val);
748 foreach ($RE as $regexp) {
749 $page = preg_replace($regexp, '\\1 \\2', $page);
754 function NoSuchRevision (&$request, $page, $version) {
755 $html = HTML(HTML::h2(_("Revision Not Found")),
756 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
757 $version, WikiLink($page, 'auto'))));
758 include_once('lib/Template.php');
759 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
765 * Get time offset for local time zone.
767 * @param $time time_t Get offset for this time. Default: now.
768 * @param $no_colon boolean Don't put colon between hours and minutes.
769 * @return string Offset as a string in the format +HH:MM.
771 function TimezoneOffset ($time = false, $no_colon = false) {
774 $secs = date('Z', $time);
783 $colon = $no_colon ? '' : ':';
784 $mins = intval(($secs + 30) / 60);
785 return sprintf("%s%02d%s%02d",
786 $sign, $mins / 60, $colon, $mins % 60);
791 * Format time in ISO-8601 format.
793 * @param $time time_t Time. Default: now.
794 * @return string Date and time in ISO-8601 format.
796 function Iso8601DateTime ($time = false) {
799 $tzoff = TimezoneOffset($time);
800 $date = date('Y-m-d', $time);
801 $time = date('H:i:s', $time);
802 return $date . 'T' . $time . $tzoff;
806 * Format time in RFC-2822 format.
808 * @param $time time_t Time. Default: now.
809 * @return string Date and time in RFC-2822 format.
811 function Rfc2822DateTime ($time = false) {
814 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
818 * Format time in RFC-1123 format.
820 * @param $time time_t Time. Default: now.
821 * @return string Date and time in RFC-1123 format.
823 function Rfc1123DateTime ($time = false) {
826 return gmdate('D, d M Y H:i:s \G\M\T', $time);
829 /** Parse date in RFC-1123 format.
831 * According to RFC 1123 we must accept dates in the following
834 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
835 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
836 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
838 * (Though we're only allowed to generate dates in the first format.)
840 function ParseRfc1123DateTime ($timestr) {
841 $timestr = trim($timestr);
842 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
843 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
845 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
847 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
848 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
850 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
851 if ($year < 70) $year += 2000;
852 elseif ($year < 100) $year += 1900;
854 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
855 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
857 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
864 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
866 return false; // failed
871 * Format time to standard 'ctime' format.
873 * @param $time time_t Time. Default: now.
874 * @return string Date and time.
876 function CTime ($time = false)
880 return date("D M j H:i:s Y", $time);
886 * Internationalized printf.
888 * This is essentially the same as PHP's built-in printf
889 * with the following exceptions:
891 * <li> It passes the format string through gettext().
892 * <li> It supports the argument reordering extensions.
899 * __printf("Differences between versions %s and %s of %s",
900 * $new_link, $old_link, $page_link);
903 * Then in locale/po/de.po, one can reorder the printf arguments:
906 * msgid "Differences between %s and %s of %s."
907 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
910 * (Note that while PHP tries to expand $vars within double-quotes,
911 * the values in msgstr undergo no such expansion, so the '$'s
914 * One shouldn't use reordered arguments in the default format string.
915 * Backslashes in the default string would be necessary to escape the
916 * '$'s, and they'll cause all kinds of trouble....
918 function __printf ($fmt) {
919 $args = func_get_args();
921 echo __vsprintf($fmt, $args);
925 * Internationalized sprintf.
927 * This is essentially the same as PHP's built-in printf with the
928 * following exceptions:
931 * <li> It passes the format string through gettext().
932 * <li> It supports the argument reordering extensions.
937 function __sprintf ($fmt) {
938 $args = func_get_args();
940 return __vsprintf($fmt, $args);
944 * Internationalized vsprintf.
946 * This is essentially the same as PHP's built-in printf with the
947 * following exceptions:
950 * <li> It passes the format string through gettext().
951 * <li> It supports the argument reordering extensions.
956 function __vsprintf ($fmt, $args) {
957 $fmt = gettext($fmt);
958 // PHP's sprintf doesn't support variable with specifiers,
959 // like sprintf("%*s", 10, "x"); --- so we won't either.
961 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
962 // Format string has '%2$s' style argument reordering.
963 // PHP doesn't support this.
964 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
965 // literal variable name substitution only to keep locale
966 // strings uncluttered
967 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
968 '%1\$s','%s'), E_USER_WARNING); //php+locale error
970 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
973 // Reorder arguments appropriately.
974 foreach($m[1] as $argnum) {
975 if ($argnum < 1 || $argnum > count($args))
976 trigger_error(sprintf(_("%s: argument index out of range"),
977 $argnum), E_USER_WARNING);
978 $newargs[] = $args[$argnum - 1];
983 // Not all PHP's have vsprintf, so...
984 array_unshift($args, $fmt);
985 return call_user_func_array('sprintf', $args);
991 * Build an array in $this->_fileList of files from $dirname.
992 * Subdirectories are not traversed.
994 * (This was a function LoadDir in lib/loadsave.php)
995 * See also http://www.php.net/manual/en/function.readdir.php
997 function getFiles() {
998 return $this->_fileList;
1001 function _filenameSelector($filename) {
1002 if (! $this->_pattern)
1005 return glob_match ($this->_pattern, $filename, $this->_case);
1009 function fileSet($directory, $filepattern = false) {
1010 $this->_fileList = array();
1011 $this->_pattern = $filepattern;
1012 $this->_case = !isWindows();
1013 $this->_pathsep = '/';
1015 if (empty($directory)) {
1016 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1018 return; // early return
1021 @ $dir_handle = opendir($dir=$directory);
1022 if (empty($dir_handle)) {
1023 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1024 $dir), E_USER_NOTICE);
1025 return; // early return
1028 while ($filename = readdir($dir_handle)) {
1029 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1031 if ($this->_filenameSelector($filename)) {
1032 array_push($this->_fileList, "$filename");
1033 //trigger_error(sprintf(_("found file %s"), $filename),
1034 // E_USER_NOTICE); //debugging
1037 closedir($dir_handle);
1043 // expands a list containing regex's to its matching entries
1044 class ListRegexExpand {
1045 var $match, $list, $index, $case_sensitive;
1046 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1047 $this->match = str_replace('/','\/',$match);
1048 $this->list = &$list;
1049 $this->case_sensitive = $case_sensitive;
1051 function listMatchCallback ($item, $key) {
1052 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1053 unset($this->list[$this->index]);
1054 $this->list[] = $item;
1057 function expandRegex ($index, &$pages) {
1058 $this->index = $index;
1059 array_walk($pages, array($this, 'listMatchCallback'));
1064 // convert fileglob to regex style
1065 function glob_to_pcre ($glob) {
1066 $re = preg_replace('/\./', '\\.', $glob);
1067 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1068 if (!preg_match('/^[\?\*]/',$glob))
1070 if (!preg_match('/[\?\*]$/',$glob))
1075 function glob_match ($glob, $against, $case_sensitive = true) {
1076 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1079 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1080 $list = explode(',',$input);
1081 // expand wildcards from list of $allnames
1082 if (preg_match('/[\?\*]/',$input)) {
1083 for ($i = 0; $i < sizeof($list); $i++) {
1085 if (preg_match('/[\?\*]/',$f)) {
1087 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1088 $expand->expandRegex($i, $allnames);
1095 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1097 function explodePageList($input, $perm = false) {
1098 // expand wildcards from list of all pages
1099 if (preg_match('/[\?\*]/',$input)) {
1100 $dbi = $GLOBALS['request']->_dbi;
1101 $allPagehandles = $dbi->getAllPages($perm);
1102 while ($pagehandle = $allPagehandles->next()) {
1103 $allPages[] = $pagehandle->getName();
1105 return explodeList($input, $allPages);
1107 return explode(',',$input);
1111 // Class introspections
1113 /** Determine whether object is of a specified type.
1115 * @param $object object An object.
1116 * @param $class string Class name.
1117 * @return bool True iff $object is a $class
1118 * or a sub-type of $class.
1120 function isa ($object, $class)
1122 $lclass = strtolower($class);
1124 return is_object($object)
1125 && ( get_class($object) == strtolower($lclass)
1126 || is_subclass_of($object, $lclass) );
1129 /** Determine whether (possible) object has method.
1131 * @param $object mixed Object
1132 * @param $method string Method name
1133 * @return bool True iff $object is an object with has method $method.
1135 function can ($object, $method)
1137 return is_object($object) && method_exists($object, strtolower($method));
1140 /** Determine whether a function is okay to use.
1142 * Some providers (e.g. Lycos) disable some of PHP functions for
1143 * "security reasons." This makes those functions, of course,
1144 * unusable, despite the fact the function_exists() says they
1147 * This function test to see if a function exists and is not
1148 * disallowed by PHP's disable_functions config setting.
1150 * @param string $function_name Function name
1151 * @return bool True iff function can be used.
1153 function function_usable($function_name)
1156 if (!is_array($disabled)) {
1157 $disabled = array();
1158 // Use get_cfg_var since ini_get() is one of the disabled functions
1159 // (on Lycos, at least.)
1160 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1161 foreach ($split as $f)
1162 $disabled[strtolower($f)] = true;
1165 return ( function_exists($function_name)
1166 and ! isset($disabled[strtolower($function_name)])
1173 * This is used for generating ETags.
1175 function hash ($x) {
1176 if (is_scalar($x)) {
1179 elseif (is_array($x)) {
1181 return md5(serialize($x));
1183 elseif (is_object($x)) {
1186 trigger_error("Can't hash $x", E_USER_ERROR);
1191 * Seed the random number generator.
1193 * better_srand() ensures the randomizer is seeded only once.
1195 * How random do you want it? See:
1196 * http://www.php.net/manual/en/function.srand.php
1197 * http://www.php.net/manual/en/function.mt-srand.php
1199 function better_srand($seed = '') {
1200 static $wascalled = FALSE;
1202 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1205 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1210 * Recursively count all non-empty elements
1211 * in array of any dimension or mixed - i.e.
1212 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1213 * See http://www.php.net/manual/en/function.count.php
1215 function count_all($arg) {
1216 // skip if argument is empty
1218 //print_r($arg); //debugging
1220 // not an array, return 1 (base case)
1223 // else call recursively for all elements $arg
1224 foreach($arg as $key => $val)
1225 $count += count_all($val);
1230 function isSubPage($pagename) {
1231 return (strstr($pagename, SUBPAGE_SEPARATOR));
1234 function subPageSlice($pagename, $pos) {
1235 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1236 $pages = array_slice($pages,$pos,1);
1243 * Class for "popping up" and alert box. (Except that right now, it doesn't
1247 * This is a hackish and needs to be refactored. However it would be nice to
1248 * unify all the different methods we use for showing Alerts and Dialogs.
1249 * (E.g. "Page deleted", login form, ...)
1254 * @param object $request
1255 * @param mixed $head Header ("title") for alert box.
1256 * @param mixed $body The text in the alert box.
1257 * @param hash $buttons An array mapping button labels to URLs.
1258 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1260 function Alert($head, $body, $buttons=false) {
1261 if ($buttons === false)
1264 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1265 $this->_buttons = $buttons;
1269 * Show the alert box.
1271 function show(&$request) {
1274 $tokens = $this->_tokens;
1275 $tokens['BUTTONS'] = $this->_getButtons();
1277 $request->discardOutput();
1278 $tmpl = new Template('dialog', $request, $tokens);
1284 function _getButtons() {
1287 $buttons = $this->_buttons;
1289 $buttons = array(_("Okay") => $request->getURLtoSelf());
1292 foreach ($buttons as $label => $url)
1293 print "$label $url\n";
1294 $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1295 return new XmlContent($out);
1301 // $Log: not supported by cvs2svn $
1302 // Revision 1.148 2003/03/25 21:03:02 dairiki
1303 // Cleanup debugging output.
1305 // Revision 1.147 2003/03/13 20:17:05 dairiki
1306 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1308 // Revision 1.146 2003/03/07 02:46:24 dairiki
1309 // function_usable(): New function.
1311 // Revision 1.145 2003/03/04 01:55:05 dairiki
1312 // Fix to ensure absolute URL for logo in RSS recent changes.
1314 // Revision 1.144 2003/02/26 00:39:30 dairiki
1315 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1316 // being displayed at incorrect times.
1318 // Revision 1.143 2003/02/26 00:10:26 dairiki
1319 // More/better/different checks for bad page names.
1321 // Revision 1.142 2003/02/25 22:19:46 dairiki
1322 // Add some sanity checking for pagenames.
1324 // Revision 1.141 2003/02/22 20:49:55 dairiki
1325 // Fixes for "Call-time pass by reference has been deprecated" errors.
1327 // Revision 1.140 2003/02/21 23:33:29 dairiki
1328 // Set alt="" on the link icon image tags.
1329 // (See SF bug #675141.)
1331 // Revision 1.139 2003/02/21 22:16:27 dairiki
1332 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1333 // These have been obsolete for quite awhile (I hope).
1335 // Revision 1.138 2003/02/21 04:12:36 dairiki
1336 // WikiPageName: fixes for new cached links.
1338 // Alert: new class for displaying alerts.
1340 // ExtractWikiPageLinks and friends are now gone.
1342 // LinkBracketLink moved to InlineParser.php
1344 // Revision 1.137 2003/02/18 23:13:40 dairiki
1345 // Wups again. Typo fix.
1347 // Revision 1.136 2003/02/18 21:52:07 dairiki
1348 // Fix so that one can still link to wiki pages with # in their names.
1349 // (This was made difficult by the introduction of named tags, since
1350 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1352 // Now the ~ escape for page names should work: [Page ~#1].
1354 // Revision 1.135 2003/02/18 19:17:04 dairiki
1355 // split_pagename():
1356 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1357 // Cleanup up subpage splitting code.
1359 // Revision 1.134 2003/02/16 19:44:20 dairiki
1360 // New function hash(). This is a helper, primarily for generating
1363 // Revision 1.133 2003/02/16 04:50:09 dairiki
1365 // Rfc1123DateTime(), ParseRfc1123DateTime()
1366 // for converting unix timestamps to and from strings.
1368 // These functions produce and grok the time strings
1369 // in the format specified by RFC 2616 for use in HTTP headers
1370 // (like Last-Modified).
1372 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1373 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1374 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1377 // (c-file-style: "gnu")
1381 // c-basic-offset: 4
1382 // c-hanging-comment-ender-p: nil
1383 // indent-tabs-mode: nil