1 <?php //rcs_id('$Id: stdlib.php,v 1.173 2004-05-03 15:00:31 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')) . '.'",
76 function UnMangleXmlIdentifier($str) {
79 return preg_replace('/x(\w\w)\./e',
80 "sprintf('%c', hex('\\0'))",
85 * Generates a valid URL for a given Wiki pagename.
86 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
87 * If a WikiDB_Page object function will extract the name to link to.
88 * If a WikiDB_PageRevision object function will extract the name to link to.
90 * @param boolean $get_abs_url Default value is false.
91 * @return string The absolute URL to the page passed as $pagename.
93 function WikiURL($pagename, $args = '', $get_abs_url = false) {
96 if (is_object($pagename)) {
97 if (isa($pagename, 'WikiDB_Page')) {
98 $pagename = $pagename->getName();
100 elseif (isa($pagename, 'WikiDB_PageRevision')) {
101 $page = $pagename->getPage();
102 $args['version'] = $pagename->getVersion();
103 $pagename = $page->getName();
105 elseif (isa($pagename, 'WikiPageName')) {
106 $anchor = $pagename->anchor;
107 $pagename = $pagename->name;
109 $anchor = $pagename->anchor;
110 $pagename = $pagename->name;
114 if (is_array($args)) {
116 foreach ($args as $key => $val) {
117 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
118 $enc_args[] = urlencode($key) . '=' . urlencode($val);
120 $args = join('&', $enc_args);
124 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
125 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
130 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
131 $url .= "?pagename=" . rawurlencode($pagename);
136 $url .= "#" . MangleXmlIdentifier($anchor);
140 /** Convert relative URL to absolute URL.
142 * This converts a relative URL to one of PhpWiki's support files
143 * to an absolute one.
146 * @return string Absolute URL
148 function AbsoluteURL ($url) {
149 if (preg_match('/^https?:/', $url))
151 if ($url[0] != '/') {
152 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
153 while ($base != '/' and substr($url, 0, 3) == "../") {
154 $url = substr($url, 3);
155 $base = dirname($base);
161 return SERVER_URL . $url;
165 * Generates icon in front of links.
167 * @param string $protocol_or_url URL or protocol to determine which icon to use.
169 * @return HtmlElement HtmlElement object that contains data to create img link to
170 * icon for use with url or protocol passed to the function. False if no img to be
173 function IconForLink($protocol_or_url) {
175 if (0 and $filename_suffix == false) {
176 // display apache style icon for file type instead of protocol icon
177 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
178 // - document: html, htm, text, txt, rtf, pdf, doc
179 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
180 // - audio: mp3,mp2,aiff,aif,au
181 // - multimedia: mpeg,mpg,mov,qt
183 list ($proto) = explode(':', $protocol_or_url, 2);
184 $src = $Theme->getLinkIconURL($proto);
186 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
193 * Glue icon in front of text.
195 * @param string $protocol_or_url Protocol or URL. Used to determine the
197 * @param string $text The text.
198 * @return XmlContent.
200 function PossiblyGlueIconToText($proto_or_url, $text) {
202 if (! $request->getPref('noLinkIcons')) {
203 $icon = IconForLink($proto_or_url);
205 if (!is_object($text)) {
206 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
207 list (, $first_word, $tail) = $m;
214 $text = HTML::span(array('style' => 'white-space: nowrap'),
217 $text = HTML($text, $tail);
224 * Determines if the url passed to function is safe, by detecting if the characters
225 * '<', '>', or '"' are present.
227 * @param string $url URL to check for unsafe characters.
228 * @return boolean True if same, false else.
230 function IsSafeURL($url) {
231 return !ereg('[<>"]', $url);
235 * Generates an HtmlElement object to store data for a link.
237 * @param string $url URL that the link will point to.
238 * @param string $linktext Text to be displayed as link.
239 * @return HtmlElement HtmlElement object that contains data to construct an html link.
241 function LinkURL($url, $linktext = '') {
242 // FIXME: Is this needed (or sufficient?)
243 if(! IsSafeURL($url)) {
244 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
245 _("BAD URL -- remove all of <, >, \"")));
249 $linktext = preg_replace("/mailto:/A", "", $url);
251 $link = HTML::a(array('href' => $url),
252 PossiblyGlueIconToText($url, $linktext));
255 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
260 function LinkImage($url, $alt = false) {
261 // FIXME: Is this needed (or sufficient?)
262 if(! IsSafeURL($url)) {
263 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
264 _("BAD URL -- remove all of <, >, \"")));
269 $link = HTML::img(array('src' => $url, 'alt' => $alt));
271 $link->setAttr('class', 'inlineimage');
278 var $items = array();
280 // var in php5.0.0.rc1 deprecated
282 function push($item) {
283 $this->items[$this->size] = $item;
289 if ($this->size == 0) {
290 return false; // stack is empty
293 return $this->items[$this->size];
302 return $this->items[$this->size - 1];
308 // end class definition
310 function SplitQueryArgs ($query_args = '')
312 $split_args = split('&', $query_args);
314 while (list($key, $val) = each($split_args))
315 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
316 $args[$m[1]] = $m[2];
320 function LinkPhpwikiURL($url, $text = '', $basepage) {
323 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
324 return HTML::strong(array('class' => 'rawurl'),
325 HTML::u(array('class' => 'baduri'),
326 _("BAD phpwiki: URL")));
330 $pagename = urldecode($m[1]);
333 if (empty($pagename) &&
334 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
335 // Convert old style links (to not break diff links in
337 $pagename = urldecode($m[2]);
338 $args = array("action" => $m[1]);
341 $args = SplitQueryArgs($qargs);
344 if (empty($pagename))
345 $pagename = $GLOBALS['request']->getArg('pagename');
347 if (isset($args['action']) && $args['action'] == 'browse')
348 unset($args['action']);
351 if (empty($args['action']))
353 else if (is_safe_action($args['action']))
354 $class = 'wikiaction';
356 if (empty($args['action']) || is_safe_action($args['action']))
357 $class = 'wikiaction';
359 // Don't allow administrative links on unlocked pages.
360 $dbi = $GLOBALS['request']->getDbh();
361 $page = $dbi->getPage($basepage);
362 if (!$page->get('locked'))
363 return HTML::span(array('class' => 'wikiunsafe'),
364 HTML::u(_("Lock page to enable link")));
365 $class = 'wikiadmin';
369 $text = HTML::span(array('class' => 'rawurl'), $url);
371 $wikipage = new WikiPageName($pagename);
372 if (!$wikipage->isValid()) {
374 return $Theme->linkBadWikiWord($wikipage, $url);
377 return HTML::a(array('href' => WikiURL($pagename, $args),
383 * A class to assist in parsing wiki pagenames.
385 * Now with subpages and anchors, parsing and passing around
386 * pagenames is more complicated. This should help.
390 /** Short name for page.
392 * This is the value of $name passed to the constructor.
393 * (For use, e.g. as a default label for links to the page.)
397 /** The full page name.
399 * This is the full name of the page (without anchor).
405 * This is the referenced anchor within the page, or the empty string.
411 * @param mixed $name Page name.
412 * WikiDB_Page, WikiDB_PageRevision, or string.
413 * This can be a relative subpage name (like '/SubPage'),
414 * or can be the empty string to refer to the $basename.
416 * @param string $anchor For links to anchors in page.
418 * @param mixed $basename Page name from which to interpret
419 * relative or other non-fully-specified page names.
421 function WikiPageName($name, $basename=false, $anchor=false) {
422 if (is_string($name)) {
423 $this->shortName = $name;
425 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
427 $name = $this->_pagename($basename) . $name;
429 $name = $this->_normalize_bad_pagename($name);
433 $name = $this->_pagename($name);
434 $this->shortName = $name;
437 $this->name = $this->_check($name);
438 $this->anchor = (string)$anchor;
441 function getParent() {
443 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
445 return substr($name, 0, -strlen($tail));
448 function isValid($strict = false) {
450 return !isset($this->_errors);
451 return !empty($this->name);
454 function getWarnings() {
456 if (isset($this->_warnings))
457 $warnings = array_merge($warnings, $this->_warnings);
458 if (isset($this->_errors))
459 $warnings = array_merge($warnings, $this->_errors);
463 return sprintf(_("'%s': Bad page name: %s"),
464 $this->shortName, join(', ', $warnings));
467 function _pagename($page) {
468 if (isa($page, 'WikiDB_Page'))
469 return $page->getName();
470 elseif (isa($page, 'WikiDB_PageRevision'))
471 return $page->getPageName();
472 elseif (isa($page, 'WikiPageName'))
474 if (!is_string($page)) {
475 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
476 $page, gettype($page), get_class($page)),
479 //assert(is_string($page));
483 function _normalize_bad_pagename($name) {
484 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
486 // Punt... You really shouldn't get here.
489 return $request->getArg('pagename');
491 assert($name[0] == SUBPAGE_SEPARATOR);
492 return substr($name, 1);
496 function _check($pagename) {
497 // Compress internal white-space to single space character.
498 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
499 if ($pagename != $orig)
500 $this->_warnings[] = _("White space converted to single space");
502 // Delete any control characters.
503 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
504 if ($pagename != $orig)
505 $this->_errors[] = _("Control characters not allowed");
507 // Strip leading and trailing white-space.
508 $pagename = trim($pagename);
511 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
512 $pagename = substr($pagename, 1);
513 if ($pagename != $orig)
514 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
516 if (preg_match('/[:;]/', $pagename))
517 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
519 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
520 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
521 $this->_errors[] = _("too long");
525 if ($pagename == '.' or $pagename == '..') {
526 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
535 * Convert old page markup to new-style markup.
537 * @param string $text Old-style wiki markup.
539 * @param string $markup_type
541 * <dt><code>"block"</code> <dd>Convert all markup.
542 * <dt><code>"inline"</code> <dd>Convert only inline markup.
543 * <dt><code>"links"</code> <dd>Convert only link markup.
546 * @return string New-style wiki markup.
548 * @bugs Footnotes don't work quite as before (esp if there are
549 * multiple references to the same footnote. But close enough,
550 * probably for now....
552 function ConvertOldMarkup ($text, $markup_type = "block") {
558 /*****************************************************************
559 * Conversions for inline markup:
566 // escape escaped brackets
570 // change ! escapes to ~'s.
571 global $WikiNameRegexp, $request;
572 //include_once('lib/interwiki.php');
573 $map = getInterwikiMap();
574 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
575 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
576 $bang_esc[] = $WikiNameRegexp;
577 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
580 $subs["links"] = array($orig, $repl);
583 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
586 // Convert footnote references.
587 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
588 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
590 // Convert old style emphases to HTML style emphasis.
591 $orig[] = '/__(.*?)__/';
592 $repl[] = '<strong>\\1</strong>';
593 $orig[] = "/''(.*?)''/";
594 $repl[] = '<em>\\1</em>';
596 // Escape nestled markup.
597 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
600 // in old markup headings only allowed at beginning of line
604 $subs["inline"] = array($orig, $repl);
606 /*****************************************************************
607 * Patterns which match block markup constructs which take
608 * special handling...
612 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
615 $blockpats[] = '\|(?:.*\n\|)*';
618 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
620 // Footnote definitions
621 $blockpats[] = '\[\s*(\d+)\s*\]';
624 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
627 $blockpats[] = '!{1,3}[^!]';
629 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
630 . join("|", $blockpats)
635 if ($markup_type != "block") {
636 list ($orig, $repl) = $subs[$markup_type];
637 return preg_replace($orig, $repl, $text);
640 list ($orig, $repl) = $subs['inline'];
642 while (preg_match($block_re, $text, $m)) {
643 $text = substr($text, strlen($m[0]));
644 list (,$leading_text, $block) = $m;
647 if (strchr(" \t", $block[0])) {
650 $suffix = "\n</pre>\n";
652 elseif ($block[0] == '|') {
654 $prefix = "<?plugin OldStyleTable\n";
657 elseif (strchr("#*;", $block[0])) {
658 // Old-style list item
659 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
660 list (,$ind,$bullet) = $m;
661 $block = substr($block, strlen($m[0]));
663 $indent = str_repeat(' ', strlen($ind));
664 if ($bullet[0] == ';') {
665 //$term = ltrim(substr($bullet, 1));
666 //return $indent . $term . "\n" . $indent . ' ';
667 $prefix = $ind . $bullet;
670 $prefix = $indent . $bullet . ' ';
672 elseif ($block[0] == '[') {
673 // Footnote definition
674 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
676 $block = substr($block, strlen($m[0]));
677 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
679 elseif ($block[0] == '<') {
681 // HACK: no inline markup...
685 elseif ($block[0] == '!') {
687 preg_match('/^!{1,3}/', $block, $m);
689 $block = substr($block, strlen($m[0]));
696 $out .= ( preg_replace($orig, $repl, $leading_text)
698 . preg_replace($orig, $repl, $block)
701 return $out . preg_replace($orig, $repl, $text);
707 * Expand tabs in string.
709 * Converts all tabs to (the appropriate number of) spaces.
712 * @param integer $tab_width
715 function expand_tabs($str, $tab_width = 8) {
716 $split = split("\t", $str);
717 $tail = array_pop($split);
719 foreach ($split as $hunk) {
721 $pos = strlen(strrchr($expanded, "\n")) - 1;
722 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
724 return substr($expanded, 1) . $tail;
728 * Split WikiWords in page names.
730 * It has been deemed useful to split WikiWords (into "Wiki Words") in
731 * places like page titles. This is rumored to help search engines
734 * @param $page string The page name.
736 * @return string The split name.
738 function split_pagename ($page) {
740 if (preg_match("/\s/", $page))
741 return $page; // Already split --- don't split any more.
743 // FIXME: this algorithm is Anglo-centric.
746 // This mess splits between a lower-case letter followed by
747 // either an upper-case or a numeral; except that it wont
748 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
749 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
750 // This the single-letter words 'I' and 'A' from any following
751 // capitalized words.
752 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
753 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
754 // Split numerals from following letters.
755 $RE[] = '/(\d)([[:alpha:]])/';
756 //TODO: Split at subpage seperators. TBD in Theme.php
757 //$RE[] = "/(${sep})([^${sep}]+)/";
759 foreach ($RE as $key)
760 $RE[$key] = pcre_fix_posix_classes($key);
763 foreach ($RE as $regexp) {
764 $page = preg_replace($regexp, '\\1 \\2', $page);
769 function NoSuchRevision (&$request, $page, $version) {
770 $html = HTML(HTML::h2(_("Revision Not Found")),
771 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
772 $version, WikiLink($page, 'auto'))));
773 include_once('lib/Template.php');
774 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
780 * Get time offset for local time zone.
782 * @param $time time_t Get offset for this time. Default: now.
783 * @param $no_colon boolean Don't put colon between hours and minutes.
784 * @return string Offset as a string in the format +HH:MM.
786 function TimezoneOffset ($time = false, $no_colon = false) {
789 $secs = date('Z', $time);
798 $colon = $no_colon ? '' : ':';
799 $mins = intval(($secs + 30) / 60);
800 return sprintf("%s%02d%s%02d",
801 $sign, $mins / 60, $colon, $mins % 60);
806 * Format time in ISO-8601 format.
808 * @param $time time_t Time. Default: now.
809 * @return string Date and time in ISO-8601 format.
811 function Iso8601DateTime ($time = false) {
814 $tzoff = TimezoneOffset($time);
815 $date = date('Y-m-d', $time);
816 $time = date('H:i:s', $time);
817 return $date . 'T' . $time . $tzoff;
821 * Format time in RFC-2822 format.
823 * @param $time time_t Time. Default: now.
824 * @return string Date and time in RFC-2822 format.
826 function Rfc2822DateTime ($time = false) {
829 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
833 * Format time in RFC-1123 format.
835 * @param $time time_t Time. Default: now.
836 * @return string Date and time in RFC-1123 format.
838 function Rfc1123DateTime ($time = false) {
841 return gmdate('D, d M Y H:i:s \G\M\T', $time);
844 /** Parse date in RFC-1123 format.
846 * According to RFC 1123 we must accept dates in the following
849 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
850 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
851 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
853 * (Though we're only allowed to generate dates in the first format.)
855 function ParseRfc1123DateTime ($timestr) {
856 $timestr = trim($timestr);
857 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
858 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
860 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
862 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
863 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
865 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
866 if ($year < 70) $year += 2000;
867 elseif ($year < 100) $year += 1900;
869 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
870 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
872 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
879 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
881 return false; // failed
886 * Format time to standard 'ctime' format.
888 * @param $time time_t Time. Default: now.
889 * @return string Date and time.
891 function CTime ($time = false)
895 return date("D M j H:i:s Y", $time);
900 * Format number as kilobytes or bytes.
901 * Short format is used for PageList
902 * Long format is used in PageInfo
904 * @param $bytes int. Default: 0.
905 * @param $longformat bool. Default: false.
906 * @return class FormattedText (XmlElement.php).
908 function ByteFormatter ($bytes = 0, $longformat = false) {
913 $size = fmt("%s b", $bytes);
915 $size = fmt("%s bytes", $bytes);
918 $kb = round($bytes / 1024, 1);
920 $size = fmt("%s k", $kb);
922 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
928 * Internationalized printf.
930 * This is essentially the same as PHP's built-in printf
931 * with the following exceptions:
933 * <li> It passes the format string through gettext().
934 * <li> It supports the argument reordering extensions.
941 * __printf("Differences between versions %s and %s of %s",
942 * $new_link, $old_link, $page_link);
945 * Then in locale/po/de.po, one can reorder the printf arguments:
948 * msgid "Differences between %s and %s of %s."
949 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
952 * (Note that while PHP tries to expand $vars within double-quotes,
953 * the values in msgstr undergo no such expansion, so the '$'s
956 * One shouldn't use reordered arguments in the default format string.
957 * Backslashes in the default string would be necessary to escape the
958 * '$'s, and they'll cause all kinds of trouble....
960 function __printf ($fmt) {
961 $args = func_get_args();
963 echo __vsprintf($fmt, $args);
967 * Internationalized sprintf.
969 * This is essentially the same as PHP's built-in printf with the
970 * following exceptions:
973 * <li> It passes the format string through gettext().
974 * <li> It supports the argument reordering extensions.
979 function __sprintf ($fmt) {
980 $args = func_get_args();
982 return __vsprintf($fmt, $args);
986 * Internationalized vsprintf.
988 * This is essentially the same as PHP's built-in printf with the
989 * following exceptions:
992 * <li> It passes the format string through gettext().
993 * <li> It supports the argument reordering extensions.
998 function __vsprintf ($fmt, $args) {
999 $fmt = gettext($fmt);
1000 // PHP's sprintf doesn't support variable with specifiers,
1001 // like sprintf("%*s", 10, "x"); --- so we won't either.
1003 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1004 // Format string has '%2$s' style argument reordering.
1005 // PHP doesn't support this.
1006 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1007 // literal variable name substitution only to keep locale
1008 // strings uncluttered
1009 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1010 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1012 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1015 // Reorder arguments appropriately.
1016 foreach($m[1] as $argnum) {
1017 if ($argnum < 1 || $argnum > count($args))
1018 trigger_error(sprintf(_("%s: argument index out of range"),
1019 $argnum), E_USER_WARNING);
1020 $newargs[] = $args[$argnum - 1];
1025 // Not all PHP's have vsprintf, so...
1026 array_unshift($args, $fmt);
1027 return call_user_func_array('sprintf', $args);
1030 function file_mtime ($filename) {
1031 if ($stat = stat($filename))
1037 function sort_file_mtime ($a, $b) {
1038 $ma = file_mtime($a);
1039 $mb = file_mtime($b);
1040 if (!$ma or !$mb or $ma == $mb) return 0;
1041 return ($ma > $mb) ? -1 : 1;
1046 * Build an array in $this->_fileList of files from $dirname.
1047 * Subdirectories are not traversed.
1049 * (This was a function LoadDir in lib/loadsave.php)
1050 * See also http://www.php.net/manual/en/function.readdir.php
1052 function getFiles($exclude=false,$sortby=false,$limit=false) {
1053 $list = $this->_fileList;
1055 switch (Pagelist::sortby($sortby,'db')) {
1056 case 'pagename ASC': break;
1057 case 'pagename DESC':
1058 $list = array_reverse($list);
1061 usort($list,'sort_file_mtime');
1064 usort($list,'sort_file_mtime');
1065 $list = array_reverse($list);
1070 return array_splice($list,0,$limit);
1074 function _filenameSelector($filename) {
1075 if (! $this->_pattern)
1078 return glob_match ($this->_pattern, $filename, $this->_case);
1082 function fileSet($directory, $filepattern = false) {
1083 $this->_fileList = array();
1084 $this->_pattern = $filepattern;
1085 $this->_case = !isWindows();
1086 $this->_pathsep = '/';
1088 if (empty($directory)) {
1089 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1091 return; // early return
1094 @ $dir_handle = opendir($dir=$directory);
1095 if (empty($dir_handle)) {
1096 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1097 $dir), E_USER_NOTICE);
1098 return; // early return
1101 while ($filename = readdir($dir_handle)) {
1102 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1104 if ($this->_filenameSelector($filename)) {
1105 array_push($this->_fileList, "$filename");
1106 //trigger_error(sprintf(_("found file %s"), $filename),
1107 // E_USER_NOTICE); //debugging
1110 closedir($dir_handle);
1116 // expands a list containing regex's to its matching entries
1117 class ListRegexExpand {
1118 var $match, $list, $index, $case_sensitive;
1119 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1120 $this->match = str_replace('/','\/',$match);
1121 $this->list = &$list;
1122 $this->case_sensitive = $case_sensitive;
1123 //$this->index = false;
1125 function listMatchCallback ($item, $key) {
1126 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1127 unset($this->list[$this->index]);
1128 $this->list[] = $item;
1131 function expandRegex ($index, &$pages) {
1132 $this->index = $index;
1133 array_walk($pages, array($this, 'listMatchCallback'));
1138 // convert fileglob to regex style
1139 function glob_to_pcre ($glob) {
1140 $re = preg_replace('/\./', '\\.', $glob);
1141 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1142 if (!preg_match('/^[\?\*]/',$glob))
1144 if (!preg_match('/[\?\*]$/',$glob))
1149 function glob_match ($glob, $against, $case_sensitive = true) {
1150 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1153 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1154 $list = explode(',',$input);
1155 // expand wildcards from list of $allnames
1156 if (preg_match('/[\?\*]/',$input)) {
1157 // Optimizing loop invariants:
1158 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1159 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1161 if (preg_match('/[\?\*]/',$f)) {
1163 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1164 $expand->expandRegex($i, $allnames);
1171 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1172 function explodePageList($input, $perm=false, $sortby='pagename', $limit=false) {
1173 include_once("lib/PageList.php");
1174 return PageList::explodePageList($input,$perm,$sortby,$limit);
1177 // Class introspections
1179 /** Determine whether object is of a specified type.
1181 * @param $object object An object.
1182 * @param $class string Class name.
1183 * @return bool True iff $object is a $class
1184 * or a sub-type of $class.
1186 function isa ($object, $class) {
1187 $lclass = strtolower($class);
1189 return is_object($object)
1190 && ( get_class($object) == strtolower($lclass)
1191 || is_subclass_of($object, $lclass) );
1194 /** Determine whether (possible) object has method.
1196 * @param $object mixed Object
1197 * @param $method string Method name
1198 * @return bool True iff $object is an object with has method $method.
1200 function can ($object, $method) {
1201 return is_object($object) && method_exists($object, strtolower($method));
1204 /** Determine whether a function is okay to use.
1206 * Some providers (e.g. Lycos) disable some of PHP functions for
1207 * "security reasons." This makes those functions, of course,
1208 * unusable, despite the fact the function_exists() says they
1211 * This function test to see if a function exists and is not
1212 * disallowed by PHP's disable_functions config setting.
1214 * @param string $function_name Function name
1215 * @return bool True iff function can be used.
1217 function function_usable($function_name) {
1219 if (!is_array($disabled)) {
1220 $disabled = array();
1221 // Use get_cfg_var since ini_get() is one of the disabled functions
1222 // (on Lycos, at least.)
1223 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1224 foreach ($split as $f)
1225 $disabled[strtolower($f)] = true;
1228 return ( function_exists($function_name)
1229 and ! isset($disabled[strtolower($function_name)])
1236 * This is used for generating ETags.
1238 function hash ($x) {
1239 if (is_scalar($x)) {
1242 elseif (is_array($x)) {
1244 return md5(serialize($x));
1246 elseif (is_object($x)) {
1249 trigger_error("Can't hash $x", E_USER_ERROR);
1254 * Seed the random number generator.
1256 * better_srand() ensures the randomizer is seeded only once.
1258 * How random do you want it? See:
1259 * http://www.php.net/manual/en/function.srand.php
1260 * http://www.php.net/manual/en/function.mt-srand.php
1262 function better_srand($seed = '') {
1263 static $wascalled = FALSE;
1265 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1268 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1273 * Recursively count all non-empty elements
1274 * in array of any dimension or mixed - i.e.
1275 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1276 * See http://www.php.net/manual/en/function.count.php
1278 function count_all($arg) {
1279 // skip if argument is empty
1281 //print_r($arg); //debugging
1283 // not an array, return 1 (base case)
1286 // else call recursively for all elements $arg
1287 foreach($arg as $key => $val)
1288 $count += count_all($val);
1293 function isSubPage($pagename) {
1294 return (strstr($pagename, SUBPAGE_SEPARATOR));
1297 function subPageSlice($pagename, $pos) {
1298 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1299 $pages = array_slice($pages,$pos,1);
1306 * Class for "popping up" and alert box. (Except that right now, it doesn't
1310 * This is a hackish and needs to be refactored. However it would be nice to
1311 * unify all the different methods we use for showing Alerts and Dialogs.
1312 * (E.g. "Page deleted", login form, ...)
1317 * @param object $request
1318 * @param mixed $head Header ("title") for alert box.
1319 * @param mixed $body The text in the alert box.
1320 * @param hash $buttons An array mapping button labels to URLs.
1321 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1323 function Alert($head, $body, $buttons=false) {
1324 if ($buttons === false)
1327 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1328 $this->_buttons = $buttons;
1332 * Show the alert box.
1334 function show(&$request) {
1337 $tokens = $this->_tokens;
1338 $tokens['BUTTONS'] = $this->_getButtons();
1340 $request->discardOutput();
1341 $tmpl = new Template('dialog', $request, $tokens);
1347 function _getButtons() {
1350 $buttons = $this->_buttons;
1352 $buttons = array(_("Okay") => $request->getURLtoSelf());
1355 foreach ($buttons as $label => $url)
1356 print "$label $url\n";
1357 $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1358 return new XmlContent($out);
1363 * Returns true if current php version is at mimimum a.b.c
1364 * Called: check_php_version(4,1)
1366 function check_php_version ($a = '0', $b = '0', $c = '0') {
1367 global $PHP_VERSION;
1368 if(!isset($PHP_VERSION))
1369 $PHP_VERSION = substr( str_pad( preg_replace('/\D/','', PHP_VERSION), 3, '0'), 0, 3);
1370 return $PHP_VERSION >= ($a.$b.$c);
1372 // 1.3.10pre => 1030.10
1374 function phpwiki_version() {
1375 static $PHPWIKI_VERSION;
1376 if(!isset($PHPWIKI_VERSION)) {
1377 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION));
1378 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1380 return $PHPWIKI_VERSION;
1383 function isWikiWord($word) {
1384 global $WikiNameRegexp;
1385 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1386 return preg_match("/^$WikiNameRegexp\$/",$word);
1389 // needed to store serialized objects-values only (perm, pref)
1390 function obj2hash ($obj, $exclude = false, $fields = false) {
1392 if (! $fields ) $fields = get_object_vars($obj);
1393 foreach ($fields as $key => $val) {
1394 if (is_array($exclude)) {
1395 if (in_array($key,$exclude)) continue;
1402 // $Log: not supported by cvs2svn $
1403 // Revision 1.172 2004/04/26 20:44:34 rurban
1404 // locking table specific for better databases
1406 // Revision 1.171 2004/04/19 23:13:03 zorloc
1407 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
1409 // Revision 1.170 2004/04/19 18:27:45 rurban
1410 // Prevent from some PHP5 warnings (ref args, no :: object init)
1411 // php5 runs now through, just one wrong XmlElement object init missing
1412 // Removed unneccesary UpgradeUser lines
1413 // Changed WikiLink to omit version if current (RecentChanges)
1415 // Revision 1.169 2004/04/15 21:29:48 rurban
1416 // allow [0] with new markup: link to page "0"
1418 // Revision 1.168 2004/04/10 02:30:49 rurban
1419 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
1420 // Fixed "cannot setlocale..." (sf.net problem)
1422 // Revision 1.167 2004/04/02 15:06:55 rurban
1423 // fixed a nasty ADODB_mysql session update bug
1424 // improved UserPreferences layout (tabled hints)
1425 // fixed UserPreferences auth handling
1426 // improved auth stability
1427 // improved old cookie handling: fixed deletion of old cookies with paths
1429 // Revision 1.166 2004/04/01 15:57:10 rurban
1430 // simplified Sidebar theme: table, not absolute css positioning
1431 // added the new box methods.
1432 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
1434 // Revision 1.165 2004/03/24 19:39:03 rurban
1435 // php5 workaround code (plus some interim debugging code in XmlElement)
1436 // php5 doesn't work yet with the current XmlElement class constructors,
1437 // WikiUserNew does work better than php4.
1438 // rewrote WikiUserNew user upgrading to ease php5 update
1439 // fixed pref handling in WikiUserNew
1440 // added Email Notification
1441 // added simple Email verification
1442 // removed emailVerify userpref subclass: just a email property
1443 // changed pref binary storage layout: numarray => hash of non default values
1444 // print optimize message only if really done.
1445 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1446 // prefs should be stored in db or homepage, besides the current session.
1448 // Revision 1.164 2004/03/18 21:41:09 rurban
1449 // fixed sqlite support
1450 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
1452 // Revision 1.163 2004/03/17 18:41:49 rurban
1453 // just reformatting
1455 // Revision 1.162 2004/03/16 15:43:08 rurban
1456 // make fileSet sortable to please PageList
1458 // Revision 1.161 2004/03/12 15:48:07 rurban
1459 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1460 // simplified lib/stdlib.php:explodePageList
1462 // Revision 1.160 2004/02/28 21:14:08 rurban
1463 // generally more PHPDOC docs
1464 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
1465 // fxied WikiUserNew pref handling: empty theme not stored, save only
1466 // changed prefs, sql prefs improved, fixed password update,
1467 // removed REPLACE sql (dangerous)
1468 // moved gettext init after the locale was guessed
1469 // + some minor changes
1471 // Revision 1.158 2004/02/19 21:54:17 rurban
1472 // moved initerwiki code to PageType.php
1473 // re-enabled and fixed InlineImages support, now also for InterWiki Urls
1474 // * [File:my_image.gif] inlines the image,
1475 // * File:my_image.gif shows a plain inter-wiki link,
1476 // * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
1477 // * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
1479 // Revision 1.157 2004/02/09 03:58:12 rurban
1480 // for now default DB_SESSION to false
1482 // * not existing perms will now query the parent, and not
1483 // return the default perm
1484 // * added pagePermissions func which returns the object per page
1485 // * added getAccessDescription
1487 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1488 // * force init of authdbh in the 2 db classes
1490 // * fixed session handling (not triple auth request anymore)
1491 // * don't store cookie prefs with sessions
1492 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1494 // Revision 1.156 2004/01/26 09:17:49 rurban
1495 // * changed stored pref representation as before.
1496 // the array of objects is 1) bigger and 2)
1497 // less portable. If we would import packed pref
1498 // objects and the object definition was changed, PHP would fail.
1499 // This doesn't happen with an simple array of non-default values.
1500 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1501 // understands the interim format of array of objects also.
1502 // * simplified $prefs->get() and fixed $prefs->set()
1503 // * added $user->_userid and class '_WikiUser' portability functions
1504 // * fixed $user object ->_level upgrading, mostly using sessions.
1505 // this fixes yesterdays problems with loosing authorization level.
1506 // * fixed WikiUserNew::checkPass to return the _level
1507 // * fixed WikiUserNew::isSignedIn
1508 // * added explodePageList to class PageList, support sortby arg
1509 // * fixed UserPreferences for WikiUserNew
1510 // * fixed WikiPlugin for empty defaults array
1511 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1512 // removed sort arg, support sortby arg
1514 // Revision 1.155 2004/01/25 10:52:22 rurban
1515 // added sortby support to explodePageList() and UnfoldSubpages
1516 // fixes [ 758044 ] Plugin UnfoldSubpages does not sort (includes fix)
1518 // Revision 1.154 2004/01/25 03:49:03 rurban
1519 // added isWikiWord() to avoid redundancy
1520 // added check_php_version() to check for older php versions.
1521 // e.g. object::method calls, ...
1523 // Revision 1.153 2003/11/30 18:43:18 carstenklapp
1524 // Fixed careless mistakes in my last optimization commit.
1526 // Revision 1.152 2003/11/30 18:20:34 carstenklapp
1527 // Minor code optimization: reduce invariant loops
1529 // Revision 1.151 2003/11/29 19:30:01 carstenklapp
1530 // New function ByteFormatter.
1532 // Revision 1.150 2003/09/13 22:43:00 carstenklapp
1533 // New preference to hide LinkIcons.
1535 // Revision 1.149 2003/03/26 19:37:08 dairiki
1536 // Fix "object to string conversion" bug with external image links.
1538 // Revision 1.148 2003/03/25 21:03:02 dairiki
1539 // Cleanup debugging output.
1541 // Revision 1.147 2003/03/13 20:17:05 dairiki
1542 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1544 // Revision 1.146 2003/03/07 02:46:24 dairiki
1545 // function_usable(): New function.
1547 // Revision 1.145 2003/03/04 01:55:05 dairiki
1548 // Fix to ensure absolute URL for logo in RSS recent changes.
1550 // Revision 1.144 2003/02/26 00:39:30 dairiki
1551 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1552 // being displayed at incorrect times.
1554 // Revision 1.143 2003/02/26 00:10:26 dairiki
1555 // More/better/different checks for bad page names.
1557 // Revision 1.142 2003/02/25 22:19:46 dairiki
1558 // Add some sanity checking for pagenames.
1560 // Revision 1.141 2003/02/22 20:49:55 dairiki
1561 // Fixes for "Call-time pass by reference has been deprecated" errors.
1563 // Revision 1.140 2003/02/21 23:33:29 dairiki
1564 // Set alt="" on the link icon image tags.
1565 // (See SF bug #675141.)
1567 // Revision 1.139 2003/02/21 22:16:27 dairiki
1568 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1569 // These have been obsolete for quite awhile (I hope).
1571 // Revision 1.138 2003/02/21 04:12:36 dairiki
1572 // WikiPageName: fixes for new cached links.
1574 // Alert: new class for displaying alerts.
1576 // ExtractWikiPageLinks and friends are now gone.
1578 // LinkBracketLink moved to InlineParser.php
1580 // Revision 1.137 2003/02/18 23:13:40 dairiki
1581 // Wups again. Typo fix.
1583 // Revision 1.136 2003/02/18 21:52:07 dairiki
1584 // Fix so that one can still link to wiki pages with # in their names.
1585 // (This was made difficult by the introduction of named tags, since
1586 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1588 // Now the ~ escape for page names should work: [Page ~#1].
1590 // Revision 1.135 2003/02/18 19:17:04 dairiki
1591 // split_pagename():
1592 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1593 // Cleanup up subpage splitting code.
1595 // Revision 1.134 2003/02/16 19:44:20 dairiki
1596 // New function hash(). This is a helper, primarily for generating
1599 // Revision 1.133 2003/02/16 04:50:09 dairiki
1601 // Rfc1123DateTime(), ParseRfc1123DateTime()
1602 // for converting unix timestamps to and from strings.
1604 // These functions produce and grok the time strings
1605 // in the format specified by RFC 2616 for use in HTTP headers
1606 // (like Last-Modified).
1608 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1609 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1610 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1613 // (c-file-style: "gnu")
1617 // c-basic-offset: 4
1618 // c-hanging-comment-ender-p: nil
1619 // indent-tabs-mode: nil