1 <?php //rcs_id('$Id: stdlib.php,v 1.133 2003-02-16 04:50:09 dairiki Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
6 IconForLink($protocol_or_url)
7 LinkURL($url, $linktext)
10 MakeWikiForm ($pagename, $args, $class, $button_text)
11 SplitQueryArgs ($query_args)
12 LinkPhpwikiURL($url, $text)
13 LinkBracketLink($bracketlink)
14 ExtractWikiPageLinks($content)
15 ConvertOldMarkup($content)
17 class Stack { push($item), pop(), cnt(), top() }
19 split_pagename ($page)
20 NoSuchRevision ($request, $page, $version)
21 TimezoneOffset ($time, $no_colon)
22 Iso8601DateTime ($time)
23 Rfc2822DateTime ($time)
27 __vsprintf ($fmt, $args)
28 better_srand($seed = '')
31 subPageSlice($pagename, $pos)
32 explodePageList($input, $perm = false)
34 function: LinkInterWikiLink($link, $linktext)
35 moved to: lib/interwiki.php
36 function: linkExistingWikiWord($wikiword, $linktext, $version)
37 moved to: lib/Theme.php
38 function: LinkUnknownWikiWord($wikiword, $linktext)
39 moved to: lib/Theme.php
40 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
41 gone see: lib/plugin/RecentChanges.php
45 * Convert string to a valid XML identifier.
47 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
49 * We would like to have, e.g. named anchors within wiki pages
50 * names like "Table of Contents" --- clearly not a valid XML
51 * fragment identifier.
53 * This function implements a one-to-one map from {any string}
54 * to {valid XML identifiers}.
57 * converting all bytes not in [A-Za-z0-9:_-],
58 * and any leading byte not in [A-Za-z] to 'xbb.',
59 * where 'bb' is the hexadecimal representation of the
62 * As a special case, the empty string is converted to 'empty.'
67 function MangleXmlIdentifier($str)
72 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
73 "'x' . sprintf('%02x', ord('\\0')) . '.'",
79 * Generates a valid URL for a given Wiki pagename.
80 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
81 * If a WikiDB_Page object function will extract the name to link to.
82 * If a WikiDB_PageRevision object function will extract the name to link to.
84 * @param boolean $get_abs_url Default value is false.
85 * @return string The absolute URL to the page passed as $pagename.
87 function WikiURL($pagename, $args = '', $get_abs_url = false) {
90 if (is_object($pagename)) {
91 if (isa($pagename, 'WikiDB_Page')) {
92 $pagename = $pagename->getName();
94 elseif (isa($pagename, 'WikiDB_PageRevision')) {
95 $page = $pagename->getPage();
96 $args['version'] = $pagename->getVersion();
97 $pagename = $page->getName();
99 elseif (isa($pagename, 'WikiPageName')) {
100 $anchor = $pagename->anchor;
101 $pagename = $pagename->fullPagename;
105 if (is_array($args)) {
107 foreach ($args as $key => $val) {
108 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
109 $enc_args[] = urlencode($key) . '=' . urlencode($val);
111 $args = join('&', $enc_args);
115 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
116 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
121 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
122 $url .= "?pagename=" . rawurlencode($pagename);
127 $url .= "#" . MangleXmlIdentifier($anchor);
132 * Generates icon in front of links.
134 * @param string $protocol_or_url URL or protocol to determine which icon to use.
136 * @return HtmlElement HtmlElement object that contains data to create img link to
137 * icon for use with url or protocol passed to the function. False if no img to be
140 function IconForLink($protocol_or_url) {
142 if ($filename_suffix = false) {
143 // display apache style icon for file type instead of protocol icon
144 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
145 // - document: html, htm, text, txt, rtf, pdf, doc
146 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
147 // - audio: mp3,mp2,aiff,aif,au
148 // - multimedia: mpeg,mpg,mov,qt
150 list ($proto) = explode(':', $protocol_or_url, 2);
151 $src = $Theme->getLinkIconURL($proto);
153 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
160 * Glue icon in front of text.
162 * @param string $protocol_or_url Protocol or URL. Used to determine the
164 * @param string $text The text.
165 * @return XmlContent.
167 function PossiblyGlueIconToText($proto_or_url, $text) {
168 $icon = IconForLink($proto_or_url);
170 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
171 list (, $first_word, $tail) = $m;
172 $text = HTML::span(array('style' => 'white-space: nowrap'),
175 $text = HTML($text, $tail);
181 * Determines if the url passed to function is safe, by detecting if the characters
182 * '<', '>', or '"' are present.
184 * @param string $url URL to check for unsafe characters.
185 * @return boolean True if same, false else.
187 function IsSafeURL($url) {
188 return !ereg('[<>"]', $url);
192 * Generates an HtmlElement object to store data for a link.
194 * @param string $url URL that the link will point to.
195 * @param string $linktext Text to be displayed as link.
196 * @return HtmlElement HtmlElement object that contains data to construct an html link.
198 function LinkURL($url, $linktext = '') {
199 // FIXME: Is this needed (or sufficient?)
200 if(! IsSafeURL($url)) {
201 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
202 _("BAD URL -- remove all of <, >, \"")));
206 $linktext = preg_replace("/mailto:/A", "", $url);
208 $link = HTML::a(array('href' => $url),
209 PossiblyGlueIconToText($url, $linktext));
212 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
217 function LinkImage($url, $alt = false) {
218 // FIXME: Is this needed (or sufficient?)
219 if(! IsSafeURL($url)) {
220 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
221 _("BAD URL -- remove all of <, >, \"")));
226 $link = HTML::img(array('src' => $url, 'alt' => $alt));
228 $link->setAttr('class', 'inlineimage');
235 var $items = array();
238 function push($item) {
239 $this->items[$this->size] = $item;
245 if ($this->size == 0) {
246 return false; // stack is empty
249 return $this->items[$this->size];
258 return $this->items[$this->size - 1];
264 // end class definition
267 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
268 // HACK: so as to not completely break old PhpWikiAdministration pages.
269 trigger_error("MagicPhpWikiURL forms are no longer supported. "
270 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
273 $loader = new WikiPluginLoader;
274 @$action = (string)$args['action'];
275 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
278 function SplitQueryArgs ($query_args = '')
280 $split_args = split('&', $query_args);
282 while (list($key, $val) = each($split_args))
283 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
284 $args[$m[1]] = $m[2];
288 function LinkPhpwikiURL($url, $text = '') {
291 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
292 return HTML::strong(array('class' => 'rawurl'),
293 HTML::u(array('class' => 'baduri'),
294 _("BAD phpwiki: URL")));
298 $pagename = urldecode($m[1]);
301 if (empty($pagename) &&
302 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
303 // Convert old style links (to not break diff links in
305 $pagename = urldecode($m[2]);
306 $args = array("action" => $m[1]);
309 $args = SplitQueryArgs($qargs);
312 if (empty($pagename))
313 $pagename = $GLOBALS['request']->getArg('pagename');
315 if (isset($args['action']) && $args['action'] == 'browse')
316 unset($args['action']);
319 if (empty($args['action']))
321 else if (is_safe_action($args['action']))
322 $class = 'wikiaction';
324 if (empty($args['action']) || is_safe_action($args['action']))
325 $class = 'wikiaction';
327 // Don't allow administrative links on unlocked pages.
328 $page = $GLOBALS['request']->getPage();
329 if (!$page->get('locked'))
330 return HTML::span(array('class' => 'wikiunsafe'),
331 HTML::u(_("Lock page to enable link")));
332 $class = 'wikiadmin';
335 // FIXME: ug, don't like this
336 if (preg_match('/=\d*\(/', $qargs))
337 return MakeWikiForm($pagename, $args, $class, $text);
339 $text = HTML::span(array('class' => 'rawurl'), $url);
341 return HTML::a(array('href' => WikiURL($pagename, $args),
347 * A class to assist in parsing wiki pagenames.
349 * Now with subpages and anchors, parsing and passing around
350 * pagenames is more complicated. This should help.
354 /** Short name for page.
356 * This is the value of $name passed to the constructor.
360 /** The full page name.
362 * This is the full name of the page (without anchor).
368 * This is the referenced anchor within the page, or the empty string.
374 * @param WikiRequest $request
375 * @param string $name Page name.
376 * This can be a relative subpage name (like '/SubPage'), and can also
377 * include an anchor (e.g. 'SandBox#anchorname' or just '#anchor').
379 function WikiPageName($request, $name) {
380 $this->shortName = $name;
382 if ($name[0] == SUBPAGE_SEPARATOR or $name[0] == '#')
383 $name = $request->getArg('pagename') . $name;
385 if (strstr($name, '#')) {
386 list($this->fullPagename, $this->anchor) = split('#', $name, 2);
389 $this->fullPagename = $name;
394 $dbi = $request->getDbh();
395 $this->_exists = $dbi->isWikiPage($this->fullPagename);
399 * Determine whether page 'exists'.
401 * @return boolean True if page exists with non-default content.
404 return $this->_exists;
408 function LinkBracketLink($bracketlink) {
409 global $request, $AllowedProtocols, $InlineImages;
411 include_once("lib/interwiki.php");
412 $intermap = InterWikiMap::GetMap($request);
414 // $bracketlink will start and end with brackets; in between will
415 // be either a page name, a URL or both separated by a pipe.
417 // strip brackets and leading space
418 preg_match('/(\#?) \[\s* (?: ([^|]*?) \s* (\|) )? \s* (.+?) \s*\]/x', $bracketlink, $matches);
419 list (, $hash, $label, $bar, $link) = $matches;
421 // if label looks like a url to an image, we want an image link.
422 if (preg_match("/\\.($InlineImages)$/i", $label)) {
424 if (! preg_match("#^($AllowedProtocols):#", $imgurl)) {
425 // linkname like 'images/next.gif'.
427 $imgurl = $Theme->getImageURL($linkname);
429 $label = LinkImage($imgurl, $link);
433 // It's an anchor, not a link...
434 $id = MangleXmlIdentifier($link);
435 return HTML::a(array('name' => $id, 'id' => $id),
436 $bar ? $label : $link);
439 $wikipage = new WikiPageName($request, $link);
440 if ($wikipage->exists()) {
441 return WikiLink($wikipage, 'known', $label);
443 elseif (preg_match("#^($AllowedProtocols):#", $link)) {
444 // if it's an image, embed it; otherwise, it's a regular link
445 if (preg_match("/\\.($InlineImages)$/i", $link))
446 // no image link, just the src. see [img|link] above
447 return LinkImage($link, $label);
449 return LinkURL($link, $label);
451 elseif (preg_match("/^phpwiki:/", $link))
452 return LinkPhpwikiURL($link, $label);
453 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link))
454 return $intermap->link($link, $label);
456 return WikiLink($wikipage, 'unknown', $label);
461 * Extract internal links from wiki page.
463 * @param mixed $content The raw wiki-text, either as
464 * an array of lines or as one big string.
466 * @return array List of the names of pages linked to.
468 function ExtractWikiPageLinks($content) {
469 list ($wikilinks,) = ExtractLinks($content);
474 * Extract external links from a wiki page.
476 * @param mixed $content The raw wiki-text, either as
477 * an array of lines or as one big string.
479 * @return array List of the names of pages linked to.
481 function ExtractExternalLinks($content) {
482 list (, $urls) = ExtractLinks($content);
487 * Extract links from wiki page.
489 * FIXME: this should be done by the transform code.
491 * @param mixed $content The raw wiki-text, either as
492 * an array of lines or as one big string.
494 * @return array List of two arrays. The first contains
495 * the internal links (names of pages linked to), the second
496 * contains external URLs linked to.
498 function ExtractLinks($content) {
499 include_once('lib/interwiki.php');
500 global $request, $WikiNameRegexp, $AllowedProtocols;
502 if (is_string($content))
503 $content = explode("\n", $content);
505 $wikilinks = array();
508 foreach ($content as $line) {
509 // remove plugin code
510 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
511 // remove escaped '['
512 $line = str_replace('[[', ' ', $line);
514 $line = preg_replace('/\[\d+\]/', ' ', $line);
516 // bracket links (only type wiki-* is of interest)
517 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
519 for ($i = 0; $i < $numBracketLinks; $i++) {
520 $link = LinkBracketLink($brktlinks[0][$i]);
521 $class = $link->getAttr('class');
522 if (preg_match('/^(named-)?wiki(unknown)?$/', $class)) {
523 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
524 $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
526 $wikilinks[$brktlinks[2][$i]] = 1;
529 elseif (preg_match('/^(namedurl|rawurl|(named-)?interwiki)$/', $class)) {
530 $urls[$brktlinks[2][$i]] = 1;
532 $line = str_replace($brktlinks[0][$i], '', $line);
536 preg_match_all("/!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]/",
538 foreach ($link[0] as $url) {
539 if ($url[0] <> '!') {
542 $line = str_replace($url, '', $line);
546 $map = InterWikiMap::GetMap($request);
547 $regexp = pcre_fix_posix_classes("!?(?<![[:alnum:]])")
548 . $map->getRegexp() . ":[^\\s.,;?()]+";
549 preg_match_all("/$regexp/", $line, $link);
550 foreach ($link[0] as $interlink) {
551 if ($interlink[0] <> '!') {
552 $link = $map->link($interlink);
553 $urls[$link->getAttr('href')] = 1;
555 $line = str_replace($interlink, '', $line);
558 // BumpyText old-style wiki links
559 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
560 for ($i = 0; isset($link[0][$i]); $i++) {
561 if($link[0][$i][0] <> '!') {
562 if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
563 $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
565 $wikilinks[$link[0][$i]] = 1;
571 return array(array_keys($wikilinks), array_keys($urls));
576 * Convert old page markup to new-style markup.
578 * @param string $text Old-style wiki markup.
580 * @param string $markup_type
582 * <dt><code>"block"</code> <dd>Convert all markup.
583 * <dt><code>"inline"</code> <dd>Convert only inline markup.
584 * <dt><code>"links"</code> <dd>Convert only link markup.
587 * @return string New-style wiki markup.
589 * @bugs Footnotes don't work quite as before (esp if there are
590 * multiple references to the same footnote. But close enough,
591 * probably for now....
593 function ConvertOldMarkup ($text, $markup_type = "block") {
599 /*****************************************************************
600 * Conversions for inline markup:
607 // escape escaped brackets
611 // change ! escapes to ~'s.
612 global $AllowedProtocols, $WikiNameRegexp, $request;
613 include_once('lib/interwiki.php');
614 $map = InterWikiMap::GetMap($request);
615 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
616 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
617 $bang_esc[] = $WikiNameRegexp;
618 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
621 $subs["links"] = array($orig, $repl);
624 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
627 // Convert footnote references.
628 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
629 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
631 // Convert old style emphases to HTML style emphasis.
632 $orig[] = '/__(.*?)__/';
633 $repl[] = '<strong>\\1</strong>';
634 $orig[] = "/''(.*?)''/";
635 $repl[] = '<em>\\1</em>';
637 // Escape nestled markup.
638 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
641 // in old markup headings only allowed at beginning of line
645 $subs["inline"] = array($orig, $repl);
647 /*****************************************************************
648 * Patterns which match block markup constructs which take
649 * special handling...
653 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
656 $blockpats[] = '\|(?:.*\n\|)*';
659 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
661 // Footnote definitions
662 $blockpats[] = '\[\s*(\d+)\s*\]';
665 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
668 $blockpats[] = '!{1,3}[^!]';
670 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
671 . join("|", $blockpats)
676 if ($markup_type != "block") {
677 list ($orig, $repl) = $subs[$markup_type];
678 return preg_replace($orig, $repl, $text);
681 list ($orig, $repl) = $subs['inline'];
683 while (preg_match($block_re, $text, $m)) {
684 $text = substr($text, strlen($m[0]));
685 list (,$leading_text, $block) = $m;
688 if (strchr(" \t", $block[0])) {
691 $suffix = "\n</pre>\n";
693 elseif ($block[0] == '|') {
695 $prefix = "<?plugin OldStyleTable\n";
698 elseif (strchr("#*;", $block[0])) {
699 // Old-style list item
700 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
701 list (,$ind,$bullet) = $m;
702 $block = substr($block, strlen($m[0]));
704 $indent = str_repeat(' ', strlen($ind));
705 if ($bullet[0] == ';') {
706 //$term = ltrim(substr($bullet, 1));
707 //return $indent . $term . "\n" . $indent . ' ';
708 $prefix = $ind . $bullet;
711 $prefix = $indent . $bullet . ' ';
713 elseif ($block[0] == '[') {
714 // Footnote definition
715 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
717 $block = substr($block, strlen($m[0]));
718 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
720 elseif ($block[0] == '<') {
722 // HACK: no inline markup...
726 elseif ($block[0] == '!') {
728 preg_match('/^!{1,3}/', $block, $m);
730 $block = substr($block, strlen($m[0]));
737 $out .= ( preg_replace($orig, $repl, $leading_text)
739 . preg_replace($orig, $repl, $block)
742 return $out . preg_replace($orig, $repl, $text);
748 * Expand tabs in string.
750 * Converts all tabs to (the appropriate number of) spaces.
753 * @param integer $tab_width
756 function expand_tabs($str, $tab_width = 8) {
757 $split = split("\t", $str);
758 $tail = array_pop($split);
760 foreach ($split as $hunk) {
762 $pos = strlen(strrchr($expanded, "\n")) - 1;
763 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
765 return substr($expanded, 1) . $tail;
769 * Split WikiWords in page names.
771 * It has been deemed useful to split WikiWords (into "Wiki Words") in
772 * places like page titles. This is rumored to help search engines
775 * @param $page string The page name.
777 * @return string The split name.
779 function split_pagename ($page) {
781 if (preg_match("/\s/", $page))
782 return $page; // Already split --- don't split any more.
784 // FIXME: this algorithm is Anglo-centric.
787 // This mess splits between a lower-case letter followed by
788 // either an upper-case or a numeral; except that it wont
789 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
790 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
791 // This the single-letter words 'I' and 'A' from any following
792 // capitalized words.
793 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
794 // Split numerals from following letters.
795 $RE[] = '/(\d)([[:alpha:]])/';
797 foreach ($RE as $key => $val)
798 $RE[$key] = pcre_fix_posix_classes($val);
800 if (isSubPage($page)) {
801 // FIXME: is this needed?
802 $pages = explode(SUBPAGE_SEPARATOR,$page);
803 $new_page = $pages[0] ? split_pagename($pages[0]) : '';
804 for ($i=1; $i < sizeof($pages); $i++) {
805 $new_page .= (SUBPAGE_SEPARATOR . ($pages[$i] ? split_pagename($pages[$i]) : ''));
809 foreach ($RE as $regexp) {
810 $page = preg_replace($regexp, '\\1 \\2', $page);
816 function NoSuchRevision (&$request, $page, $version) {
817 $html = HTML(HTML::h2(_("Revision Not Found")),
818 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
819 $version, WikiLink($page, 'auto'))));
820 include_once('lib/Template.php');
821 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
827 * Get time offset for local time zone.
829 * @param $time time_t Get offset for this time. Default: now.
830 * @param $no_colon boolean Don't put colon between hours and minutes.
831 * @return string Offset as a string in the format +HH:MM.
833 function TimezoneOffset ($time = false, $no_colon = false) {
836 $secs = date('Z', $time);
845 $colon = $no_colon ? '' : ':';
846 $mins = intval(($secs + 30) / 60);
847 return sprintf("%s%02d%s%02d",
848 $sign, $mins / 60, $colon, $mins % 60);
853 * Format time in ISO-8601 format.
855 * @param $time time_t Time. Default: now.
856 * @return string Date and time in ISO-8601 format.
858 function Iso8601DateTime ($time = false) {
861 $tzoff = TimezoneOffset($time);
862 $date = date('Y-m-d', $time);
863 $time = date('H:i:s', $time);
864 return $date . 'T' . $time . $tzoff;
868 * Format time in RFC-2822 format.
870 * @param $time time_t Time. Default: now.
871 * @return string Date and time in RFC-2822 format.
873 function Rfc2822DateTime ($time = false) {
876 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
880 * Format time in RFC-1123 format.
882 * @param $time time_t Time. Default: now.
883 * @return string Date and time in RFC-1123 format.
885 function Rfc1123DateTime ($time = false) {
888 return gmdate('D, d M Y H:i:s \G\M\T', $time);
891 /** Parse date in RFC-1123 format.
893 * According to RFC 1123 we must accept dates in the following
896 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
897 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
898 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
900 * (Though we're only allowed to generate dates in the first format.)
902 function ParseRfc1123DateTime ($timestr) {
903 $timestr = trim($timestr);
904 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
905 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
907 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
909 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
910 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
912 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
913 if ($year < 70) $year += 2000;
914 elseif ($year < 100) $year += 1900;
916 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
917 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
919 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
926 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
928 return false; // failed
933 * Format time to standard 'ctime' format.
935 * @param $time time_t Time. Default: now.
936 * @return string Date and time.
938 function CTime ($time = false)
942 return date("D M j H:i:s Y", $time);
948 * Internationalized printf.
950 * This is essentially the same as PHP's built-in printf
951 * with the following exceptions:
953 * <li> It passes the format string through gettext().
954 * <li> It supports the argument reordering extensions.
961 * __printf("Differences between versions %s and %s of %s",
962 * $new_link, $old_link, $page_link);
965 * Then in locale/po/de.po, one can reorder the printf arguments:
968 * msgid "Differences between %s and %s of %s."
969 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
972 * (Note that while PHP tries to expand $vars within double-quotes,
973 * the values in msgstr undergo no such expansion, so the '$'s
976 * One shouldn't use reordered arguments in the default format string.
977 * Backslashes in the default string would be necessary to escape the
978 * '$'s, and they'll cause all kinds of trouble....
980 function __printf ($fmt) {
981 $args = func_get_args();
983 echo __vsprintf($fmt, $args);
987 * Internationalized sprintf.
989 * This is essentially the same as PHP's built-in printf with the
990 * following exceptions:
993 * <li> It passes the format string through gettext().
994 * <li> It supports the argument reordering extensions.
999 function __sprintf ($fmt) {
1000 $args = func_get_args();
1002 return __vsprintf($fmt, $args);
1006 * Internationalized vsprintf.
1008 * This is essentially the same as PHP's built-in printf with the
1009 * following exceptions:
1012 * <li> It passes the format string through gettext().
1013 * <li> It supports the argument reordering extensions.
1018 function __vsprintf ($fmt, $args) {
1019 $fmt = gettext($fmt);
1020 // PHP's sprintf doesn't support variable with specifiers,
1021 // like sprintf("%*s", 10, "x"); --- so we won't either.
1023 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1024 // Format string has '%2$s' style argument reordering.
1025 // PHP doesn't support this.
1026 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1027 // literal variable name substitution only to keep locale
1028 // strings uncluttered
1029 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1030 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1032 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1035 // Reorder arguments appropriately.
1036 foreach($m[1] as $argnum) {
1037 if ($argnum < 1 || $argnum > count($args))
1038 trigger_error(sprintf(_("%s: argument index out of range"),
1039 $argnum), E_USER_WARNING);
1040 $newargs[] = $args[$argnum - 1];
1045 // Not all PHP's have vsprintf, so...
1046 array_unshift($args, $fmt);
1047 return call_user_func_array('sprintf', $args);
1053 * Build an array in $this->_fileList of files from $dirname.
1054 * Subdirectories are not traversed.
1056 * (This was a function LoadDir in lib/loadsave.php)
1057 * See also http://www.php.net/manual/en/function.readdir.php
1059 function getFiles() {
1060 return $this->_fileList;
1063 function _filenameSelector($filename) {
1064 if (! $this->_pattern)
1067 return glob_match ($this->_pattern, $filename, $this->_case);
1071 function fileSet($directory, $filepattern = false) {
1072 $this->_fileList = array();
1073 $this->_pattern = $filepattern;
1074 $this->_case = !isWindows();
1075 $this->_pathsep = '/';
1077 if (empty($directory)) {
1078 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1080 return; // early return
1083 @ $dir_handle = opendir($dir=$directory);
1084 if (empty($dir_handle)) {
1085 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1086 $dir), E_USER_NOTICE);
1087 return; // early return
1090 while ($filename = readdir($dir_handle)) {
1091 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1093 if ($this->_filenameSelector($filename)) {
1094 array_push($this->_fileList, "$filename");
1095 //trigger_error(sprintf(_("found file %s"), $filename),
1096 // E_USER_NOTICE); //debugging
1099 closedir($dir_handle);
1105 // expands a list containing regex's to its matching entries
1106 class ListRegexExpand {
1107 var $match, $list, $index, $case_sensitive;
1108 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1109 $this->match = str_replace('/','\/',$match);
1110 $this->list = &$list;
1111 $this->case_sensitive = $case_sensitive;
1113 function listMatchCallback ($item, $key) {
1114 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1115 unset($this->list[$this->index]);
1116 $this->list[] = $item;
1119 function expandRegex ($index, &$pages) {
1120 $this->index = $index;
1121 array_walk($pages, array($this, 'listMatchCallback'));
1126 // convert fileglob to regex style
1127 function glob_to_pcre ($glob) {
1128 $re = preg_replace('/\./', '\\.', $glob);
1129 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1130 if (!preg_match('/^[\?\*]/',$glob))
1132 if (!preg_match('/[\?\*]$/',$glob))
1137 function glob_match ($glob, $against, $case_sensitive = true) {
1138 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1141 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1142 $list = explode(',',$input);
1143 // expand wildcards from list of $allnames
1144 if (preg_match('/[\?\*]/',$input)) {
1145 for ($i = 0; $i < sizeof($list); $i++) {
1147 if (preg_match('/[\?\*]/',$f)) {
1149 $expand = new ListRegexExpand(&$list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1150 $expand->expandRegex($i, &$allnames);
1157 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1159 function explodePageList($input, $perm = false) {
1160 // expand wildcards from list of all pages
1161 if (preg_match('/[\?\*]/',$input)) {
1162 $dbi = $GLOBALS['request']->_dbi;
1163 $allPagehandles = $dbi->getAllPages($perm);
1164 while ($pagehandle = $allPagehandles->next()) {
1165 $allPages[] = $pagehandle->getName();
1167 return explodeList($input, &$allPages);
1169 return explode(',',$input);
1173 // Class introspections
1175 /** Determine whether object is of a specified type.
1177 * @param $object object An object.
1178 * @param $class string Class name.
1179 * @return bool True iff $object is a $class
1180 * or a sub-type of $class.
1182 function isa ($object, $class)
1184 $lclass = strtolower($class);
1186 return is_object($object)
1187 && ( get_class($object) == strtolower($lclass)
1188 || is_subclass_of($object, $lclass) );
1191 /** Determine whether (possible) object has method.
1193 * @param $object mixed Object
1194 * @param $method string Method name
1195 * @return bool True iff $object is an object with has method $method.
1197 function can ($object, $method)
1199 return is_object($object) && method_exists($object, strtolower($method));
1203 * Seed the random number generator.
1205 * better_srand() ensures the randomizer is seeded only once.
1207 * How random do you want it? See:
1208 * http://www.php.net/manual/en/function.srand.php
1209 * http://www.php.net/manual/en/function.mt-srand.php
1211 function better_srand($seed = '') {
1212 static $wascalled = FALSE;
1214 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1217 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1222 * Recursively count all non-empty elements
1223 * in array of any dimension or mixed - i.e.
1224 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1225 * See http://www.php.net/manual/en/function.count.php
1227 function count_all($arg) {
1228 // skip if argument is empty
1230 //print_r($arg); //debugging
1232 // not an array, return 1 (base case)
1235 // else call recursively for all elements $arg
1236 foreach($arg as $key => $val)
1237 $count += count_all($val);
1242 function isSubPage($pagename) {
1243 return (strstr($pagename, SUBPAGE_SEPARATOR));
1246 function subPageSlice($pagename, $pos) {
1247 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1248 $pages = array_slice($pages,$pos,1);
1252 // $Log: not supported by cvs2svn $
1253 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1254 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1255 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1258 // (c-file-style: "gnu")
1262 // c-basic-offset: 4
1263 // c-hanging-comment-ender-p: nil
1264 // indent-tabs-mode: nil