1 <?php //rcs_id('$Id: stdlib.php,v 1.144 2003-02-26 00:39:30 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);
132 * Generates icon in front of links.
134 * @param string $protocol_or_url URL or protocol to determine which icon to use.
136 * @return HtmlElement HtmlElement object that contains data to create img link to
137 * icon for use with url or protocol passed to the function. False if no img to be
140 function IconForLink($protocol_or_url) {
142 if ($filename_suffix = false) {
143 // display apache style icon for file type instead of protocol icon
144 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
145 // - document: html, htm, text, txt, rtf, pdf, doc
146 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
147 // - audio: mp3,mp2,aiff,aif,au
148 // - multimedia: mpeg,mpg,mov,qt
150 list ($proto) = explode(':', $protocol_or_url, 2);
151 $src = $Theme->getLinkIconURL($proto);
153 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
160 * Glue icon in front of text.
162 * @param string $protocol_or_url Protocol or URL. Used to determine the
164 * @param string $text The text.
165 * @return XmlContent.
167 function PossiblyGlueIconToText($proto_or_url, $text) {
168 $icon = IconForLink($proto_or_url);
170 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
171 list (, $first_word, $tail) = $m;
172 $text = HTML::span(array('style' => 'white-space: nowrap'),
175 $text = HTML($text, $tail);
181 * Determines if the url passed to function is safe, by detecting if the characters
182 * '<', '>', or '"' are present.
184 * @param string $url URL to check for unsafe characters.
185 * @return boolean True if same, false else.
187 function IsSafeURL($url) {
188 return !ereg('[<>"]', $url);
192 * Generates an HtmlElement object to store data for a link.
194 * @param string $url URL that the link will point to.
195 * @param string $linktext Text to be displayed as link.
196 * @return HtmlElement HtmlElement object that contains data to construct an html link.
198 function LinkURL($url, $linktext = '') {
199 // FIXME: Is this needed (or sufficient?)
200 if(! IsSafeURL($url)) {
201 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
202 _("BAD URL -- remove all of <, >, \"")));
206 $linktext = preg_replace("/mailto:/A", "", $url);
208 $link = HTML::a(array('href' => $url),
209 PossiblyGlueIconToText($url, $linktext));
212 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
217 function LinkImage($url, $alt = false) {
218 // FIXME: Is this needed (or sufficient?)
219 if(! IsSafeURL($url)) {
220 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
221 _("BAD URL -- remove all of <, >, \"")));
226 $link = HTML::img(array('src' => $url, 'alt' => $alt));
228 $link->setAttr('class', 'inlineimage');
235 var $items = array();
238 function push($item) {
239 $this->items[$this->size] = $item;
245 if ($this->size == 0) {
246 return false; // stack is empty
249 return $this->items[$this->size];
258 return $this->items[$this->size - 1];
264 // end class definition
266 function SplitQueryArgs ($query_args = '')
268 $split_args = split('&', $query_args);
270 while (list($key, $val) = each($split_args))
271 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
272 $args[$m[1]] = $m[2];
276 function LinkPhpwikiURL($url, $text = '', $basepage) {
279 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
280 return HTML::strong(array('class' => 'rawurl'),
281 HTML::u(array('class' => 'baduri'),
282 _("BAD phpwiki: URL")));
286 $pagename = urldecode($m[1]);
289 if (empty($pagename) &&
290 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
291 // Convert old style links (to not break diff links in
293 $pagename = urldecode($m[2]);
294 $args = array("action" => $m[1]);
297 $args = SplitQueryArgs($qargs);
300 if (empty($pagename))
301 $pagename = $GLOBALS['request']->getArg('pagename');
303 if (isset($args['action']) && $args['action'] == 'browse')
304 unset($args['action']);
307 if (empty($args['action']))
309 else if (is_safe_action($args['action']))
310 $class = 'wikiaction';
312 if (empty($args['action']) || is_safe_action($args['action']))
313 $class = 'wikiaction';
315 // Don't allow administrative links on unlocked pages.
316 $dbi = $GLOBALS['request']->getDbh();
317 $page = $dbi->getPage($basepage);
318 if (!$page->get('locked'))
319 return HTML::span(array('class' => 'wikiunsafe'),
320 HTML::u(_("Lock page to enable link")));
321 $class = 'wikiadmin';
325 $text = HTML::span(array('class' => 'rawurl'), $url);
327 $wikipage = new WikiPageName($pagename);
328 if (!$wikipage->isValid()) {
330 return $Theme->linkBadWikiWord($wikipage, $url);
333 return HTML::a(array('href' => WikiURL($pagename, $args),
339 * A class to assist in parsing wiki pagenames.
341 * Now with subpages and anchors, parsing and passing around
342 * pagenames is more complicated. This should help.
346 /** Short name for page.
348 * This is the value of $name passed to the constructor.
349 * (For use, e.g. as a default label for links to the page.)
353 /** The full page name.
355 * This is the full name of the page (without anchor).
361 * This is the referenced anchor within the page, or the empty string.
367 * @param mixed $name Page name.
368 * WikiDB_Page, WikiDB_PageRevision, or string.
369 * This can be a relative subpage name (like '/SubPage'),
370 * or can be the empty string to refer to the $basename.
372 * @param string $anchor For links to anchors in page.
374 * @param mixed $basename Page name from which to interpret
375 * relative or other non-fully-specified page names.
377 function WikiPageName($name, $basename=false, $anchor=false) {
378 if (is_string($name)) {
379 $this->shortName = $name;
381 if ($anchor === false and preg_match('/\A(.*)#(.*?)?\Z/', $name, $m))
382 list(, $name, $anchor) = $m;
384 if (empty($name) or $name[0] == SUBPAGE_SEPARATOR) {
386 $name = $this->_pagename($basename) . $name;
388 $name = $this->_normalize_bad_pagename($name);
392 $name = $this->_pagename($name);
393 $this->shortName = $name;
396 $this->name = $this->_check($name);
397 $this->anchor = (string)$anchor;
400 function getParent() {
402 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
404 return substr($name, 0, -strlen($tail));
407 function isValid($strict = false) {
409 return !isset($this->_errors);
410 return !empty($this->name);
413 function getWarnings() {
415 if (isset($this->_warnings))
416 $warnings = array_merge($warnings, $this->_warnings);
417 if (isset($this->_errors))
418 $warnings = array_merge($warnings, $this->_errors);
422 return sprintf(_("'%s': Bad page name: %s"),
423 $this->shortName, join(', ', $warnings));
426 function _pagename($page) {
427 if (isa($page, 'WikiDB_Page'))
428 return $page->getName();
429 elseif (isa($page, 'WikiDB_PageRevision'))
430 return $page->getPageName();
431 elseif (isa($page, 'WikiPageName'))
433 if (!is_string($page)) {
434 print "PAGE: " . gettype($page) . " " . get_class($page) . "<br>\n";
436 //assert(is_string($page));
440 function _normalize_bad_pagename($name) {
441 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
443 // Punt... You really shouldn't get here.
446 return $request->getArg('pagename');
448 assert($name[0] == SUBPAGE_SEPARATOR);
449 return substr($name, 1);
453 function _check($pagename) {
454 // Compress internal white-space to single space character.
455 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
456 if ($pagename != $orig)
457 $this->_warnings[] = _("White space converted to single space");
459 // Delete any control characters.
460 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
461 if ($pagename != $orig)
462 $this->_errors[] = _("Control characters not allowed");
464 // Strip leading and trailing white-space.
465 $pagename = trim($pagename);
468 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
469 $pagename = substr($pagename, 1);
470 if ($pagename != $orig)
471 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
473 if (preg_match('/[:;]/', $pagename))
474 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
476 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
477 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
478 $this->_errors[] = _("too long");
482 if ($pagename == '.' or $pagename == '..') {
483 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
492 * Convert old page markup to new-style markup.
494 * @param string $text Old-style wiki markup.
496 * @param string $markup_type
498 * <dt><code>"block"</code> <dd>Convert all markup.
499 * <dt><code>"inline"</code> <dd>Convert only inline markup.
500 * <dt><code>"links"</code> <dd>Convert only link markup.
503 * @return string New-style wiki markup.
505 * @bugs Footnotes don't work quite as before (esp if there are
506 * multiple references to the same footnote. But close enough,
507 * probably for now....
509 function ConvertOldMarkup ($text, $markup_type = "block") {
515 /*****************************************************************
516 * Conversions for inline markup:
523 // escape escaped brackets
527 // change ! escapes to ~'s.
528 global $AllowedProtocols, $WikiNameRegexp, $request;
529 include_once('lib/interwiki.php');
530 $map = InterWikiMap::GetMap($request);
531 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
532 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
533 $bang_esc[] = $WikiNameRegexp;
534 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
537 $subs["links"] = array($orig, $repl);
540 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
543 // Convert footnote references.
544 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
545 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
547 // Convert old style emphases to HTML style emphasis.
548 $orig[] = '/__(.*?)__/';
549 $repl[] = '<strong>\\1</strong>';
550 $orig[] = "/''(.*?)''/";
551 $repl[] = '<em>\\1</em>';
553 // Escape nestled markup.
554 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
557 // in old markup headings only allowed at beginning of line
561 $subs["inline"] = array($orig, $repl);
563 /*****************************************************************
564 * Patterns which match block markup constructs which take
565 * special handling...
569 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
572 $blockpats[] = '\|(?:.*\n\|)*';
575 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
577 // Footnote definitions
578 $blockpats[] = '\[\s*(\d+)\s*\]';
581 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
584 $blockpats[] = '!{1,3}[^!]';
586 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
587 . join("|", $blockpats)
592 if ($markup_type != "block") {
593 list ($orig, $repl) = $subs[$markup_type];
594 return preg_replace($orig, $repl, $text);
597 list ($orig, $repl) = $subs['inline'];
599 while (preg_match($block_re, $text, $m)) {
600 $text = substr($text, strlen($m[0]));
601 list (,$leading_text, $block) = $m;
604 if (strchr(" \t", $block[0])) {
607 $suffix = "\n</pre>\n";
609 elseif ($block[0] == '|') {
611 $prefix = "<?plugin OldStyleTable\n";
614 elseif (strchr("#*;", $block[0])) {
615 // Old-style list item
616 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
617 list (,$ind,$bullet) = $m;
618 $block = substr($block, strlen($m[0]));
620 $indent = str_repeat(' ', strlen($ind));
621 if ($bullet[0] == ';') {
622 //$term = ltrim(substr($bullet, 1));
623 //return $indent . $term . "\n" . $indent . ' ';
624 $prefix = $ind . $bullet;
627 $prefix = $indent . $bullet . ' ';
629 elseif ($block[0] == '[') {
630 // Footnote definition
631 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
633 $block = substr($block, strlen($m[0]));
634 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
636 elseif ($block[0] == '<') {
638 // HACK: no inline markup...
642 elseif ($block[0] == '!') {
644 preg_match('/^!{1,3}/', $block, $m);
646 $block = substr($block, strlen($m[0]));
653 $out .= ( preg_replace($orig, $repl, $leading_text)
655 . preg_replace($orig, $repl, $block)
658 return $out . preg_replace($orig, $repl, $text);
664 * Expand tabs in string.
666 * Converts all tabs to (the appropriate number of) spaces.
669 * @param integer $tab_width
672 function expand_tabs($str, $tab_width = 8) {
673 $split = split("\t", $str);
674 $tail = array_pop($split);
676 foreach ($split as $hunk) {
678 $pos = strlen(strrchr($expanded, "\n")) - 1;
679 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
681 return substr($expanded, 1) . $tail;
685 * Split WikiWords in page names.
687 * It has been deemed useful to split WikiWords (into "Wiki Words") in
688 * places like page titles. This is rumored to help search engines
691 * @param $page string The page name.
693 * @return string The split name.
695 function split_pagename ($page) {
697 if (preg_match("/\s/", $page))
698 return $page; // Already split --- don't split any more.
700 // FIXME: this algorithm is Anglo-centric.
703 // This mess splits between a lower-case letter followed by
704 // either an upper-case or a numeral; except that it wont
705 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
706 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
707 // This the single-letter words 'I' and 'A' from any following
708 // capitalized words.
709 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
710 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
711 // Split numerals from following letters.
712 $RE[] = '/(\d)([[:alpha:]])/';
714 foreach ($RE as $key => $val)
715 $RE[$key] = pcre_fix_posix_classes($val);
718 foreach ($RE as $regexp) {
719 $page = preg_replace($regexp, '\\1 \\2', $page);
724 function NoSuchRevision (&$request, $page, $version) {
725 $html = HTML(HTML::h2(_("Revision Not Found")),
726 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
727 $version, WikiLink($page, 'auto'))));
728 include_once('lib/Template.php');
729 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
735 * Get time offset for local time zone.
737 * @param $time time_t Get offset for this time. Default: now.
738 * @param $no_colon boolean Don't put colon between hours and minutes.
739 * @return string Offset as a string in the format +HH:MM.
741 function TimezoneOffset ($time = false, $no_colon = false) {
744 $secs = date('Z', $time);
753 $colon = $no_colon ? '' : ':';
754 $mins = intval(($secs + 30) / 60);
755 return sprintf("%s%02d%s%02d",
756 $sign, $mins / 60, $colon, $mins % 60);
761 * Format time in ISO-8601 format.
763 * @param $time time_t Time. Default: now.
764 * @return string Date and time in ISO-8601 format.
766 function Iso8601DateTime ($time = false) {
769 $tzoff = TimezoneOffset($time);
770 $date = date('Y-m-d', $time);
771 $time = date('H:i:s', $time);
772 return $date . 'T' . $time . $tzoff;
776 * Format time in RFC-2822 format.
778 * @param $time time_t Time. Default: now.
779 * @return string Date and time in RFC-2822 format.
781 function Rfc2822DateTime ($time = false) {
784 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
788 * Format time in RFC-1123 format.
790 * @param $time time_t Time. Default: now.
791 * @return string Date and time in RFC-1123 format.
793 function Rfc1123DateTime ($time = false) {
796 return gmdate('D, d M Y H:i:s \G\M\T', $time);
799 /** Parse date in RFC-1123 format.
801 * According to RFC 1123 we must accept dates in the following
804 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
805 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
806 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
808 * (Though we're only allowed to generate dates in the first format.)
810 function ParseRfc1123DateTime ($timestr) {
811 $timestr = trim($timestr);
812 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
813 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
815 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
817 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
818 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
820 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
821 if ($year < 70) $year += 2000;
822 elseif ($year < 100) $year += 1900;
824 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
825 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
827 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
834 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
836 return false; // failed
841 * Format time to standard 'ctime' format.
843 * @param $time time_t Time. Default: now.
844 * @return string Date and time.
846 function CTime ($time = false)
850 return date("D M j H:i:s Y", $time);
856 * Internationalized printf.
858 * This is essentially the same as PHP's built-in printf
859 * with the following exceptions:
861 * <li> It passes the format string through gettext().
862 * <li> It supports the argument reordering extensions.
869 * __printf("Differences between versions %s and %s of %s",
870 * $new_link, $old_link, $page_link);
873 * Then in locale/po/de.po, one can reorder the printf arguments:
876 * msgid "Differences between %s and %s of %s."
877 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
880 * (Note that while PHP tries to expand $vars within double-quotes,
881 * the values in msgstr undergo no such expansion, so the '$'s
884 * One shouldn't use reordered arguments in the default format string.
885 * Backslashes in the default string would be necessary to escape the
886 * '$'s, and they'll cause all kinds of trouble....
888 function __printf ($fmt) {
889 $args = func_get_args();
891 echo __vsprintf($fmt, $args);
895 * Internationalized sprintf.
897 * This is essentially the same as PHP's built-in printf with the
898 * following exceptions:
901 * <li> It passes the format string through gettext().
902 * <li> It supports the argument reordering extensions.
907 function __sprintf ($fmt) {
908 $args = func_get_args();
910 return __vsprintf($fmt, $args);
914 * Internationalized vsprintf.
916 * This is essentially the same as PHP's built-in printf with the
917 * following exceptions:
920 * <li> It passes the format string through gettext().
921 * <li> It supports the argument reordering extensions.
926 function __vsprintf ($fmt, $args) {
927 $fmt = gettext($fmt);
928 // PHP's sprintf doesn't support variable with specifiers,
929 // like sprintf("%*s", 10, "x"); --- so we won't either.
931 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
932 // Format string has '%2$s' style argument reordering.
933 // PHP doesn't support this.
934 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
935 // literal variable name substitution only to keep locale
936 // strings uncluttered
937 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
938 '%1\$s','%s'), E_USER_WARNING); //php+locale error
940 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
943 // Reorder arguments appropriately.
944 foreach($m[1] as $argnum) {
945 if ($argnum < 1 || $argnum > count($args))
946 trigger_error(sprintf(_("%s: argument index out of range"),
947 $argnum), E_USER_WARNING);
948 $newargs[] = $args[$argnum - 1];
953 // Not all PHP's have vsprintf, so...
954 array_unshift($args, $fmt);
955 return call_user_func_array('sprintf', $args);
961 * Build an array in $this->_fileList of files from $dirname.
962 * Subdirectories are not traversed.
964 * (This was a function LoadDir in lib/loadsave.php)
965 * See also http://www.php.net/manual/en/function.readdir.php
967 function getFiles() {
968 return $this->_fileList;
971 function _filenameSelector($filename) {
972 if (! $this->_pattern)
975 return glob_match ($this->_pattern, $filename, $this->_case);
979 function fileSet($directory, $filepattern = false) {
980 $this->_fileList = array();
981 $this->_pattern = $filepattern;
982 $this->_case = !isWindows();
983 $this->_pathsep = '/';
985 if (empty($directory)) {
986 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
988 return; // early return
991 @ $dir_handle = opendir($dir=$directory);
992 if (empty($dir_handle)) {
993 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
994 $dir), E_USER_NOTICE);
995 return; // early return
998 while ($filename = readdir($dir_handle)) {
999 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1001 if ($this->_filenameSelector($filename)) {
1002 array_push($this->_fileList, "$filename");
1003 //trigger_error(sprintf(_("found file %s"), $filename),
1004 // E_USER_NOTICE); //debugging
1007 closedir($dir_handle);
1013 // expands a list containing regex's to its matching entries
1014 class ListRegexExpand {
1015 var $match, $list, $index, $case_sensitive;
1016 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1017 $this->match = str_replace('/','\/',$match);
1018 $this->list = &$list;
1019 $this->case_sensitive = $case_sensitive;
1021 function listMatchCallback ($item, $key) {
1022 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1023 unset($this->list[$this->index]);
1024 $this->list[] = $item;
1027 function expandRegex ($index, &$pages) {
1028 $this->index = $index;
1029 array_walk($pages, array($this, 'listMatchCallback'));
1034 // convert fileglob to regex style
1035 function glob_to_pcre ($glob) {
1036 $re = preg_replace('/\./', '\\.', $glob);
1037 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1038 if (!preg_match('/^[\?\*]/',$glob))
1040 if (!preg_match('/[\?\*]$/',$glob))
1045 function glob_match ($glob, $against, $case_sensitive = true) {
1046 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1049 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1050 $list = explode(',',$input);
1051 // expand wildcards from list of $allnames
1052 if (preg_match('/[\?\*]/',$input)) {
1053 for ($i = 0; $i < sizeof($list); $i++) {
1055 if (preg_match('/[\?\*]/',$f)) {
1057 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1058 $expand->expandRegex($i, $allnames);
1065 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1067 function explodePageList($input, $perm = false) {
1068 // expand wildcards from list of all pages
1069 if (preg_match('/[\?\*]/',$input)) {
1070 $dbi = $GLOBALS['request']->_dbi;
1071 $allPagehandles = $dbi->getAllPages($perm);
1072 while ($pagehandle = $allPagehandles->next()) {
1073 $allPages[] = $pagehandle->getName();
1075 return explodeList($input, $allPages);
1077 return explode(',',$input);
1081 // Class introspections
1083 /** Determine whether object is of a specified type.
1085 * @param $object object An object.
1086 * @param $class string Class name.
1087 * @return bool True iff $object is a $class
1088 * or a sub-type of $class.
1090 function isa ($object, $class)
1092 $lclass = strtolower($class);
1094 return is_object($object)
1095 && ( get_class($object) == strtolower($lclass)
1096 || is_subclass_of($object, $lclass) );
1099 /** Determine whether (possible) object has method.
1101 * @param $object mixed Object
1102 * @param $method string Method name
1103 * @return bool True iff $object is an object with has method $method.
1105 function can ($object, $method)
1107 return is_object($object) && method_exists($object, strtolower($method));
1112 * This is used for generating ETags.
1114 function hash ($x) {
1115 if (is_scalar($x)) {
1118 elseif (is_array($x)) {
1120 return md5(serialize($x));
1122 elseif (is_object($x)) {
1125 trigger_error("Can't hash $x", E_USER_ERROR);
1130 * Seed the random number generator.
1132 * better_srand() ensures the randomizer is seeded only once.
1134 * How random do you want it? See:
1135 * http://www.php.net/manual/en/function.srand.php
1136 * http://www.php.net/manual/en/function.mt-srand.php
1138 function better_srand($seed = '') {
1139 static $wascalled = FALSE;
1141 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1144 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1149 * Recursively count all non-empty elements
1150 * in array of any dimension or mixed - i.e.
1151 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1152 * See http://www.php.net/manual/en/function.count.php
1154 function count_all($arg) {
1155 // skip if argument is empty
1157 //print_r($arg); //debugging
1159 // not an array, return 1 (base case)
1162 // else call recursively for all elements $arg
1163 foreach($arg as $key => $val)
1164 $count += count_all($val);
1169 function isSubPage($pagename) {
1170 return (strstr($pagename, SUBPAGE_SEPARATOR));
1173 function subPageSlice($pagename, $pos) {
1174 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1175 $pages = array_slice($pages,$pos,1);
1182 * Class for "popping up" and alert box. (Except that right now, it doesn't
1186 * This is a hackish and needs to be refactored. However it would be nice to
1187 * unify all the different methods we use for showing Alerts and Dialogs.
1188 * (E.g. "Page deleted", login form, ...)
1193 * @param object $request
1194 * @param mixed $head Header ("title") for alert box.
1195 * @param mixed $body The text in the alert box.
1196 * @param hash $buttons An array mapping button labels to URLs.
1197 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1199 function Alert($head, $body, $buttons=false) {
1200 if ($buttons === false)
1203 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1204 $this->_buttons = $buttons;
1208 * Show the alert box.
1210 function show(&$request) {
1213 $tokens = $this->_tokens;
1214 $tokens['BUTTONS'] = $this->_getButtons();
1216 $request->discardOutput();
1217 $tmpl = new Template('dialog', $request, $tokens);
1223 function _getButtons() {
1226 $buttons = $this->_buttons;
1228 $buttons = array(_("Okay") => $request->getURLtoSelf());
1231 foreach ($buttons as $label => $url)
1232 print "$label $url\n";
1233 $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1234 return new XmlContent($out);
1240 // $Log: not supported by cvs2svn $
1241 // Revision 1.143 2003/02/26 00:10:26 dairiki
1242 // More/better/different checks for bad page names.
1244 // Revision 1.142 2003/02/25 22:19:46 dairiki
1245 // Add some sanity checking for pagenames.
1247 // Revision 1.141 2003/02/22 20:49:55 dairiki
1248 // Fixes for "Call-time pass by reference has been deprecated" errors.
1250 // Revision 1.140 2003/02/21 23:33:29 dairiki
1251 // Set alt="" on the link icon image tags.
1252 // (See SF bug #675141.)
1254 // Revision 1.139 2003/02/21 22:16:27 dairiki
1255 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1256 // These have been obsolete for quite awhile (I hope).
1258 // Revision 1.138 2003/02/21 04:12:36 dairiki
1259 // WikiPageName: fixes for new cached links.
1261 // Alert: new class for displaying alerts.
1263 // ExtractWikiPageLinks and friends are now gone.
1265 // LinkBracketLink moved to InlineParser.php
1267 // Revision 1.137 2003/02/18 23:13:40 dairiki
1268 // Wups again. Typo fix.
1270 // Revision 1.136 2003/02/18 21:52:07 dairiki
1271 // Fix so that one can still link to wiki pages with # in their names.
1272 // (This was made difficult by the introduction of named tags, since
1273 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1275 // Now the ~ escape for page names should work: [Page ~#1].
1277 // Revision 1.135 2003/02/18 19:17:04 dairiki
1278 // split_pagename():
1279 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1280 // Cleanup up subpage splitting code.
1282 // Revision 1.134 2003/02/16 19:44:20 dairiki
1283 // New function hash(). This is a helper, primarily for generating
1286 // Revision 1.133 2003/02/16 04:50:09 dairiki
1288 // Rfc1123DateTime(), ParseRfc1123DateTime()
1289 // for converting unix timestamps to and from strings.
1291 // These functions produce and grok the time strings
1292 // in the format specified by RFC 2616 for use in HTTP headers
1293 // (like Last-Modified).
1295 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1296 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1297 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1300 // (c-file-style: "gnu")
1304 // c-basic-offset: 4
1305 // c-hanging-comment-ender-p: nil
1306 // indent-tabs-mode: nil