1 <?php //rcs_id('$Id: stdlib.php,v 1.165 2004-03-24 19:39:03 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) {
71 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
72 "'x' . sprintf('%02x', ord('\\0')) . '.'",
77 * Generates a valid URL for a given Wiki pagename.
78 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
79 * If a WikiDB_Page object function will extract the name to link to.
80 * If a WikiDB_PageRevision object function will extract the name to link to.
82 * @param boolean $get_abs_url Default value is false.
83 * @return string The absolute URL to the page passed as $pagename.
85 function WikiURL($pagename, $args = '', $get_abs_url = false) {
88 if (is_object($pagename)) {
89 if (isa($pagename, 'WikiDB_Page')) {
90 $pagename = $pagename->getName();
92 elseif (isa($pagename, 'WikiDB_PageRevision')) {
93 $page = $pagename->getPage();
94 $args['version'] = $pagename->getVersion();
95 $pagename = $page->getName();
97 elseif (isa($pagename, 'WikiPageName')) {
98 $anchor = $pagename->anchor;
99 $pagename = $pagename->name;
103 if (is_array($args)) {
105 foreach ($args as $key => $val) {
106 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
107 $enc_args[] = urlencode($key) . '=' . urlencode($val);
109 $args = join('&', $enc_args);
113 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
114 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
119 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
120 $url .= "?pagename=" . rawurlencode($pagename);
125 $url .= "#" . MangleXmlIdentifier($anchor);
129 /** Convert relative URL to absolute URL.
131 * This converts a relative URL to one of PhpWiki's support files
132 * to an absolute one.
135 * @return string Absolute URL
137 function AbsoluteURL ($url) {
138 if (preg_match('/^https?:/', $url))
140 if ($url[0] != '/') {
141 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
142 while ($base != '/' and substr($url, 0, 3) == "../") {
143 $url = substr($url, 3);
144 $base = dirname($base);
150 return SERVER_URL . $url;
154 * Generates icon in front of links.
156 * @param string $protocol_or_url URL or protocol to determine which icon to use.
158 * @return HtmlElement HtmlElement object that contains data to create img link to
159 * icon for use with url or protocol passed to the function. False if no img to be
162 function IconForLink($protocol_or_url) {
164 if ($filename_suffix = false) {
165 // display apache style icon for file type instead of protocol icon
166 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
167 // - document: html, htm, text, txt, rtf, pdf, doc
168 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
169 // - audio: mp3,mp2,aiff,aif,au
170 // - multimedia: mpeg,mpg,mov,qt
172 list ($proto) = explode(':', $protocol_or_url, 2);
173 $src = $Theme->getLinkIconURL($proto);
175 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
182 * Glue icon in front of text.
184 * @param string $protocol_or_url Protocol or URL. Used to determine the
186 * @param string $text The text.
187 * @return XmlContent.
189 function PossiblyGlueIconToText($proto_or_url, $text) {
191 if (! $request->getPref('noLinkIcons')) {
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);
213 * Determines if the url passed to function is safe, by detecting if the characters
214 * '<', '>', or '"' are present.
216 * @param string $url URL to check for unsafe characters.
217 * @return boolean True if same, false else.
219 function IsSafeURL($url) {
220 return !ereg('[<>"]', $url);
224 * Generates an HtmlElement object to store data for a link.
226 * @param string $url URL that the link will point to.
227 * @param string $linktext Text to be displayed as link.
228 * @return HtmlElement HtmlElement object that contains data to construct an html link.
230 function LinkURL($url, $linktext = '') {
231 // FIXME: Is this needed (or sufficient?)
232 if(! IsSafeURL($url)) {
233 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
234 _("BAD URL -- remove all of <, >, \"")));
238 $linktext = preg_replace("/mailto:/A", "", $url);
240 $link = HTML::a(array('href' => $url),
241 PossiblyGlueIconToText($url, $linktext));
244 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
249 function LinkImage($url, $alt = false) {
250 // FIXME: Is this needed (or sufficient?)
251 if(! IsSafeURL($url)) {
252 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
253 _("BAD URL -- remove all of <, >, \"")));
258 $link = HTML::img(array('src' => $url, 'alt' => $alt));
260 $link->setAttr('class', 'inlineimage');
267 var $items = array();
269 // var in php5.0.0.rc1 deprecated
271 function push($item) {
272 $this->items[$this->size] = $item;
278 if ($this->size == 0) {
279 return false; // stack is empty
282 return $this->items[$this->size];
291 return $this->items[$this->size - 1];
297 // end class definition
299 function SplitQueryArgs ($query_args = '')
301 $split_args = split('&', $query_args);
303 while (list($key, $val) = each($split_args))
304 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
305 $args[$m[1]] = $m[2];
309 function LinkPhpwikiURL($url, $text = '', $basepage) {
312 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
313 return HTML::strong(array('class' => 'rawurl'),
314 HTML::u(array('class' => 'baduri'),
315 _("BAD phpwiki: URL")));
319 $pagename = urldecode($m[1]);
322 if (empty($pagename) &&
323 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
324 // Convert old style links (to not break diff links in
326 $pagename = urldecode($m[2]);
327 $args = array("action" => $m[1]);
330 $args = SplitQueryArgs($qargs);
333 if (empty($pagename))
334 $pagename = $GLOBALS['request']->getArg('pagename');
336 if (isset($args['action']) && $args['action'] == 'browse')
337 unset($args['action']);
340 if (empty($args['action']))
342 else if (is_safe_action($args['action']))
343 $class = 'wikiaction';
345 if (empty($args['action']) || is_safe_action($args['action']))
346 $class = 'wikiaction';
348 // Don't allow administrative links on unlocked pages.
349 $dbi = $GLOBALS['request']->getDbh();
350 $page = $dbi->getPage($basepage);
351 if (!$page->get('locked'))
352 return HTML::span(array('class' => 'wikiunsafe'),
353 HTML::u(_("Lock page to enable link")));
354 $class = 'wikiadmin';
358 $text = HTML::span(array('class' => 'rawurl'), $url);
360 $wikipage = new WikiPageName($pagename);
361 if (!$wikipage->isValid()) {
363 return $Theme->linkBadWikiWord($wikipage, $url);
366 return HTML::a(array('href' => WikiURL($pagename, $args),
372 * A class to assist in parsing wiki pagenames.
374 * Now with subpages and anchors, parsing and passing around
375 * pagenames is more complicated. This should help.
379 /** Short name for page.
381 * This is the value of $name passed to the constructor.
382 * (For use, e.g. as a default label for links to the page.)
386 /** The full page name.
388 * This is the full name of the page (without anchor).
394 * This is the referenced anchor within the page, or the empty string.
400 * @param mixed $name Page name.
401 * WikiDB_Page, WikiDB_PageRevision, or string.
402 * This can be a relative subpage name (like '/SubPage'),
403 * or can be the empty string to refer to the $basename.
405 * @param string $anchor For links to anchors in page.
407 * @param mixed $basename Page name from which to interpret
408 * relative or other non-fully-specified page names.
410 function WikiPageName($name, $basename=false, $anchor=false) {
411 if (is_string($name)) {
412 $this->shortName = $name;
414 if (empty($name) or $name[0] == SUBPAGE_SEPARATOR) {
416 $name = $this->_pagename($basename) . $name;
418 $name = $this->_normalize_bad_pagename($name);
422 $name = $this->_pagename($name);
423 $this->shortName = $name;
426 $this->name = $this->_check($name);
427 $this->anchor = (string)$anchor;
430 function getParent() {
432 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
434 return substr($name, 0, -strlen($tail));
437 function isValid($strict = false) {
439 return !isset($this->_errors);
440 return !empty($this->name);
443 function getWarnings() {
445 if (isset($this->_warnings))
446 $warnings = array_merge($warnings, $this->_warnings);
447 if (isset($this->_errors))
448 $warnings = array_merge($warnings, $this->_errors);
452 return sprintf(_("'%s': Bad page name: %s"),
453 $this->shortName, join(', ', $warnings));
456 function _pagename($page) {
457 if (isa($page, 'WikiDB_Page'))
458 return $page->getName();
459 elseif (isa($page, 'WikiDB_PageRevision'))
460 return $page->getPageName();
461 elseif (isa($page, 'WikiPageName'))
463 if (!is_string($page)) {
464 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
465 $page, gettype($page), get_class($page)),
468 //assert(is_string($page));
472 function _normalize_bad_pagename($name) {
473 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
475 // Punt... You really shouldn't get here.
478 return $request->getArg('pagename');
480 assert($name[0] == SUBPAGE_SEPARATOR);
481 return substr($name, 1);
485 function _check($pagename) {
486 // Compress internal white-space to single space character.
487 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
488 if ($pagename != $orig)
489 $this->_warnings[] = _("White space converted to single space");
491 // Delete any control characters.
492 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
493 if ($pagename != $orig)
494 $this->_errors[] = _("Control characters not allowed");
496 // Strip leading and trailing white-space.
497 $pagename = trim($pagename);
500 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
501 $pagename = substr($pagename, 1);
502 if ($pagename != $orig)
503 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
505 if (preg_match('/[:;]/', $pagename))
506 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
508 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
509 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
510 $this->_errors[] = _("too long");
514 if ($pagename == '.' or $pagename == '..') {
515 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
524 * Convert old page markup to new-style markup.
526 * @param string $text Old-style wiki markup.
528 * @param string $markup_type
530 * <dt><code>"block"</code> <dd>Convert all markup.
531 * <dt><code>"inline"</code> <dd>Convert only inline markup.
532 * <dt><code>"links"</code> <dd>Convert only link markup.
535 * @return string New-style wiki markup.
537 * @bugs Footnotes don't work quite as before (esp if there are
538 * multiple references to the same footnote. But close enough,
539 * probably for now....
541 function ConvertOldMarkup ($text, $markup_type = "block") {
547 /*****************************************************************
548 * Conversions for inline markup:
555 // escape escaped brackets
559 // change ! escapes to ~'s.
560 global $AllowedProtocols, $WikiNameRegexp, $request;
561 //include_once('lib/interwiki.php');
562 $map = PageType_interwikimap::GetMap($request);
563 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
564 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
565 $bang_esc[] = $WikiNameRegexp;
566 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
569 $subs["links"] = array($orig, $repl);
572 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
575 // Convert footnote references.
576 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
577 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
579 // Convert old style emphases to HTML style emphasis.
580 $orig[] = '/__(.*?)__/';
581 $repl[] = '<strong>\\1</strong>';
582 $orig[] = "/''(.*?)''/";
583 $repl[] = '<em>\\1</em>';
585 // Escape nestled markup.
586 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
589 // in old markup headings only allowed at beginning of line
593 $subs["inline"] = array($orig, $repl);
595 /*****************************************************************
596 * Patterns which match block markup constructs which take
597 * special handling...
601 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
604 $blockpats[] = '\|(?:.*\n\|)*';
607 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
609 // Footnote definitions
610 $blockpats[] = '\[\s*(\d+)\s*\]';
613 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
616 $blockpats[] = '!{1,3}[^!]';
618 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
619 . join("|", $blockpats)
624 if ($markup_type != "block") {
625 list ($orig, $repl) = $subs[$markup_type];
626 return preg_replace($orig, $repl, $text);
629 list ($orig, $repl) = $subs['inline'];
631 while (preg_match($block_re, $text, $m)) {
632 $text = substr($text, strlen($m[0]));
633 list (,$leading_text, $block) = $m;
636 if (strchr(" \t", $block[0])) {
639 $suffix = "\n</pre>\n";
641 elseif ($block[0] == '|') {
643 $prefix = "<?plugin OldStyleTable\n";
646 elseif (strchr("#*;", $block[0])) {
647 // Old-style list item
648 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
649 list (,$ind,$bullet) = $m;
650 $block = substr($block, strlen($m[0]));
652 $indent = str_repeat(' ', strlen($ind));
653 if ($bullet[0] == ';') {
654 //$term = ltrim(substr($bullet, 1));
655 //return $indent . $term . "\n" . $indent . ' ';
656 $prefix = $ind . $bullet;
659 $prefix = $indent . $bullet . ' ';
661 elseif ($block[0] == '[') {
662 // Footnote definition
663 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
665 $block = substr($block, strlen($m[0]));
666 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
668 elseif ($block[0] == '<') {
670 // HACK: no inline markup...
674 elseif ($block[0] == '!') {
676 preg_match('/^!{1,3}/', $block, $m);
678 $block = substr($block, strlen($m[0]));
685 $out .= ( preg_replace($orig, $repl, $leading_text)
687 . preg_replace($orig, $repl, $block)
690 return $out . preg_replace($orig, $repl, $text);
696 * Expand tabs in string.
698 * Converts all tabs to (the appropriate number of) spaces.
701 * @param integer $tab_width
704 function expand_tabs($str, $tab_width = 8) {
705 $split = split("\t", $str);
706 $tail = array_pop($split);
708 foreach ($split as $hunk) {
710 $pos = strlen(strrchr($expanded, "\n")) - 1;
711 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
713 return substr($expanded, 1) . $tail;
717 * Split WikiWords in page names.
719 * It has been deemed useful to split WikiWords (into "Wiki Words") in
720 * places like page titles. This is rumored to help search engines
723 * @param $page string The page name.
725 * @return string The split name.
727 function split_pagename ($page) {
729 if (preg_match("/\s/", $page))
730 return $page; // Already split --- don't split any more.
732 // FIXME: this algorithm is Anglo-centric.
735 // This mess splits between a lower-case letter followed by
736 // either an upper-case or a numeral; except that it wont
737 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
738 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
739 // This the single-letter words 'I' and 'A' from any following
740 // capitalized words.
741 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
742 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
743 // Split numerals from following letters.
744 $RE[] = '/(\d)([[:alpha:]])/';
746 foreach ($RE as $key => $val)
747 $RE[$key] = pcre_fix_posix_classes($val);
750 foreach ($RE as $regexp) {
751 $page = preg_replace($regexp, '\\1 \\2', $page);
756 function NoSuchRevision (&$request, $page, $version) {
757 $html = HTML(HTML::h2(_("Revision Not Found")),
758 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
759 $version, WikiLink($page, 'auto'))));
760 include_once('lib/Template.php');
761 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
767 * Get time offset for local time zone.
769 * @param $time time_t Get offset for this time. Default: now.
770 * @param $no_colon boolean Don't put colon between hours and minutes.
771 * @return string Offset as a string in the format +HH:MM.
773 function TimezoneOffset ($time = false, $no_colon = false) {
776 $secs = date('Z', $time);
785 $colon = $no_colon ? '' : ':';
786 $mins = intval(($secs + 30) / 60);
787 return sprintf("%s%02d%s%02d",
788 $sign, $mins / 60, $colon, $mins % 60);
793 * Format time in ISO-8601 format.
795 * @param $time time_t Time. Default: now.
796 * @return string Date and time in ISO-8601 format.
798 function Iso8601DateTime ($time = false) {
801 $tzoff = TimezoneOffset($time);
802 $date = date('Y-m-d', $time);
803 $time = date('H:i:s', $time);
804 return $date . 'T' . $time . $tzoff;
808 * Format time in RFC-2822 format.
810 * @param $time time_t Time. Default: now.
811 * @return string Date and time in RFC-2822 format.
813 function Rfc2822DateTime ($time = false) {
816 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
820 * Format time in RFC-1123 format.
822 * @param $time time_t Time. Default: now.
823 * @return string Date and time in RFC-1123 format.
825 function Rfc1123DateTime ($time = false) {
828 return gmdate('D, d M Y H:i:s \G\M\T', $time);
831 /** Parse date in RFC-1123 format.
833 * According to RFC 1123 we must accept dates in the following
836 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
837 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
838 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
840 * (Though we're only allowed to generate dates in the first format.)
842 function ParseRfc1123DateTime ($timestr) {
843 $timestr = trim($timestr);
844 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
845 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
847 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
849 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
850 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
852 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
853 if ($year < 70) $year += 2000;
854 elseif ($year < 100) $year += 1900;
856 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
857 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
859 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
866 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
868 return false; // failed
873 * Format time to standard 'ctime' format.
875 * @param $time time_t Time. Default: now.
876 * @return string Date and time.
878 function CTime ($time = false)
882 return date("D M j H:i:s Y", $time);
887 * Format number as kilobytes or bytes.
888 * Short format is used for PageList
889 * Long format is used in PageInfo
891 * @param $bytes int. Default: 0.
892 * @param $longformat bool. Default: false.
893 * @return class FormattedText (XmlElement.php).
895 function ByteFormatter ($bytes = 0, $longformat = false) {
900 $size = fmt("%s b", $bytes);
902 $size = fmt("%s bytes", $bytes);
905 $kb = round($bytes / 1024, 1);
907 $size = fmt("%s k", $kb);
909 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
915 * Internationalized printf.
917 * This is essentially the same as PHP's built-in printf
918 * with the following exceptions:
920 * <li> It passes the format string through gettext().
921 * <li> It supports the argument reordering extensions.
928 * __printf("Differences between versions %s and %s of %s",
929 * $new_link, $old_link, $page_link);
932 * Then in locale/po/de.po, one can reorder the printf arguments:
935 * msgid "Differences between %s and %s of %s."
936 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
939 * (Note that while PHP tries to expand $vars within double-quotes,
940 * the values in msgstr undergo no such expansion, so the '$'s
943 * One shouldn't use reordered arguments in the default format string.
944 * Backslashes in the default string would be necessary to escape the
945 * '$'s, and they'll cause all kinds of trouble....
947 function __printf ($fmt) {
948 $args = func_get_args();
950 echo __vsprintf($fmt, $args);
954 * Internationalized sprintf.
956 * This is essentially the same as PHP's built-in printf with the
957 * following exceptions:
960 * <li> It passes the format string through gettext().
961 * <li> It supports the argument reordering extensions.
966 function __sprintf ($fmt) {
967 $args = func_get_args();
969 return __vsprintf($fmt, $args);
973 * Internationalized vsprintf.
975 * This is essentially the same as PHP's built-in printf with the
976 * following exceptions:
979 * <li> It passes the format string through gettext().
980 * <li> It supports the argument reordering extensions.
985 function __vsprintf ($fmt, $args) {
986 $fmt = gettext($fmt);
987 // PHP's sprintf doesn't support variable with specifiers,
988 // like sprintf("%*s", 10, "x"); --- so we won't either.
990 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
991 // Format string has '%2$s' style argument reordering.
992 // PHP doesn't support this.
993 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
994 // literal variable name substitution only to keep locale
995 // strings uncluttered
996 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
997 '%1\$s','%s'), E_USER_WARNING); //php+locale error
999 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1002 // Reorder arguments appropriately.
1003 foreach($m[1] as $argnum) {
1004 if ($argnum < 1 || $argnum > count($args))
1005 trigger_error(sprintf(_("%s: argument index out of range"),
1006 $argnum), E_USER_WARNING);
1007 $newargs[] = $args[$argnum - 1];
1012 // Not all PHP's have vsprintf, so...
1013 array_unshift($args, $fmt);
1014 return call_user_func_array('sprintf', $args);
1017 function file_mtime ($filename) {
1018 if ($stat = stat($filename))
1022 function sort_file_mtime ($a, $b) {
1023 $ma = file_mtime($a);
1024 $mb = file_mtime($b);
1025 if (!$ma or !$mb or $ma == $mb) return 0;
1026 return ($ma > $mb) ? -1 : 1;
1031 * Build an array in $this->_fileList of files from $dirname.
1032 * Subdirectories are not traversed.
1034 * (This was a function LoadDir in lib/loadsave.php)
1035 * See also http://www.php.net/manual/en/function.readdir.php
1037 function getFiles($exclude=false,$sortby=false,$limit=false) {
1038 $list = $this->_fileList;
1040 switch (Pagelist::sortby($sortby,'db')) {
1041 case 'pagename ASC': break;
1042 case 'pagename DESC':
1043 $list = array_reverse($list);
1046 usort($list,'sort_file_mtime');
1049 usort($list,'sort_file_mtime');
1050 $list = array_reverse($list);
1055 return array_splice($list,0,$limit);
1059 function _filenameSelector($filename) {
1060 if (! $this->_pattern)
1063 return glob_match ($this->_pattern, $filename, $this->_case);
1067 function fileSet($directory, $filepattern = false) {
1068 $this->_fileList = array();
1069 $this->_pattern = $filepattern;
1070 $this->_case = !isWindows();
1071 $this->_pathsep = '/';
1073 if (empty($directory)) {
1074 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1076 return; // early return
1079 @ $dir_handle = opendir($dir=$directory);
1080 if (empty($dir_handle)) {
1081 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1082 $dir), E_USER_NOTICE);
1083 return; // early return
1086 while ($filename = readdir($dir_handle)) {
1087 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1089 if ($this->_filenameSelector($filename)) {
1090 array_push($this->_fileList, "$filename");
1091 //trigger_error(sprintf(_("found file %s"), $filename),
1092 // E_USER_NOTICE); //debugging
1095 closedir($dir_handle);
1101 // expands a list containing regex's to its matching entries
1102 class ListRegexExpand {
1103 var $match, $list, $index, $case_sensitive;
1104 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1105 $this->match = str_replace('/','\/',$match);
1106 $this->list = &$list;
1107 $this->case_sensitive = $case_sensitive;
1108 //$this->index = false;
1110 function listMatchCallback ($item, $key) {
1111 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1112 unset($this->list[$this->index]);
1113 $this->list[] = $item;
1116 function expandRegex ($index, &$pages) {
1117 $this->index = $index;
1118 array_walk($pages, array($this, 'listMatchCallback'));
1123 // convert fileglob to regex style
1124 function glob_to_pcre ($glob) {
1125 $re = preg_replace('/\./', '\\.', $glob);
1126 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1127 if (!preg_match('/^[\?\*]/',$glob))
1129 if (!preg_match('/[\?\*]$/',$glob))
1134 function glob_match ($glob, $against, $case_sensitive = true) {
1135 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1138 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1139 $list = explode(',',$input);
1140 // expand wildcards from list of $allnames
1141 if (preg_match('/[\?\*]/',$input)) {
1142 // Optimizing loop invariants:
1143 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1144 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1146 if (preg_match('/[\?\*]/',$f)) {
1148 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1149 $expand->expandRegex($i, $allnames);
1156 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1157 function explodePageList($input, $perm=false, $sortby='pagename', $limit=false) {
1158 include_once("lib/PageList.php");
1159 return PageList::explodePageList($input,$perm,$sortby,$limit);
1162 // Class introspections
1164 /** Determine whether object is of a specified type.
1166 * @param $object object An object.
1167 * @param $class string Class name.
1168 * @return bool True iff $object is a $class
1169 * or a sub-type of $class.
1171 function isa ($object, $class) {
1172 $lclass = strtolower($class);
1174 return is_object($object)
1175 && ( get_class($object) == strtolower($lclass)
1176 || is_subclass_of($object, $lclass) );
1179 /** Determine whether (possible) object has method.
1181 * @param $object mixed Object
1182 * @param $method string Method name
1183 * @return bool True iff $object is an object with has method $method.
1185 function can ($object, $method) {
1186 return is_object($object) && method_exists($object, strtolower($method));
1189 /** Determine whether a function is okay to use.
1191 * Some providers (e.g. Lycos) disable some of PHP functions for
1192 * "security reasons." This makes those functions, of course,
1193 * unusable, despite the fact the function_exists() says they
1196 * This function test to see if a function exists and is not
1197 * disallowed by PHP's disable_functions config setting.
1199 * @param string $function_name Function name
1200 * @return bool True iff function can be used.
1202 function function_usable($function_name) {
1204 if (!is_array($disabled)) {
1205 $disabled = array();
1206 // Use get_cfg_var since ini_get() is one of the disabled functions
1207 // (on Lycos, at least.)
1208 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1209 foreach ($split as $f)
1210 $disabled[strtolower($f)] = true;
1213 return ( function_exists($function_name)
1214 and ! isset($disabled[strtolower($function_name)])
1221 * This is used for generating ETags.
1223 function hash ($x) {
1224 if (is_scalar($x)) {
1227 elseif (is_array($x)) {
1229 return md5(serialize($x));
1231 elseif (is_object($x)) {
1234 trigger_error("Can't hash $x", E_USER_ERROR);
1239 * Seed the random number generator.
1241 * better_srand() ensures the randomizer is seeded only once.
1243 * How random do you want it? See:
1244 * http://www.php.net/manual/en/function.srand.php
1245 * http://www.php.net/manual/en/function.mt-srand.php
1247 function better_srand($seed = '') {
1248 static $wascalled = FALSE;
1250 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1253 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1258 * Recursively count all non-empty elements
1259 * in array of any dimension or mixed - i.e.
1260 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1261 * See http://www.php.net/manual/en/function.count.php
1263 function count_all($arg) {
1264 // skip if argument is empty
1266 //print_r($arg); //debugging
1268 // not an array, return 1 (base case)
1271 // else call recursively for all elements $arg
1272 foreach($arg as $key => $val)
1273 $count += count_all($val);
1278 function isSubPage($pagename) {
1279 return (strstr($pagename, SUBPAGE_SEPARATOR));
1282 function subPageSlice($pagename, $pos) {
1283 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1284 $pages = array_slice($pages,$pos,1);
1291 * Class for "popping up" and alert box. (Except that right now, it doesn't
1295 * This is a hackish and needs to be refactored. However it would be nice to
1296 * unify all the different methods we use for showing Alerts and Dialogs.
1297 * (E.g. "Page deleted", login form, ...)
1302 * @param object $request
1303 * @param mixed $head Header ("title") for alert box.
1304 * @param mixed $body The text in the alert box.
1305 * @param hash $buttons An array mapping button labels to URLs.
1306 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1308 function Alert($head, $body, $buttons=false) {
1309 if ($buttons === false)
1312 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1313 $this->_buttons = $buttons;
1317 * Show the alert box.
1319 function show(&$request) {
1322 $tokens = $this->_tokens;
1323 $tokens['BUTTONS'] = $this->_getButtons();
1325 $request->discardOutput();
1326 $tmpl = new Template('dialog', $request, $tokens);
1332 function _getButtons() {
1335 $buttons = $this->_buttons;
1337 $buttons = array(_("Okay") => $request->getURLtoSelf());
1340 foreach ($buttons as $label => $url)
1341 print "$label $url\n";
1342 $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1343 return new XmlContent($out);
1348 * Returns true if current php version is at mimimum a.b.c
1349 * Called: check_php_version(4,1)
1351 function check_php_version ($a = '0', $b = '0', $c = '0') {
1352 global $PHP_VERSION;
1353 if(!isset($PHP_VERSION))
1354 $PHP_VERSION = substr( str_pad( preg_replace('/\D/','', PHP_VERSION), 3, '0'), 0, 3);
1355 return $PHP_VERSION >= ($a.$b.$c);
1358 function isWikiWord($word) {
1359 global $WikiNameRegexp;
1360 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1361 return preg_match("/^$WikiNameRegexp\$/",$word);
1364 // needed to store serialized objects-values only (perm, pref)
1365 function obj2hash ($obj, $exclude = false, $fields = false) {
1367 if (! $fields ) $fields = get_object_vars($obj);
1368 foreach ($fields as $key => $val) {
1369 if (is_array($exclude)) {
1370 if (in_array($key,$exclude)) continue;
1377 // $Log: not supported by cvs2svn $
1378 // Revision 1.164 2004/03/18 21:41:09 rurban
1379 // fixed sqlite support
1380 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
1382 // Revision 1.163 2004/03/17 18:41:49 rurban
1383 // just reformatting
1385 // Revision 1.162 2004/03/16 15:43:08 rurban
1386 // make fileSet sortable to please PageList
1388 // Revision 1.161 2004/03/12 15:48:07 rurban
1389 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1390 // simplified lib/stdlib.php:explodePageList
1392 // Revision 1.160 2004/02/28 21:14:08 rurban
1393 // generally more PHPDOC docs
1394 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
1395 // fxied WikiUserNew pref handling: empty theme not stored, save only
1396 // changed prefs, sql prefs improved, fixed password update,
1397 // removed REPLACE sql (dangerous)
1398 // moved gettext init after the locale was guessed
1399 // + some minor changes
1401 // Revision 1.158 2004/02/19 21:54:17 rurban
1402 // moved initerwiki code to PageType.php
1403 // re-enabled and fixed InlineImages support, now also for InterWiki Urls
1404 // * [File:my_image.gif] inlines the image,
1405 // * File:my_image.gif shows a plain inter-wiki link,
1406 // * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
1407 // * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
1409 // Revision 1.157 2004/02/09 03:58:12 rurban
1410 // for now default DB_SESSION to false
1412 // * not existing perms will now query the parent, and not
1413 // return the default perm
1414 // * added pagePermissions func which returns the object per page
1415 // * added getAccessDescription
1417 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1418 // * force init of authdbh in the 2 db classes
1420 // * fixed session handling (not triple auth request anymore)
1421 // * don't store cookie prefs with sessions
1422 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1424 // Revision 1.156 2004/01/26 09:17:49 rurban
1425 // * changed stored pref representation as before.
1426 // the array of objects is 1) bigger and 2)
1427 // less portable. If we would import packed pref
1428 // objects and the object definition was changed, PHP would fail.
1429 // This doesn't happen with an simple array of non-default values.
1430 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1431 // understands the interim format of array of objects also.
1432 // * simplified $prefs->get() and fixed $prefs->set()
1433 // * added $user->_userid and class '_WikiUser' portability functions
1434 // * fixed $user object ->_level upgrading, mostly using sessions.
1435 // this fixes yesterdays problems with loosing authorization level.
1436 // * fixed WikiUserNew::checkPass to return the _level
1437 // * fixed WikiUserNew::isSignedIn
1438 // * added explodePageList to class PageList, support sortby arg
1439 // * fixed UserPreferences for WikiUserNew
1440 // * fixed WikiPlugin for empty defaults array
1441 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1442 // removed sort arg, support sortby arg
1444 // Revision 1.155 2004/01/25 10:52:22 rurban
1445 // added sortby support to explodePageList() and UnfoldSubpages
1446 // fixes [ 758044 ] Plugin UnfoldSubpages does not sort (includes fix)
1448 // Revision 1.154 2004/01/25 03:49:03 rurban
1449 // added isWikiWord() to avoid redundancy
1450 // added check_php_version() to check for older php versions.
1451 // e.g. object::method calls, ...
1453 // Revision 1.153 2003/11/30 18:43:18 carstenklapp
1454 // Fixed careless mistakes in my last optimization commit.
1456 // Revision 1.152 2003/11/30 18:20:34 carstenklapp
1457 // Minor code optimization: reduce invariant loops
1459 // Revision 1.151 2003/11/29 19:30:01 carstenklapp
1460 // New function ByteFormatter.
1462 // Revision 1.150 2003/09/13 22:43:00 carstenklapp
1463 // New preference to hide LinkIcons.
1465 // Revision 1.149 2003/03/26 19:37:08 dairiki
1466 // Fix "object to string conversion" bug with external image links.
1468 // Revision 1.148 2003/03/25 21:03:02 dairiki
1469 // Cleanup debugging output.
1471 // Revision 1.147 2003/03/13 20:17:05 dairiki
1472 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1474 // Revision 1.146 2003/03/07 02:46:24 dairiki
1475 // function_usable(): New function.
1477 // Revision 1.145 2003/03/04 01:55:05 dairiki
1478 // Fix to ensure absolute URL for logo in RSS recent changes.
1480 // Revision 1.144 2003/02/26 00:39:30 dairiki
1481 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1482 // being displayed at incorrect times.
1484 // Revision 1.143 2003/02/26 00:10:26 dairiki
1485 // More/better/different checks for bad page names.
1487 // Revision 1.142 2003/02/25 22:19:46 dairiki
1488 // Add some sanity checking for pagenames.
1490 // Revision 1.141 2003/02/22 20:49:55 dairiki
1491 // Fixes for "Call-time pass by reference has been deprecated" errors.
1493 // Revision 1.140 2003/02/21 23:33:29 dairiki
1494 // Set alt="" on the link icon image tags.
1495 // (See SF bug #675141.)
1497 // Revision 1.139 2003/02/21 22:16:27 dairiki
1498 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1499 // These have been obsolete for quite awhile (I hope).
1501 // Revision 1.138 2003/02/21 04:12:36 dairiki
1502 // WikiPageName: fixes for new cached links.
1504 // Alert: new class for displaying alerts.
1506 // ExtractWikiPageLinks and friends are now gone.
1508 // LinkBracketLink moved to InlineParser.php
1510 // Revision 1.137 2003/02/18 23:13:40 dairiki
1511 // Wups again. Typo fix.
1513 // Revision 1.136 2003/02/18 21:52:07 dairiki
1514 // Fix so that one can still link to wiki pages with # in their names.
1515 // (This was made difficult by the introduction of named tags, since
1516 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1518 // Now the ~ escape for page names should work: [Page ~#1].
1520 // Revision 1.135 2003/02/18 19:17:04 dairiki
1521 // split_pagename():
1522 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1523 // Cleanup up subpage splitting code.
1525 // Revision 1.134 2003/02/16 19:44:20 dairiki
1526 // New function hash(). This is a helper, primarily for generating
1529 // Revision 1.133 2003/02/16 04:50:09 dairiki
1531 // Rfc1123DateTime(), ParseRfc1123DateTime()
1532 // for converting unix timestamps to and from strings.
1534 // These functions produce and grok the time strings
1535 // in the format specified by RFC 2616 for use in HTTP headers
1536 // (like Last-Modified).
1538 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1539 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1540 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1543 // (c-file-style: "gnu")
1547 // c-basic-offset: 4
1548 // c-hanging-comment-ender-p: nil
1549 // indent-tabs-mode: nil