1 <?php //rcs_id('$Id: stdlib.php,v 1.170 2004-04-19 18:27:45 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;
101 $anchor = $pagename->anchor;
102 $pagename = $pagename->name;
106 if (is_array($args)) {
108 foreach ($args as $key => $val) {
109 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
110 $enc_args[] = urlencode($key) . '=' . urlencode($val);
112 $args = join('&', $enc_args);
116 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
117 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
122 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
123 $url .= "?pagename=" . rawurlencode($pagename);
128 $url .= "#" . MangleXmlIdentifier($anchor);
132 /** Convert relative URL to absolute URL.
134 * This converts a relative URL to one of PhpWiki's support files
135 * to an absolute one.
138 * @return string Absolute URL
140 function AbsoluteURL ($url) {
141 if (preg_match('/^https?:/', $url))
143 if ($url[0] != '/') {
144 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
145 while ($base != '/' and substr($url, 0, 3) == "../") {
146 $url = substr($url, 3);
147 $base = dirname($base);
153 return SERVER_URL . $url;
157 * Generates icon in front of links.
159 * @param string $protocol_or_url URL or protocol to determine which icon to use.
161 * @return HtmlElement HtmlElement object that contains data to create img link to
162 * icon for use with url or protocol passed to the function. False if no img to be
165 function IconForLink($protocol_or_url) {
167 if (0 and $filename_suffix == false) {
168 // display apache style icon for file type instead of protocol icon
169 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
170 // - document: html, htm, text, txt, rtf, pdf, doc
171 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
172 // - audio: mp3,mp2,aiff,aif,au
173 // - multimedia: mpeg,mpg,mov,qt
175 list ($proto) = explode(':', $protocol_or_url, 2);
176 $src = $Theme->getLinkIconURL($proto);
178 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
185 * Glue icon in front of text.
187 * @param string $protocol_or_url Protocol or URL. Used to determine the
189 * @param string $text The text.
190 * @return XmlContent.
192 function PossiblyGlueIconToText($proto_or_url, $text) {
194 if (! $request->getPref('noLinkIcons')) {
195 $icon = IconForLink($proto_or_url);
197 if (!is_object($text)) {
198 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
199 list (, $first_word, $tail) = $m;
206 $text = HTML::span(array('style' => 'white-space: nowrap'),
209 $text = HTML($text, $tail);
216 * Determines if the url passed to function is safe, by detecting if the characters
217 * '<', '>', or '"' are present.
219 * @param string $url URL to check for unsafe characters.
220 * @return boolean True if same, false else.
222 function IsSafeURL($url) {
223 return !ereg('[<>"]', $url);
227 * Generates an HtmlElement object to store data for a link.
229 * @param string $url URL that the link will point to.
230 * @param string $linktext Text to be displayed as link.
231 * @return HtmlElement HtmlElement object that contains data to construct an html link.
233 function LinkURL($url, $linktext = '') {
234 // FIXME: Is this needed (or sufficient?)
235 if(! IsSafeURL($url)) {
236 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
237 _("BAD URL -- remove all of <, >, \"")));
241 $linktext = preg_replace("/mailto:/A", "", $url);
243 $link = HTML::a(array('href' => $url),
244 PossiblyGlueIconToText($url, $linktext));
247 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
252 function LinkImage($url, $alt = false) {
253 // FIXME: Is this needed (or sufficient?)
254 if(! IsSafeURL($url)) {
255 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
256 _("BAD URL -- remove all of <, >, \"")));
261 $link = HTML::img(array('src' => $url, 'alt' => $alt));
263 $link->setAttr('class', 'inlineimage');
270 var $items = array();
272 // var in php5.0.0.rc1 deprecated
274 function push($item) {
275 $this->items[$this->size] = $item;
281 if ($this->size == 0) {
282 return false; // stack is empty
285 return $this->items[$this->size];
294 return $this->items[$this->size - 1];
300 // end class definition
302 function SplitQueryArgs ($query_args = '')
304 $split_args = split('&', $query_args);
306 while (list($key, $val) = each($split_args))
307 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
308 $args[$m[1]] = $m[2];
312 function LinkPhpwikiURL($url, $text = '', $basepage) {
315 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
316 return HTML::strong(array('class' => 'rawurl'),
317 HTML::u(array('class' => 'baduri'),
318 _("BAD phpwiki: URL")));
322 $pagename = urldecode($m[1]);
325 if (empty($pagename) &&
326 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
327 // Convert old style links (to not break diff links in
329 $pagename = urldecode($m[2]);
330 $args = array("action" => $m[1]);
333 $args = SplitQueryArgs($qargs);
336 if (empty($pagename))
337 $pagename = $GLOBALS['request']->getArg('pagename');
339 if (isset($args['action']) && $args['action'] == 'browse')
340 unset($args['action']);
343 if (empty($args['action']))
345 else if (is_safe_action($args['action']))
346 $class = 'wikiaction';
348 if (empty($args['action']) || is_safe_action($args['action']))
349 $class = 'wikiaction';
351 // Don't allow administrative links on unlocked pages.
352 $dbi = $GLOBALS['request']->getDbh();
353 $page = $dbi->getPage($basepage);
354 if (!$page->get('locked'))
355 return HTML::span(array('class' => 'wikiunsafe'),
356 HTML::u(_("Lock page to enable link")));
357 $class = 'wikiadmin';
361 $text = HTML::span(array('class' => 'rawurl'), $url);
363 $wikipage = new WikiPageName($pagename);
364 if (!$wikipage->isValid()) {
366 return $Theme->linkBadWikiWord($wikipage, $url);
369 return HTML::a(array('href' => WikiURL($pagename, $args),
375 * A class to assist in parsing wiki pagenames.
377 * Now with subpages and anchors, parsing and passing around
378 * pagenames is more complicated. This should help.
382 /** Short name for page.
384 * This is the value of $name passed to the constructor.
385 * (For use, e.g. as a default label for links to the page.)
389 /** The full page name.
391 * This is the full name of the page (without anchor).
397 * This is the referenced anchor within the page, or the empty string.
403 * @param mixed $name Page name.
404 * WikiDB_Page, WikiDB_PageRevision, or string.
405 * This can be a relative subpage name (like '/SubPage'),
406 * or can be the empty string to refer to the $basename.
408 * @param string $anchor For links to anchors in page.
410 * @param mixed $basename Page name from which to interpret
411 * relative or other non-fully-specified page names.
413 function WikiPageName($name, $basename=false, $anchor=false) {
414 if (is_string($name)) {
415 $this->shortName = $name;
417 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
419 $name = $this->_pagename($basename) . $name;
421 $name = $this->_normalize_bad_pagename($name);
425 $name = $this->_pagename($name);
426 $this->shortName = $name;
429 $this->name = $this->_check($name);
430 $this->anchor = (string)$anchor;
433 function getParent() {
435 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
437 return substr($name, 0, -strlen($tail));
440 function isValid($strict = false) {
442 return !isset($this->_errors);
443 return !empty($this->name);
446 function getWarnings() {
448 if (isset($this->_warnings))
449 $warnings = array_merge($warnings, $this->_warnings);
450 if (isset($this->_errors))
451 $warnings = array_merge($warnings, $this->_errors);
455 return sprintf(_("'%s': Bad page name: %s"),
456 $this->shortName, join(', ', $warnings));
459 function _pagename($page) {
460 if (isa($page, 'WikiDB_Page'))
461 return $page->getName();
462 elseif (isa($page, 'WikiDB_PageRevision'))
463 return $page->getPageName();
464 elseif (isa($page, 'WikiPageName'))
466 if (!is_string($page)) {
467 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
468 $page, gettype($page), get_class($page)),
471 //assert(is_string($page));
475 function _normalize_bad_pagename($name) {
476 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
478 // Punt... You really shouldn't get here.
481 return $request->getArg('pagename');
483 assert($name[0] == SUBPAGE_SEPARATOR);
484 return substr($name, 1);
488 function _check($pagename) {
489 // Compress internal white-space to single space character.
490 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
491 if ($pagename != $orig)
492 $this->_warnings[] = _("White space converted to single space");
494 // Delete any control characters.
495 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
496 if ($pagename != $orig)
497 $this->_errors[] = _("Control characters not allowed");
499 // Strip leading and trailing white-space.
500 $pagename = trim($pagename);
503 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
504 $pagename = substr($pagename, 1);
505 if ($pagename != $orig)
506 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
508 if (preg_match('/[:;]/', $pagename))
509 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
511 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
512 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
513 $this->_errors[] = _("too long");
517 if ($pagename == '.' or $pagename == '..') {
518 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
527 * Convert old page markup to new-style markup.
529 * @param string $text Old-style wiki markup.
531 * @param string $markup_type
533 * <dt><code>"block"</code> <dd>Convert all markup.
534 * <dt><code>"inline"</code> <dd>Convert only inline markup.
535 * <dt><code>"links"</code> <dd>Convert only link markup.
538 * @return string New-style wiki markup.
540 * @bugs Footnotes don't work quite as before (esp if there are
541 * multiple references to the same footnote. But close enough,
542 * probably for now....
544 function ConvertOldMarkup ($text, $markup_type = "block") {
550 /*****************************************************************
551 * Conversions for inline markup:
558 // escape escaped brackets
562 // change ! escapes to ~'s.
563 global $AllowedProtocols, $WikiNameRegexp, $request;
564 //include_once('lib/interwiki.php');
565 $map = getInterwikiMap();
566 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
567 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
568 $bang_esc[] = $WikiNameRegexp;
569 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
572 $subs["links"] = array($orig, $repl);
575 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
578 // Convert footnote references.
579 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
580 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
582 // Convert old style emphases to HTML style emphasis.
583 $orig[] = '/__(.*?)__/';
584 $repl[] = '<strong>\\1</strong>';
585 $orig[] = "/''(.*?)''/";
586 $repl[] = '<em>\\1</em>';
588 // Escape nestled markup.
589 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
592 // in old markup headings only allowed at beginning of line
596 $subs["inline"] = array($orig, $repl);
598 /*****************************************************************
599 * Patterns which match block markup constructs which take
600 * special handling...
604 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
607 $blockpats[] = '\|(?:.*\n\|)*';
610 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
612 // Footnote definitions
613 $blockpats[] = '\[\s*(\d+)\s*\]';
616 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
619 $blockpats[] = '!{1,3}[^!]';
621 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
622 . join("|", $blockpats)
627 if ($markup_type != "block") {
628 list ($orig, $repl) = $subs[$markup_type];
629 return preg_replace($orig, $repl, $text);
632 list ($orig, $repl) = $subs['inline'];
634 while (preg_match($block_re, $text, $m)) {
635 $text = substr($text, strlen($m[0]));
636 list (,$leading_text, $block) = $m;
639 if (strchr(" \t", $block[0])) {
642 $suffix = "\n</pre>\n";
644 elseif ($block[0] == '|') {
646 $prefix = "<?plugin OldStyleTable\n";
649 elseif (strchr("#*;", $block[0])) {
650 // Old-style list item
651 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
652 list (,$ind,$bullet) = $m;
653 $block = substr($block, strlen($m[0]));
655 $indent = str_repeat(' ', strlen($ind));
656 if ($bullet[0] == ';') {
657 //$term = ltrim(substr($bullet, 1));
658 //return $indent . $term . "\n" . $indent . ' ';
659 $prefix = $ind . $bullet;
662 $prefix = $indent . $bullet . ' ';
664 elseif ($block[0] == '[') {
665 // Footnote definition
666 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
668 $block = substr($block, strlen($m[0]));
669 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
671 elseif ($block[0] == '<') {
673 // HACK: no inline markup...
677 elseif ($block[0] == '!') {
679 preg_match('/^!{1,3}/', $block, $m);
681 $block = substr($block, strlen($m[0]));
688 $out .= ( preg_replace($orig, $repl, $leading_text)
690 . preg_replace($orig, $repl, $block)
693 return $out . preg_replace($orig, $repl, $text);
699 * Expand tabs in string.
701 * Converts all tabs to (the appropriate number of) spaces.
704 * @param integer $tab_width
707 function expand_tabs($str, $tab_width = 8) {
708 $split = split("\t", $str);
709 $tail = array_pop($split);
711 foreach ($split as $hunk) {
713 $pos = strlen(strrchr($expanded, "\n")) - 1;
714 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
716 return substr($expanded, 1) . $tail;
720 * Split WikiWords in page names.
722 * It has been deemed useful to split WikiWords (into "Wiki Words") in
723 * places like page titles. This is rumored to help search engines
726 * @param $page string The page name.
728 * @return string The split name.
730 function split_pagename ($page) {
732 if (preg_match("/\s/", $page))
733 return $page; // Already split --- don't split any more.
735 // FIXME: this algorithm is Anglo-centric.
738 // This mess splits between a lower-case letter followed by
739 // either an upper-case or a numeral; except that it wont
740 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
741 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
742 // This the single-letter words 'I' and 'A' from any following
743 // capitalized words.
744 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
745 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
746 // Split numerals from following letters.
747 $RE[] = '/(\d)([[:alpha:]])/';
748 //TODO: Split at subpage seperators. TBD in Theme.php
749 //$RE[] = "/(${sep})([^${sep}]+)/";
751 foreach ($RE as $key)
752 $RE[$key] = pcre_fix_posix_classes($key);
755 foreach ($RE as $regexp) {
756 $page = preg_replace($regexp, '\\1 \\2', $page);
761 function NoSuchRevision (&$request, $page, $version) {
762 $html = HTML(HTML::h2(_("Revision Not Found")),
763 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
764 $version, WikiLink($page, 'auto'))));
765 include_once('lib/Template.php');
766 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
772 * Get time offset for local time zone.
774 * @param $time time_t Get offset for this time. Default: now.
775 * @param $no_colon boolean Don't put colon between hours and minutes.
776 * @return string Offset as a string in the format +HH:MM.
778 function TimezoneOffset ($time = false, $no_colon = false) {
781 $secs = date('Z', $time);
790 $colon = $no_colon ? '' : ':';
791 $mins = intval(($secs + 30) / 60);
792 return sprintf("%s%02d%s%02d",
793 $sign, $mins / 60, $colon, $mins % 60);
798 * Format time in ISO-8601 format.
800 * @param $time time_t Time. Default: now.
801 * @return string Date and time in ISO-8601 format.
803 function Iso8601DateTime ($time = false) {
806 $tzoff = TimezoneOffset($time);
807 $date = date('Y-m-d', $time);
808 $time = date('H:i:s', $time);
809 return $date . 'T' . $time . $tzoff;
813 * Format time in RFC-2822 format.
815 * @param $time time_t Time. Default: now.
816 * @return string Date and time in RFC-2822 format.
818 function Rfc2822DateTime ($time = false) {
821 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
825 * Format time in RFC-1123 format.
827 * @param $time time_t Time. Default: now.
828 * @return string Date and time in RFC-1123 format.
830 function Rfc1123DateTime ($time = false) {
833 return gmdate('D, d M Y H:i:s \G\M\T', $time);
836 /** Parse date in RFC-1123 format.
838 * According to RFC 1123 we must accept dates in the following
841 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
842 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
843 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
845 * (Though we're only allowed to generate dates in the first format.)
847 function ParseRfc1123DateTime ($timestr) {
848 $timestr = trim($timestr);
849 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
850 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
852 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
854 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
855 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
857 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
858 if ($year < 70) $year += 2000;
859 elseif ($year < 100) $year += 1900;
861 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
862 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
864 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
871 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
873 return false; // failed
878 * Format time to standard 'ctime' format.
880 * @param $time time_t Time. Default: now.
881 * @return string Date and time.
883 function CTime ($time = false)
887 return date("D M j H:i:s Y", $time);
892 * Format number as kilobytes or bytes.
893 * Short format is used for PageList
894 * Long format is used in PageInfo
896 * @param $bytes int. Default: 0.
897 * @param $longformat bool. Default: false.
898 * @return class FormattedText (XmlElement.php).
900 function ByteFormatter ($bytes = 0, $longformat = false) {
905 $size = fmt("%s b", $bytes);
907 $size = fmt("%s bytes", $bytes);
910 $kb = round($bytes / 1024, 1);
912 $size = fmt("%s k", $kb);
914 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
920 * Internationalized printf.
922 * This is essentially the same as PHP's built-in printf
923 * with the following exceptions:
925 * <li> It passes the format string through gettext().
926 * <li> It supports the argument reordering extensions.
933 * __printf("Differences between versions %s and %s of %s",
934 * $new_link, $old_link, $page_link);
937 * Then in locale/po/de.po, one can reorder the printf arguments:
940 * msgid "Differences between %s and %s of %s."
941 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
944 * (Note that while PHP tries to expand $vars within double-quotes,
945 * the values in msgstr undergo no such expansion, so the '$'s
948 * One shouldn't use reordered arguments in the default format string.
949 * Backslashes in the default string would be necessary to escape the
950 * '$'s, and they'll cause all kinds of trouble....
952 function __printf ($fmt) {
953 $args = func_get_args();
955 echo __vsprintf($fmt, $args);
959 * Internationalized sprintf.
961 * This is essentially the same as PHP's built-in printf with the
962 * following exceptions:
965 * <li> It passes the format string through gettext().
966 * <li> It supports the argument reordering extensions.
971 function __sprintf ($fmt) {
972 $args = func_get_args();
974 return __vsprintf($fmt, $args);
978 * Internationalized vsprintf.
980 * This is essentially the same as PHP's built-in printf with the
981 * following exceptions:
984 * <li> It passes the format string through gettext().
985 * <li> It supports the argument reordering extensions.
990 function __vsprintf ($fmt, $args) {
991 $fmt = gettext($fmt);
992 // PHP's sprintf doesn't support variable with specifiers,
993 // like sprintf("%*s", 10, "x"); --- so we won't either.
995 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
996 // Format string has '%2$s' style argument reordering.
997 // PHP doesn't support this.
998 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
999 // literal variable name substitution only to keep locale
1000 // strings uncluttered
1001 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1002 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1004 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1007 // Reorder arguments appropriately.
1008 foreach($m[1] as $argnum) {
1009 if ($argnum < 1 || $argnum > count($args))
1010 trigger_error(sprintf(_("%s: argument index out of range"),
1011 $argnum), E_USER_WARNING);
1012 $newargs[] = $args[$argnum - 1];
1017 // Not all PHP's have vsprintf, so...
1018 array_unshift($args, $fmt);
1019 return call_user_func_array('sprintf', $args);
1022 function file_mtime ($filename) {
1023 if ($stat = stat($filename))
1029 function sort_file_mtime ($a, $b) {
1030 $ma = file_mtime($a);
1031 $mb = file_mtime($b);
1032 if (!$ma or !$mb or $ma == $mb) return 0;
1033 return ($ma > $mb) ? -1 : 1;
1038 * Build an array in $this->_fileList of files from $dirname.
1039 * Subdirectories are not traversed.
1041 * (This was a function LoadDir in lib/loadsave.php)
1042 * See also http://www.php.net/manual/en/function.readdir.php
1044 function getFiles($exclude=false,$sortby=false,$limit=false) {
1045 $list = $this->_fileList;
1047 switch (Pagelist::sortby($sortby,'db')) {
1048 case 'pagename ASC': break;
1049 case 'pagename DESC':
1050 $list = array_reverse($list);
1053 usort($list,'sort_file_mtime');
1056 usort($list,'sort_file_mtime');
1057 $list = array_reverse($list);
1062 return array_splice($list,0,$limit);
1066 function _filenameSelector($filename) {
1067 if (! $this->_pattern)
1070 return glob_match ($this->_pattern, $filename, $this->_case);
1074 function fileSet($directory, $filepattern = false) {
1075 $this->_fileList = array();
1076 $this->_pattern = $filepattern;
1077 $this->_case = !isWindows();
1078 $this->_pathsep = '/';
1080 if (empty($directory)) {
1081 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1083 return; // early return
1086 @ $dir_handle = opendir($dir=$directory);
1087 if (empty($dir_handle)) {
1088 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1089 $dir), E_USER_NOTICE);
1090 return; // early return
1093 while ($filename = readdir($dir_handle)) {
1094 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1096 if ($this->_filenameSelector($filename)) {
1097 array_push($this->_fileList, "$filename");
1098 //trigger_error(sprintf(_("found file %s"), $filename),
1099 // E_USER_NOTICE); //debugging
1102 closedir($dir_handle);
1108 // expands a list containing regex's to its matching entries
1109 class ListRegexExpand {
1110 var $match, $list, $index, $case_sensitive;
1111 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1112 $this->match = str_replace('/','\/',$match);
1113 $this->list = &$list;
1114 $this->case_sensitive = $case_sensitive;
1115 //$this->index = false;
1117 function listMatchCallback ($item, $key) {
1118 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1119 unset($this->list[$this->index]);
1120 $this->list[] = $item;
1123 function expandRegex ($index, &$pages) {
1124 $this->index = $index;
1125 array_walk($pages, array($this, 'listMatchCallback'));
1130 // convert fileglob to regex style
1131 function glob_to_pcre ($glob) {
1132 $re = preg_replace('/\./', '\\.', $glob);
1133 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1134 if (!preg_match('/^[\?\*]/',$glob))
1136 if (!preg_match('/[\?\*]$/',$glob))
1141 function glob_match ($glob, $against, $case_sensitive = true) {
1142 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1145 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1146 $list = explode(',',$input);
1147 // expand wildcards from list of $allnames
1148 if (preg_match('/[\?\*]/',$input)) {
1149 // Optimizing loop invariants:
1150 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1151 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1153 if (preg_match('/[\?\*]/',$f)) {
1155 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1156 $expand->expandRegex($i, $allnames);
1163 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1164 function explodePageList($input, $perm=false, $sortby='pagename', $limit=false) {
1165 include_once("lib/PageList.php");
1166 return PageList::explodePageList($input,$perm,$sortby,$limit);
1169 // Class introspections
1171 /** Determine whether object is of a specified type.
1173 * @param $object object An object.
1174 * @param $class string Class name.
1175 * @return bool True iff $object is a $class
1176 * or a sub-type of $class.
1178 function isa ($object, $class) {
1179 $lclass = strtolower($class);
1181 return is_object($object)
1182 && ( get_class($object) == strtolower($lclass)
1183 || is_subclass_of($object, $lclass) );
1186 /** Determine whether (possible) object has method.
1188 * @param $object mixed Object
1189 * @param $method string Method name
1190 * @return bool True iff $object is an object with has method $method.
1192 function can ($object, $method) {
1193 return is_object($object) && method_exists($object, strtolower($method));
1196 /** Determine whether a function is okay to use.
1198 * Some providers (e.g. Lycos) disable some of PHP functions for
1199 * "security reasons." This makes those functions, of course,
1200 * unusable, despite the fact the function_exists() says they
1203 * This function test to see if a function exists and is not
1204 * disallowed by PHP's disable_functions config setting.
1206 * @param string $function_name Function name
1207 * @return bool True iff function can be used.
1209 function function_usable($function_name) {
1211 if (!is_array($disabled)) {
1212 $disabled = array();
1213 // Use get_cfg_var since ini_get() is one of the disabled functions
1214 // (on Lycos, at least.)
1215 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1216 foreach ($split as $f)
1217 $disabled[strtolower($f)] = true;
1220 return ( function_exists($function_name)
1221 and ! isset($disabled[strtolower($function_name)])
1228 * This is used for generating ETags.
1230 function hash ($x) {
1231 if (is_scalar($x)) {
1234 elseif (is_array($x)) {
1236 return md5(serialize($x));
1238 elseif (is_object($x)) {
1241 trigger_error("Can't hash $x", E_USER_ERROR);
1246 * Seed the random number generator.
1248 * better_srand() ensures the randomizer is seeded only once.
1250 * How random do you want it? See:
1251 * http://www.php.net/manual/en/function.srand.php
1252 * http://www.php.net/manual/en/function.mt-srand.php
1254 function better_srand($seed = '') {
1255 static $wascalled = FALSE;
1257 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1260 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1265 * Recursively count all non-empty elements
1266 * in array of any dimension or mixed - i.e.
1267 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1268 * See http://www.php.net/manual/en/function.count.php
1270 function count_all($arg) {
1271 // skip if argument is empty
1273 //print_r($arg); //debugging
1275 // not an array, return 1 (base case)
1278 // else call recursively for all elements $arg
1279 foreach($arg as $key => $val)
1280 $count += count_all($val);
1285 function isSubPage($pagename) {
1286 return (strstr($pagename, SUBPAGE_SEPARATOR));
1289 function subPageSlice($pagename, $pos) {
1290 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1291 $pages = array_slice($pages,$pos,1);
1298 * Class for "popping up" and alert box. (Except that right now, it doesn't
1302 * This is a hackish and needs to be refactored. However it would be nice to
1303 * unify all the different methods we use for showing Alerts and Dialogs.
1304 * (E.g. "Page deleted", login form, ...)
1309 * @param object $request
1310 * @param mixed $head Header ("title") for alert box.
1311 * @param mixed $body The text in the alert box.
1312 * @param hash $buttons An array mapping button labels to URLs.
1313 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1315 function Alert($head, $body, $buttons=false) {
1316 if ($buttons === false)
1319 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1320 $this->_buttons = $buttons;
1324 * Show the alert box.
1326 function show(&$request) {
1329 $tokens = $this->_tokens;
1330 $tokens['BUTTONS'] = $this->_getButtons();
1332 $request->discardOutput();
1333 $tmpl = new Template('dialog', $request, $tokens);
1339 function _getButtons() {
1342 $buttons = $this->_buttons;
1344 $buttons = array(_("Okay") => $request->getURLtoSelf());
1347 foreach ($buttons as $label => $url)
1348 print "$label $url\n";
1349 $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1350 return new XmlContent($out);
1355 * Returns true if current php version is at mimimum a.b.c
1356 * Called: check_php_version(4,1)
1358 function check_php_version ($a = '0', $b = '0', $c = '0') {
1359 global $PHP_VERSION;
1360 if(!isset($PHP_VERSION))
1361 $PHP_VERSION = substr( str_pad( preg_replace('/\D/','', PHP_VERSION), 3, '0'), 0, 3);
1362 return $PHP_VERSION >= ($a.$b.$c);
1365 function isWikiWord($word) {
1366 global $WikiNameRegexp;
1367 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1368 return preg_match("/^$WikiNameRegexp\$/",$word);
1371 // needed to store serialized objects-values only (perm, pref)
1372 function obj2hash ($obj, $exclude = false, $fields = false) {
1374 if (! $fields ) $fields = get_object_vars($obj);
1375 foreach ($fields as $key => $val) {
1376 if (is_array($exclude)) {
1377 if (in_array($key,$exclude)) continue;
1384 // $Log: not supported by cvs2svn $
1385 // Revision 1.169 2004/04/15 21:29:48 rurban
1386 // allow [0] with new markup: link to page "0"
1388 // Revision 1.168 2004/04/10 02:30:49 rurban
1389 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
1390 // Fixed "cannot setlocale..." (sf.net problem)
1392 // Revision 1.167 2004/04/02 15:06:55 rurban
1393 // fixed a nasty ADODB_mysql session update bug
1394 // improved UserPreferences layout (tabled hints)
1395 // fixed UserPreferences auth handling
1396 // improved auth stability
1397 // improved old cookie handling: fixed deletion of old cookies with paths
1399 // Revision 1.166 2004/04/01 15:57:10 rurban
1400 // simplified Sidebar theme: table, not absolute css positioning
1401 // added the new box methods.
1402 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
1404 // Revision 1.165 2004/03/24 19:39:03 rurban
1405 // php5 workaround code (plus some interim debugging code in XmlElement)
1406 // php5 doesn't work yet with the current XmlElement class constructors,
1407 // WikiUserNew does work better than php4.
1408 // rewrote WikiUserNew user upgrading to ease php5 update
1409 // fixed pref handling in WikiUserNew
1410 // added Email Notification
1411 // added simple Email verification
1412 // removed emailVerify userpref subclass: just a email property
1413 // changed pref binary storage layout: numarray => hash of non default values
1414 // print optimize message only if really done.
1415 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1416 // prefs should be stored in db or homepage, besides the current session.
1418 // Revision 1.164 2004/03/18 21:41:09 rurban
1419 // fixed sqlite support
1420 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
1422 // Revision 1.163 2004/03/17 18:41:49 rurban
1423 // just reformatting
1425 // Revision 1.162 2004/03/16 15:43:08 rurban
1426 // make fileSet sortable to please PageList
1428 // Revision 1.161 2004/03/12 15:48:07 rurban
1429 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1430 // simplified lib/stdlib.php:explodePageList
1432 // Revision 1.160 2004/02/28 21:14:08 rurban
1433 // generally more PHPDOC docs
1434 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
1435 // fxied WikiUserNew pref handling: empty theme not stored, save only
1436 // changed prefs, sql prefs improved, fixed password update,
1437 // removed REPLACE sql (dangerous)
1438 // moved gettext init after the locale was guessed
1439 // + some minor changes
1441 // Revision 1.158 2004/02/19 21:54:17 rurban
1442 // moved initerwiki code to PageType.php
1443 // re-enabled and fixed InlineImages support, now also for InterWiki Urls
1444 // * [File:my_image.gif] inlines the image,
1445 // * File:my_image.gif shows a plain inter-wiki link,
1446 // * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
1447 // * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
1449 // Revision 1.157 2004/02/09 03:58:12 rurban
1450 // for now default DB_SESSION to false
1452 // * not existing perms will now query the parent, and not
1453 // return the default perm
1454 // * added pagePermissions func which returns the object per page
1455 // * added getAccessDescription
1457 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1458 // * force init of authdbh in the 2 db classes
1460 // * fixed session handling (not triple auth request anymore)
1461 // * don't store cookie prefs with sessions
1462 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1464 // Revision 1.156 2004/01/26 09:17:49 rurban
1465 // * changed stored pref representation as before.
1466 // the array of objects is 1) bigger and 2)
1467 // less portable. If we would import packed pref
1468 // objects and the object definition was changed, PHP would fail.
1469 // This doesn't happen with an simple array of non-default values.
1470 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1471 // understands the interim format of array of objects also.
1472 // * simplified $prefs->get() and fixed $prefs->set()
1473 // * added $user->_userid and class '_WikiUser' portability functions
1474 // * fixed $user object ->_level upgrading, mostly using sessions.
1475 // this fixes yesterdays problems with loosing authorization level.
1476 // * fixed WikiUserNew::checkPass to return the _level
1477 // * fixed WikiUserNew::isSignedIn
1478 // * added explodePageList to class PageList, support sortby arg
1479 // * fixed UserPreferences for WikiUserNew
1480 // * fixed WikiPlugin for empty defaults array
1481 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1482 // removed sort arg, support sortby arg
1484 // Revision 1.155 2004/01/25 10:52:22 rurban
1485 // added sortby support to explodePageList() and UnfoldSubpages
1486 // fixes [ 758044 ] Plugin UnfoldSubpages does not sort (includes fix)
1488 // Revision 1.154 2004/01/25 03:49:03 rurban
1489 // added isWikiWord() to avoid redundancy
1490 // added check_php_version() to check for older php versions.
1491 // e.g. object::method calls, ...
1493 // Revision 1.153 2003/11/30 18:43:18 carstenklapp
1494 // Fixed careless mistakes in my last optimization commit.
1496 // Revision 1.152 2003/11/30 18:20:34 carstenklapp
1497 // Minor code optimization: reduce invariant loops
1499 // Revision 1.151 2003/11/29 19:30:01 carstenklapp
1500 // New function ByteFormatter.
1502 // Revision 1.150 2003/09/13 22:43:00 carstenklapp
1503 // New preference to hide LinkIcons.
1505 // Revision 1.149 2003/03/26 19:37:08 dairiki
1506 // Fix "object to string conversion" bug with external image links.
1508 // Revision 1.148 2003/03/25 21:03:02 dairiki
1509 // Cleanup debugging output.
1511 // Revision 1.147 2003/03/13 20:17:05 dairiki
1512 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1514 // Revision 1.146 2003/03/07 02:46:24 dairiki
1515 // function_usable(): New function.
1517 // Revision 1.145 2003/03/04 01:55:05 dairiki
1518 // Fix to ensure absolute URL for logo in RSS recent changes.
1520 // Revision 1.144 2003/02/26 00:39:30 dairiki
1521 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1522 // being displayed at incorrect times.
1524 // Revision 1.143 2003/02/26 00:10:26 dairiki
1525 // More/better/different checks for bad page names.
1527 // Revision 1.142 2003/02/25 22:19:46 dairiki
1528 // Add some sanity checking for pagenames.
1530 // Revision 1.141 2003/02/22 20:49:55 dairiki
1531 // Fixes for "Call-time pass by reference has been deprecated" errors.
1533 // Revision 1.140 2003/02/21 23:33:29 dairiki
1534 // Set alt="" on the link icon image tags.
1535 // (See SF bug #675141.)
1537 // Revision 1.139 2003/02/21 22:16:27 dairiki
1538 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1539 // These have been obsolete for quite awhile (I hope).
1541 // Revision 1.138 2003/02/21 04:12:36 dairiki
1542 // WikiPageName: fixes for new cached links.
1544 // Alert: new class for displaying alerts.
1546 // ExtractWikiPageLinks and friends are now gone.
1548 // LinkBracketLink moved to InlineParser.php
1550 // Revision 1.137 2003/02/18 23:13:40 dairiki
1551 // Wups again. Typo fix.
1553 // Revision 1.136 2003/02/18 21:52:07 dairiki
1554 // Fix so that one can still link to wiki pages with # in their names.
1555 // (This was made difficult by the introduction of named tags, since
1556 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1558 // Now the ~ escape for page names should work: [Page ~#1].
1560 // Revision 1.135 2003/02/18 19:17:04 dairiki
1561 // split_pagename():
1562 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1563 // Cleanup up subpage splitting code.
1565 // Revision 1.134 2003/02/16 19:44:20 dairiki
1566 // New function hash(). This is a helper, primarily for generating
1569 // Revision 1.133 2003/02/16 04:50:09 dairiki
1571 // Rfc1123DateTime(), ParseRfc1123DateTime()
1572 // for converting unix timestamps to and from strings.
1574 // These functions produce and grok the time strings
1575 // in the format specified by RFC 2616 for use in HTTP headers
1576 // (like Last-Modified).
1578 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1579 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1580 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1583 // (c-file-style: "gnu")
1587 // c-basic-offset: 4
1588 // c-hanging-comment-ender-p: nil
1589 // indent-tabs-mode: nil