1 <?php //rcs_id('$Id: stdlib.php,v 1.159 2004-02-26 04:03:40 rurban 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) {
193 if (! $request->getPref('noLinkIcons')) {
194 $icon = IconForLink($proto_or_url);
196 if (!is_object($text)) {
197 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
198 list (, $first_word, $tail) = $m;
205 $text = HTML::span(array('style' => 'white-space: nowrap'),
208 $text = HTML($text, $tail);
215 * Determines if the url passed to function is safe, by detecting if the characters
216 * '<', '>', or '"' are present.
218 * @param string $url URL to check for unsafe characters.
219 * @return boolean True if same, false else.
221 function IsSafeURL($url) {
222 return !ereg('[<>"]', $url);
226 * Generates an HtmlElement object to store data for a link.
228 * @param string $url URL that the link will point to.
229 * @param string $linktext Text to be displayed as link.
230 * @return HtmlElement HtmlElement object that contains data to construct an html link.
232 function LinkURL($url, $linktext = '') {
233 // FIXME: Is this needed (or sufficient?)
234 if(! IsSafeURL($url)) {
235 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
236 _("BAD URL -- remove all of <, >, \"")));
240 $linktext = preg_replace("/mailto:/A", "", $url);
242 $link = HTML::a(array('href' => $url),
243 PossiblyGlueIconToText($url, $linktext));
246 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
251 function LinkImage($url, $alt = false) {
252 // FIXME: Is this needed (or sufficient?)
253 if(! IsSafeURL($url)) {
254 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
255 _("BAD URL -- remove all of <, >, \"")));
260 $link = HTML::img(array('src' => $url, 'alt' => $alt));
262 $link->setAttr('class', 'inlineimage');
269 var $items = array();
272 function push($item) {
273 $this->items[$this->size] = $item;
279 if ($this->size == 0) {
280 return false; // stack is empty
283 return $this->items[$this->size];
292 return $this->items[$this->size - 1];
298 // end class definition
300 function SplitQueryArgs ($query_args = '')
302 $split_args = split('&', $query_args);
304 while (list($key, $val) = each($split_args))
305 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
306 $args[$m[1]] = $m[2];
310 function LinkPhpwikiURL($url, $text = '', $basepage) {
313 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
314 return HTML::strong(array('class' => 'rawurl'),
315 HTML::u(array('class' => 'baduri'),
316 _("BAD phpwiki: URL")));
320 $pagename = urldecode($m[1]);
323 if (empty($pagename) &&
324 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
325 // Convert old style links (to not break diff links in
327 $pagename = urldecode($m[2]);
328 $args = array("action" => $m[1]);
331 $args = SplitQueryArgs($qargs);
334 if (empty($pagename))
335 $pagename = $GLOBALS['request']->getArg('pagename');
337 if (isset($args['action']) && $args['action'] == 'browse')
338 unset($args['action']);
341 if (empty($args['action']))
343 else if (is_safe_action($args['action']))
344 $class = 'wikiaction';
346 if (empty($args['action']) || is_safe_action($args['action']))
347 $class = 'wikiaction';
349 // Don't allow administrative links on unlocked pages.
350 $dbi = $GLOBALS['request']->getDbh();
351 $page = $dbi->getPage($basepage);
352 if (!$page->get('locked'))
353 return HTML::span(array('class' => 'wikiunsafe'),
354 HTML::u(_("Lock page to enable link")));
355 $class = 'wikiadmin';
359 $text = HTML::span(array('class' => 'rawurl'), $url);
361 $wikipage = new WikiPageName($pagename);
362 if (!$wikipage->isValid()) {
364 return $Theme->linkBadWikiWord($wikipage, $url);
367 return HTML::a(array('href' => WikiURL($pagename, $args),
373 * A class to assist in parsing wiki pagenames.
375 * Now with subpages and anchors, parsing and passing around
376 * pagenames is more complicated. This should help.
380 /** Short name for page.
382 * This is the value of $name passed to the constructor.
383 * (For use, e.g. as a default label for links to the page.)
387 /** The full page name.
389 * This is the full name of the page (without anchor).
395 * This is the referenced anchor within the page, or the empty string.
401 * @param mixed $name Page name.
402 * WikiDB_Page, WikiDB_PageRevision, or string.
403 * This can be a relative subpage name (like '/SubPage'),
404 * or can be the empty string to refer to the $basename.
406 * @param string $anchor For links to anchors in page.
408 * @param mixed $basename Page name from which to interpret
409 * relative or other non-fully-specified page names.
411 function WikiPageName($name, $basename=false, $anchor=false) {
412 if (is_string($name)) {
413 $this->shortName = $name;
415 if (empty($name) or $name[0] == SUBPAGE_SEPARATOR) {
417 $name = $this->_pagename($basename) . $name;
419 $name = $this->_normalize_bad_pagename($name);
423 $name = $this->_pagename($name);
424 $this->shortName = $name;
427 $this->name = $this->_check($name);
428 $this->anchor = (string)$anchor;
431 function getParent() {
433 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
435 return substr($name, 0, -strlen($tail));
438 function isValid($strict = false) {
440 return !isset($this->_errors);
441 return !empty($this->name);
444 function getWarnings() {
446 if (isset($this->_warnings))
447 $warnings = array_merge($warnings, $this->_warnings);
448 if (isset($this->_errors))
449 $warnings = array_merge($warnings, $this->_errors);
453 return sprintf(_("'%s': Bad page name: %s"),
454 $this->shortName, join(', ', $warnings));
457 function _pagename($page) {
458 if (isa($page, 'WikiDB_Page'))
459 return $page->getName();
460 elseif (isa($page, 'WikiDB_PageRevision'))
461 return $page->getPageName();
462 elseif (isa($page, 'WikiPageName'))
464 if (!is_string($page)) {
465 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
466 $page, gettype($page), get_class($page)),
469 //assert(is_string($page));
473 function _normalize_bad_pagename($name) {
474 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
476 // Punt... You really shouldn't get here.
479 return $request->getArg('pagename');
481 assert($name[0] == SUBPAGE_SEPARATOR);
482 return substr($name, 1);
486 function _check($pagename) {
487 // Compress internal white-space to single space character.
488 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
489 if ($pagename != $orig)
490 $this->_warnings[] = _("White space converted to single space");
492 // Delete any control characters.
493 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
494 if ($pagename != $orig)
495 $this->_errors[] = _("Control characters not allowed");
497 // Strip leading and trailing white-space.
498 $pagename = trim($pagename);
501 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
502 $pagename = substr($pagename, 1);
503 if ($pagename != $orig)
504 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
506 if (preg_match('/[:;]/', $pagename))
507 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
509 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
510 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
511 $this->_errors[] = _("too long");
515 if ($pagename == '.' or $pagename == '..') {
516 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
525 * Convert old page markup to new-style markup.
527 * @param string $text Old-style wiki markup.
529 * @param string $markup_type
531 * <dt><code>"block"</code> <dd>Convert all markup.
532 * <dt><code>"inline"</code> <dd>Convert only inline markup.
533 * <dt><code>"links"</code> <dd>Convert only link markup.
536 * @return string New-style wiki markup.
538 * @bugs Footnotes don't work quite as before (esp if there are
539 * multiple references to the same footnote. But close enough,
540 * probably for now....
542 function ConvertOldMarkup ($text, $markup_type = "block") {
548 /*****************************************************************
549 * Conversions for inline markup:
556 // escape escaped brackets
560 // change ! escapes to ~'s.
561 global $AllowedProtocols, $WikiNameRegexp, $request;
562 //include_once('lib/interwiki.php');
563 $map = PageType_interwikimap::GetMap($request);
564 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
565 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
566 $bang_esc[] = $WikiNameRegexp;
567 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
570 $subs["links"] = array($orig, $repl);
573 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
576 // Convert footnote references.
577 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
578 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
580 // Convert old style emphases to HTML style emphasis.
581 $orig[] = '/__(.*?)__/';
582 $repl[] = '<strong>\\1</strong>';
583 $orig[] = "/''(.*?)''/";
584 $repl[] = '<em>\\1</em>';
586 // Escape nestled markup.
587 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
590 // in old markup headings only allowed at beginning of line
594 $subs["inline"] = array($orig, $repl);
596 /*****************************************************************
597 * Patterns which match block markup constructs which take
598 * special handling...
602 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
605 $blockpats[] = '\|(?:.*\n\|)*';
608 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
610 // Footnote definitions
611 $blockpats[] = '\[\s*(\d+)\s*\]';
614 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
617 $blockpats[] = '!{1,3}[^!]';
619 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
620 . join("|", $blockpats)
625 if ($markup_type != "block") {
626 list ($orig, $repl) = $subs[$markup_type];
627 return preg_replace($orig, $repl, $text);
630 list ($orig, $repl) = $subs['inline'];
632 while (preg_match($block_re, $text, $m)) {
633 $text = substr($text, strlen($m[0]));
634 list (,$leading_text, $block) = $m;
637 if (strchr(" \t", $block[0])) {
640 $suffix = "\n</pre>\n";
642 elseif ($block[0] == '|') {
644 $prefix = "<?plugin OldStyleTable\n";
647 elseif (strchr("#*;", $block[0])) {
648 // Old-style list item
649 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
650 list (,$ind,$bullet) = $m;
651 $block = substr($block, strlen($m[0]));
653 $indent = str_repeat(' ', strlen($ind));
654 if ($bullet[0] == ';') {
655 //$term = ltrim(substr($bullet, 1));
656 //return $indent . $term . "\n" . $indent . ' ';
657 $prefix = $ind . $bullet;
660 $prefix = $indent . $bullet . ' ';
662 elseif ($block[0] == '[') {
663 // Footnote definition
664 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
666 $block = substr($block, strlen($m[0]));
667 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
669 elseif ($block[0] == '<') {
671 // HACK: no inline markup...
675 elseif ($block[0] == '!') {
677 preg_match('/^!{1,3}/', $block, $m);
679 $block = substr($block, strlen($m[0]));
686 $out .= ( preg_replace($orig, $repl, $leading_text)
688 . preg_replace($orig, $repl, $block)
691 return $out . preg_replace($orig, $repl, $text);
697 * Expand tabs in string.
699 * Converts all tabs to (the appropriate number of) spaces.
702 * @param integer $tab_width
705 function expand_tabs($str, $tab_width = 8) {
706 $split = split("\t", $str);
707 $tail = array_pop($split);
709 foreach ($split as $hunk) {
711 $pos = strlen(strrchr($expanded, "\n")) - 1;
712 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
714 return substr($expanded, 1) . $tail;
718 * Split WikiWords in page names.
720 * It has been deemed useful to split WikiWords (into "Wiki Words") in
721 * places like page titles. This is rumored to help search engines
724 * @param $page string The page name.
726 * @return string The split name.
728 function split_pagename ($page) {
730 if (preg_match("/\s/", $page))
731 return $page; // Already split --- don't split any more.
733 // FIXME: this algorithm is Anglo-centric.
736 // This mess splits between a lower-case letter followed by
737 // either an upper-case or a numeral; except that it wont
738 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
739 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
740 // This the single-letter words 'I' and 'A' from any following
741 // capitalized words.
742 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
743 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
744 // Split numerals from following letters.
745 $RE[] = '/(\d)([[:alpha:]])/';
747 foreach ($RE as $key => $val)
748 $RE[$key] = pcre_fix_posix_classes($val);
751 foreach ($RE as $regexp) {
752 $page = preg_replace($regexp, '\\1 \\2', $page);
757 function NoSuchRevision (&$request, $page, $version) {
758 $html = HTML(HTML::h2(_("Revision Not Found")),
759 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
760 $version, WikiLink($page, 'auto'))));
761 include_once('lib/Template.php');
762 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
768 * Get time offset for local time zone.
770 * @param $time time_t Get offset for this time. Default: now.
771 * @param $no_colon boolean Don't put colon between hours and minutes.
772 * @return string Offset as a string in the format +HH:MM.
774 function TimezoneOffset ($time = false, $no_colon = false) {
777 $secs = date('Z', $time);
786 $colon = $no_colon ? '' : ':';
787 $mins = intval(($secs + 30) / 60);
788 return sprintf("%s%02d%s%02d",
789 $sign, $mins / 60, $colon, $mins % 60);
794 * Format time in ISO-8601 format.
796 * @param $time time_t Time. Default: now.
797 * @return string Date and time in ISO-8601 format.
799 function Iso8601DateTime ($time = false) {
802 $tzoff = TimezoneOffset($time);
803 $date = date('Y-m-d', $time);
804 $time = date('H:i:s', $time);
805 return $date . 'T' . $time . $tzoff;
809 * Format time in RFC-2822 format.
811 * @param $time time_t Time. Default: now.
812 * @return string Date and time in RFC-2822 format.
814 function Rfc2822DateTime ($time = false) {
817 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
821 * Format time in RFC-1123 format.
823 * @param $time time_t Time. Default: now.
824 * @return string Date and time in RFC-1123 format.
826 function Rfc1123DateTime ($time = false) {
829 return gmdate('D, d M Y H:i:s \G\M\T', $time);
832 /** Parse date in RFC-1123 format.
834 * According to RFC 1123 we must accept dates in the following
837 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
838 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
839 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
841 * (Though we're only allowed to generate dates in the first format.)
843 function ParseRfc1123DateTime ($timestr) {
844 $timestr = trim($timestr);
845 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
846 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
848 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
850 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
851 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
853 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
854 if ($year < 70) $year += 2000;
855 elseif ($year < 100) $year += 1900;
857 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
858 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
860 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
867 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
869 return false; // failed
874 * Format time to standard 'ctime' format.
876 * @param $time time_t Time. Default: now.
877 * @return string Date and time.
879 function CTime ($time = false)
883 return date("D M j H:i:s Y", $time);
888 * Format number as kilobytes or bytes.
889 * Short format is used for PageList
890 * Long format is used in PageInfo
892 * @param $bytes int. Default: 0.
893 * @param $longformat bool. Default: false.
894 * @return class FormattedText (XmlElement.php).
896 function ByteFormatter ($bytes = 0, $longformat = false) {
901 $size = fmt("%s b", $bytes);
903 $size = fmt("%s bytes", $bytes);
906 $kb = round($bytes / 1024, 1);
908 $size = fmt("%s k", $kb);
910 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
916 * Internationalized printf.
918 * This is essentially the same as PHP's built-in printf
919 * with the following exceptions:
921 * <li> It passes the format string through gettext().
922 * <li> It supports the argument reordering extensions.
929 * __printf("Differences between versions %s and %s of %s",
930 * $new_link, $old_link, $page_link);
933 * Then in locale/po/de.po, one can reorder the printf arguments:
936 * msgid "Differences between %s and %s of %s."
937 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
940 * (Note that while PHP tries to expand $vars within double-quotes,
941 * the values in msgstr undergo no such expansion, so the '$'s
944 * One shouldn't use reordered arguments in the default format string.
945 * Backslashes in the default string would be necessary to escape the
946 * '$'s, and they'll cause all kinds of trouble....
948 function __printf ($fmt) {
949 $args = func_get_args();
951 echo __vsprintf($fmt, $args);
955 * Internationalized sprintf.
957 * This is essentially the same as PHP's built-in printf with the
958 * following exceptions:
961 * <li> It passes the format string through gettext().
962 * <li> It supports the argument reordering extensions.
967 function __sprintf ($fmt) {
968 $args = func_get_args();
970 return __vsprintf($fmt, $args);
974 * Internationalized vsprintf.
976 * This is essentially the same as PHP's built-in printf with the
977 * following exceptions:
980 * <li> It passes the format string through gettext().
981 * <li> It supports the argument reordering extensions.
986 function __vsprintf ($fmt, $args) {
987 $fmt = gettext($fmt);
988 // PHP's sprintf doesn't support variable with specifiers,
989 // like sprintf("%*s", 10, "x"); --- so we won't either.
991 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
992 // Format string has '%2$s' style argument reordering.
993 // PHP doesn't support this.
994 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
995 // literal variable name substitution only to keep locale
996 // strings uncluttered
997 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
998 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1000 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1003 // Reorder arguments appropriately.
1004 foreach($m[1] as $argnum) {
1005 if ($argnum < 1 || $argnum > count($args))
1006 trigger_error(sprintf(_("%s: argument index out of range"),
1007 $argnum), E_USER_WARNING);
1008 $newargs[] = $args[$argnum - 1];
1013 // Not all PHP's have vsprintf, so...
1014 array_unshift($args, $fmt);
1015 return call_user_func_array('sprintf', $args);
1021 * Build an array in $this->_fileList of files from $dirname.
1022 * Subdirectories are not traversed.
1024 * (This was a function LoadDir in lib/loadsave.php)
1025 * See also http://www.php.net/manual/en/function.readdir.php
1027 function getFiles() {
1028 return $this->_fileList;
1031 function _filenameSelector($filename) {
1032 if (! $this->_pattern)
1035 return glob_match ($this->_pattern, $filename, $this->_case);
1039 function fileSet($directory, $filepattern = false) {
1040 $this->_fileList = array();
1041 $this->_pattern = $filepattern;
1042 $this->_case = !isWindows();
1043 $this->_pathsep = '/';
1045 if (empty($directory)) {
1046 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1048 return; // early return
1051 @ $dir_handle = opendir($dir=$directory);
1052 if (empty($dir_handle)) {
1053 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1054 $dir), E_USER_NOTICE);
1055 return; // early return
1058 while ($filename = readdir($dir_handle)) {
1059 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1061 if ($this->_filenameSelector($filename)) {
1062 array_push($this->_fileList, "$filename");
1063 //trigger_error(sprintf(_("found file %s"), $filename),
1064 // E_USER_NOTICE); //debugging
1067 closedir($dir_handle);
1073 // expands a list containing regex's to its matching entries
1074 class ListRegexExpand {
1075 var $match, $list, $index, $case_sensitive;
1076 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1077 $this->match = str_replace('/','\/',$match);
1078 $this->list = &$list;
1079 $this->case_sensitive = $case_sensitive;
1081 function listMatchCallback ($item, $key) {
1082 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1083 unset($this->list[$this->index]);
1084 $this->list[] = $item;
1087 function expandRegex ($index, &$pages) {
1088 $this->index = $index;
1089 array_walk($pages, array($this, 'listMatchCallback'));
1094 // convert fileglob to regex style
1095 function glob_to_pcre ($glob) {
1096 $re = preg_replace('/\./', '\\.', $glob);
1097 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1098 if (!preg_match('/^[\?\*]/',$glob))
1100 if (!preg_match('/[\?\*]$/',$glob))
1105 function glob_match ($glob, $against, $case_sensitive = true) {
1106 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1109 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1110 $list = explode(',',$input);
1111 // expand wildcards from list of $allnames
1112 if (preg_match('/[\?\*]/',$input)) {
1113 // Optimizing loop invariants:
1114 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1115 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1117 if (preg_match('/[\?\*]/',$f)) {
1119 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1120 $expand->expandRegex($i, $allnames);
1127 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1128 function explodePageList($input, $perm = false, $orderby = 'pagename') {
1129 // expand wildcards from list of all pages
1130 if (preg_match('/[\?\*]/',$input)) {
1131 $dbi = $GLOBALS['request']->_dbi;
1132 require_once("lib/PageList.php");
1133 $allPagehandles = $dbi->getAllPages($perm,$orderby);
1134 while ($pagehandle = $allPagehandles->next()) {
1135 $allPages[] = $pagehandle->getName();
1137 return explodeList($input, $allPages);
1139 return explode(',',$input);
1143 // Class introspections
1145 /** Determine whether object is of a specified type.
1147 * @param $object object An object.
1148 * @param $class string Class name.
1149 * @return bool True iff $object is a $class
1150 * or a sub-type of $class.
1152 function isa ($object, $class)
1154 $lclass = strtolower($class);
1156 return is_object($object)
1157 && ( get_class($object) == strtolower($lclass)
1158 || is_subclass_of($object, $lclass) );
1161 /** Determine whether (possible) object has method.
1163 * @param $object mixed Object
1164 * @param $method string Method name
1165 * @return bool True iff $object is an object with has method $method.
1167 function can ($object, $method)
1169 return is_object($object) && method_exists($object, strtolower($method));
1172 /** Determine whether a function is okay to use.
1174 * Some providers (e.g. Lycos) disable some of PHP functions for
1175 * "security reasons." This makes those functions, of course,
1176 * unusable, despite the fact the function_exists() says they
1179 * This function test to see if a function exists and is not
1180 * disallowed by PHP's disable_functions config setting.
1182 * @param string $function_name Function name
1183 * @return bool True iff function can be used.
1185 function function_usable($function_name)
1188 if (!is_array($disabled)) {
1189 $disabled = array();
1190 // Use get_cfg_var since ini_get() is one of the disabled functions
1191 // (on Lycos, at least.)
1192 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1193 foreach ($split as $f)
1194 $disabled[strtolower($f)] = true;
1197 return ( function_exists($function_name)
1198 and ! isset($disabled[strtolower($function_name)])
1205 * This is used for generating ETags.
1207 function hash ($x) {
1208 if (is_scalar($x)) {
1211 elseif (is_array($x)) {
1213 return md5(serialize($x));
1215 elseif (is_object($x)) {
1218 trigger_error("Can't hash $x", E_USER_ERROR);
1223 * Seed the random number generator.
1225 * better_srand() ensures the randomizer is seeded only once.
1227 * How random do you want it? See:
1228 * http://www.php.net/manual/en/function.srand.php
1229 * http://www.php.net/manual/en/function.mt-srand.php
1231 function better_srand($seed = '') {
1232 static $wascalled = FALSE;
1234 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1237 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1242 * Recursively count all non-empty elements
1243 * in array of any dimension or mixed - i.e.
1244 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1245 * See http://www.php.net/manual/en/function.count.php
1247 function count_all($arg) {
1248 // skip if argument is empty
1250 //print_r($arg); //debugging
1252 // not an array, return 1 (base case)
1255 // else call recursively for all elements $arg
1256 foreach($arg as $key => $val)
1257 $count += count_all($val);
1262 function isSubPage($pagename) {
1263 return (strstr($pagename, SUBPAGE_SEPARATOR));
1266 function subPageSlice($pagename, $pos) {
1267 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1268 $pages = array_slice($pages,$pos,1);
1275 * Class for "popping up" and alert box. (Except that right now, it doesn't
1279 * This is a hackish and needs to be refactored. However it would be nice to
1280 * unify all the different methods we use for showing Alerts and Dialogs.
1281 * (E.g. "Page deleted", login form, ...)
1286 * @param object $request
1287 * @param mixed $head Header ("title") for alert box.
1288 * @param mixed $body The text in the alert box.
1289 * @param hash $buttons An array mapping button labels to URLs.
1290 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1292 function Alert($head, $body, $buttons=false) {
1293 if ($buttons === false)
1296 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1297 $this->_buttons = $buttons;
1301 * Show the alert box.
1303 function show(&$request) {
1306 $tokens = $this->_tokens;
1307 $tokens['BUTTONS'] = $this->_getButtons();
1309 $request->discardOutput();
1310 $tmpl = new Template('dialog', $request, $tokens);
1316 function _getButtons() {
1319 $buttons = $this->_buttons;
1321 $buttons = array(_("Okay") => $request->getURLtoSelf());
1324 foreach ($buttons as $label => $url)
1325 print "$label $url\n";
1326 $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1327 return new XmlContent($out);
1332 * returns true if current php version is at mimimum a.b.c
1333 * Called: check_php_version(4,1)
1335 function check_php_version ($a = '0', $b = '0', $c = '0') {
1336 global $PHP_VERSION;
1337 if(!isset($PHP_VERSION))
1338 $PHP_VERSION = substr( str_pad( preg_replace('/\D/','', PHP_VERSION), 3, '0'), 0, 3);
1339 return $PHP_VERSION >= ($a.$b.$c);
1342 function isWikiWord($word) {
1343 global $WikiNameRegexp;
1344 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1345 return preg_match("/^$WikiNameRegexp\$/",$word);
1348 // needed to store serialized objects-values only (perm, pref)
1349 function obj2hash ($obj, $exclude = false, $fields = false) {
1351 if (! $fields ) $fields = get_object_vars($obj);
1352 foreach ($fields as $key => $val) {
1353 if (is_array($exclude)) {
1354 if (in_array($key,$exclude)) continue;
1361 // $Log: not supported by cvs2svn $
1362 // Revision 1.158 2004/02/19 21:54:17 rurban
1363 // moved initerwiki code to PageType.php
1364 // re-enabled and fixed InlineImages support, now also for InterWiki Urls
1365 // * [File:my_image.gif] inlines the image,
1366 // * File:my_image.gif shows a plain inter-wiki link,
1367 // * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
1368 // * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
1370 // Revision 1.157 2004/02/09 03:58:12 rurban
1371 // for now default DB_SESSION to false
1373 // * not existing perms will now query the parent, and not
1374 // return the default perm
1375 // * added pagePermissions func which returns the object per page
1376 // * added getAccessDescription
1378 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1379 // * force init of authdbh in the 2 db classes
1381 // * fixed session handling (not triple auth request anymore)
1382 // * don't store cookie prefs with sessions
1383 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1385 // Revision 1.156 2004/01/26 09:17:49 rurban
1386 // * changed stored pref representation as before.
1387 // the array of objects is 1) bigger and 2)
1388 // less portable. If we would import packed pref
1389 // objects and the object definition was changed, PHP would fail.
1390 // This doesn't happen with an simple array of non-default values.
1391 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1392 // understands the interim format of array of objects also.
1393 // * simplified $prefs->get() and fixed $prefs->set()
1394 // * added $user->_userid and class '_WikiUser' portability functions
1395 // * fixed $user object ->_level upgrading, mostly using sessions.
1396 // this fixes yesterdays problems with loosing authorization level.
1397 // * fixed WikiUserNew::checkPass to return the _level
1398 // * fixed WikiUserNew::isSignedIn
1399 // * added explodePageList to class PageList, support sortby arg
1400 // * fixed UserPreferences for WikiUserNew
1401 // * fixed WikiPlugin for empty defaults array
1402 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1403 // removed sort arg, support sortby arg
1405 // Revision 1.155 2004/01/25 10:52:22 rurban
1406 // added sortby support to explodePageList() and UnfoldSubpages
1407 // fixes [ 758044 ] Plugin UnfoldSubpages does not sort (includes fix)
1409 // Revision 1.154 2004/01/25 03:49:03 rurban
1410 // added isWikiWord() to avoid redundancy
1411 // added check_php_version() to check for older php versions.
1412 // e.g. object::method calls, ...
1414 // Revision 1.153 2003/11/30 18:43:18 carstenklapp
1415 // Fixed careless mistakes in my last optimization commit.
1417 // Revision 1.152 2003/11/30 18:20:34 carstenklapp
1418 // Minor code optimization: reduce invariant loops
1420 // Revision 1.151 2003/11/29 19:30:01 carstenklapp
1421 // New function ByteFormatter.
1423 // Revision 1.150 2003/09/13 22:43:00 carstenklapp
1424 // New preference to hide LinkIcons.
1426 // Revision 1.149 2003/03/26 19:37:08 dairiki
1427 // Fix "object to string conversion" bug with external image links.
1429 // Revision 1.148 2003/03/25 21:03:02 dairiki
1430 // Cleanup debugging output.
1432 // Revision 1.147 2003/03/13 20:17:05 dairiki
1433 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1435 // Revision 1.146 2003/03/07 02:46:24 dairiki
1436 // function_usable(): New function.
1438 // Revision 1.145 2003/03/04 01:55:05 dairiki
1439 // Fix to ensure absolute URL for logo in RSS recent changes.
1441 // Revision 1.144 2003/02/26 00:39:30 dairiki
1442 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1443 // being displayed at incorrect times.
1445 // Revision 1.143 2003/02/26 00:10:26 dairiki
1446 // More/better/different checks for bad page names.
1448 // Revision 1.142 2003/02/25 22:19:46 dairiki
1449 // Add some sanity checking for pagenames.
1451 // Revision 1.141 2003/02/22 20:49:55 dairiki
1452 // Fixes for "Call-time pass by reference has been deprecated" errors.
1454 // Revision 1.140 2003/02/21 23:33:29 dairiki
1455 // Set alt="" on the link icon image tags.
1456 // (See SF bug #675141.)
1458 // Revision 1.139 2003/02/21 22:16:27 dairiki
1459 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1460 // These have been obsolete for quite awhile (I hope).
1462 // Revision 1.138 2003/02/21 04:12:36 dairiki
1463 // WikiPageName: fixes for new cached links.
1465 // Alert: new class for displaying alerts.
1467 // ExtractWikiPageLinks and friends are now gone.
1469 // LinkBracketLink moved to InlineParser.php
1471 // Revision 1.137 2003/02/18 23:13:40 dairiki
1472 // Wups again. Typo fix.
1474 // Revision 1.136 2003/02/18 21:52:07 dairiki
1475 // Fix so that one can still link to wiki pages with # in their names.
1476 // (This was made difficult by the introduction of named tags, since
1477 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1479 // Now the ~ escape for page names should work: [Page ~#1].
1481 // Revision 1.135 2003/02/18 19:17:04 dairiki
1482 // split_pagename():
1483 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1484 // Cleanup up subpage splitting code.
1486 // Revision 1.134 2003/02/16 19:44:20 dairiki
1487 // New function hash(). This is a helper, primarily for generating
1490 // Revision 1.133 2003/02/16 04:50:09 dairiki
1492 // Rfc1123DateTime(), ParseRfc1123DateTime()
1493 // for converting unix timestamps to and from strings.
1495 // These functions produce and grok the time strings
1496 // in the format specified by RFC 2616 for use in HTTP headers
1497 // (like Last-Modified).
1499 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1500 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1501 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1504 // (c-file-style: "gnu")
1508 // c-basic-offset: 4
1509 // c-hanging-comment-ender-p: nil
1510 // indent-tabs-mode: nil