1 <?php //rcs_id('$Id: stdlib.php,v 1.139 2003-02-21 22:16:27 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 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
43 * Convert string to a valid XML identifier.
45 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
47 * We would like to have, e.g. named anchors within wiki pages
48 * names like "Table of Contents" --- clearly not a valid XML
49 * fragment identifier.
51 * This function implements a one-to-one map from {any string}
52 * to {valid XML identifiers}.
55 * converting all bytes not in [A-Za-z0-9:_-],
56 * and any leading byte not in [A-Za-z] to 'xbb.',
57 * where 'bb' is the hexadecimal representation of the
60 * As a special case, the empty string is converted to 'empty.'
65 function MangleXmlIdentifier($str)
70 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
71 "'x' . sprintf('%02x', ord('\\0')) . '.'",
77 * Generates a valid URL for a given Wiki pagename.
78 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
79 * If a WikiDB_Page object function will extract the name to link to.
80 * If a WikiDB_PageRevision object function will extract the name to link to.
82 * @param boolean $get_abs_url Default value is false.
83 * @return string The absolute URL to the page passed as $pagename.
85 function WikiURL($pagename, $args = '', $get_abs_url = false) {
88 if (is_object($pagename)) {
89 if (isa($pagename, 'WikiDB_Page')) {
90 $pagename = $pagename->getName();
92 elseif (isa($pagename, 'WikiDB_PageRevision')) {
93 $page = $pagename->getPage();
94 $args['version'] = $pagename->getVersion();
95 $pagename = $page->getName();
97 elseif (isa($pagename, 'WikiPageName')) {
98 $anchor = $pagename->anchor;
99 $pagename = $pagename->name;
103 if (is_array($args)) {
105 foreach ($args as $key => $val) {
106 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
107 $enc_args[] = urlencode($key) . '=' . urlencode($val);
109 $args = join('&', $enc_args);
113 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
114 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
119 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
120 $url .= "?pagename=" . rawurlencode($pagename);
125 $url .= "#" . MangleXmlIdentifier($anchor);
130 * Generates icon in front of links.
132 * @param string $protocol_or_url URL or protocol to determine which icon to use.
134 * @return HtmlElement HtmlElement object that contains data to create img link to
135 * icon for use with url or protocol passed to the function. False if no img to be
138 function IconForLink($protocol_or_url) {
140 if ($filename_suffix = false) {
141 // display apache style icon for file type instead of protocol icon
142 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
143 // - document: html, htm, text, txt, rtf, pdf, doc
144 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
145 // - audio: mp3,mp2,aiff,aif,au
146 // - multimedia: mpeg,mpg,mov,qt
148 list ($proto) = explode(':', $protocol_or_url, 2);
149 $src = $Theme->getLinkIconURL($proto);
151 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
158 * Glue icon in front of text.
160 * @param string $protocol_or_url Protocol or URL. Used to determine the
162 * @param string $text The text.
163 * @return XmlContent.
165 function PossiblyGlueIconToText($proto_or_url, $text) {
166 $icon = IconForLink($proto_or_url);
168 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
169 list (, $first_word, $tail) = $m;
170 $text = HTML::span(array('style' => 'white-space: nowrap'),
173 $text = HTML($text, $tail);
179 * Determines if the url passed to function is safe, by detecting if the characters
180 * '<', '>', or '"' are present.
182 * @param string $url URL to check for unsafe characters.
183 * @return boolean True if same, false else.
185 function IsSafeURL($url) {
186 return !ereg('[<>"]', $url);
190 * Generates an HtmlElement object to store data for a link.
192 * @param string $url URL that the link will point to.
193 * @param string $linktext Text to be displayed as link.
194 * @return HtmlElement HtmlElement object that contains data to construct an html link.
196 function LinkURL($url, $linktext = '') {
197 // FIXME: Is this needed (or sufficient?)
198 if(! IsSafeURL($url)) {
199 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
200 _("BAD URL -- remove all of <, >, \"")));
204 $linktext = preg_replace("/mailto:/A", "", $url);
206 $link = HTML::a(array('href' => $url),
207 PossiblyGlueIconToText($url, $linktext));
210 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
215 function LinkImage($url, $alt = false) {
216 // FIXME: Is this needed (or sufficient?)
217 if(! IsSafeURL($url)) {
218 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
219 _("BAD URL -- remove all of <, >, \"")));
224 $link = HTML::img(array('src' => $url, 'alt' => $alt));
226 $link->setAttr('class', 'inlineimage');
233 var $items = array();
236 function push($item) {
237 $this->items[$this->size] = $item;
243 if ($this->size == 0) {
244 return false; // stack is empty
247 return $this->items[$this->size];
256 return $this->items[$this->size - 1];
262 // end class definition
264 function SplitQueryArgs ($query_args = '')
266 $split_args = split('&', $query_args);
268 while (list($key, $val) = each($split_args))
269 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
270 $args[$m[1]] = $m[2];
274 function LinkPhpwikiURL($url, $text = '') {
277 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
278 return HTML::strong(array('class' => 'rawurl'),
279 HTML::u(array('class' => 'baduri'),
280 _("BAD phpwiki: URL")));
284 $pagename = urldecode($m[1]);
287 if (empty($pagename) &&
288 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
289 // Convert old style links (to not break diff links in
291 $pagename = urldecode($m[2]);
292 $args = array("action" => $m[1]);
295 $args = SplitQueryArgs($qargs);
298 if (empty($pagename))
299 $pagename = $GLOBALS['request']->getArg('pagename');
301 if (isset($args['action']) && $args['action'] == 'browse')
302 unset($args['action']);
305 if (empty($args['action']))
307 else if (is_safe_action($args['action']))
308 $class = 'wikiaction';
310 if (empty($args['action']) || is_safe_action($args['action']))
311 $class = 'wikiaction';
313 // Don't allow administrative links on unlocked pages.
314 $page = $GLOBALS['request']->getPage();
315 if (!$page->get('locked'))
316 return HTML::span(array('class' => 'wikiunsafe'),
317 HTML::u(_("Lock page to enable link")));
318 $class = 'wikiadmin';
322 $text = HTML::span(array('class' => 'rawurl'), $url);
324 return HTML::a(array('href' => WikiURL($pagename, $args),
330 * A class to assist in parsing wiki pagenames.
332 * Now with subpages and anchors, parsing and passing around
333 * pagenames is more complicated. This should help.
337 /** Short name for page.
339 * This is the value of $name passed to the constructor.
340 * (For use, e.g. as a default label for links to the page.)
344 /** The full page name.
346 * This is the full name of the page (without anchor).
352 * This is the referenced anchor within the page, or the empty string.
358 * @param mixed $name Page name.
359 * WikiDB_Page, WikiDB_PageRevision, or string.
360 * This can be a relative subpage name (like '/SubPage'),
361 * or can be the empty string to refer to the $basename.
363 * @param string $anchor For links to anchors in page.
365 * @param mixed $basename Page name from which to interpret
366 * relative or other non-fully-specified page names.
368 function WikiPageName($name, $basename=false, $anchor=false) {
369 if (is_string($name)) {
370 $this->shortName = $name;
372 if ($anchor === false and preg_match('/\A(.*)#(.*?)?\Z/', $name, $m))
373 list(, $name, $anchor) = $m;
375 if (empty($name) or $name[0] == SUBPAGE_SEPARATOR) {
377 $name = $this->_pagename($basename) . $name;
379 $name = $this->_normalize_bad_pagename($name);
383 $name = $this->_pagename($name);
384 $this->shortName = $name;
388 $this->anchor = (string)$anchor;
391 function getParent() {
393 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
395 return substr($name, 0, -strlen($tail));
398 function _pagename($page) {
399 if (isa($page, 'WikiDB_Page'))
400 return $page->getName();
401 elseif (isa($page, 'WikiDB_PageRevision'))
402 return $page->getPageName();
403 elseif (isa($page, 'WikiPageName'))
405 if (!is_string($page)) {
406 print "PAGE: " . gettype($page) . " " . get_class($page) . "<br>\n";
408 //assert(is_string($page));
412 function _normalize_bad_pagename($name) {
413 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
415 // Punt... You really shouldn't get here.
418 return $request->getArg('pagename');
420 assert($name[0] == SUBPAGE_SEPARATOR);
421 return substr($name, 1);
426 * Convert old page markup to new-style markup.
428 * @param string $text Old-style wiki markup.
430 * @param string $markup_type
432 * <dt><code>"block"</code> <dd>Convert all markup.
433 * <dt><code>"inline"</code> <dd>Convert only inline markup.
434 * <dt><code>"links"</code> <dd>Convert only link markup.
437 * @return string New-style wiki markup.
439 * @bugs Footnotes don't work quite as before (esp if there are
440 * multiple references to the same footnote. But close enough,
441 * probably for now....
443 function ConvertOldMarkup ($text, $markup_type = "block") {
449 /*****************************************************************
450 * Conversions for inline markup:
457 // escape escaped brackets
461 // change ! escapes to ~'s.
462 global $AllowedProtocols, $WikiNameRegexp, $request;
463 include_once('lib/interwiki.php');
464 $map = InterWikiMap::GetMap($request);
465 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
466 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
467 $bang_esc[] = $WikiNameRegexp;
468 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
471 $subs["links"] = array($orig, $repl);
474 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
477 // Convert footnote references.
478 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
479 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
481 // Convert old style emphases to HTML style emphasis.
482 $orig[] = '/__(.*?)__/';
483 $repl[] = '<strong>\\1</strong>';
484 $orig[] = "/''(.*?)''/";
485 $repl[] = '<em>\\1</em>';
487 // Escape nestled markup.
488 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
491 // in old markup headings only allowed at beginning of line
495 $subs["inline"] = array($orig, $repl);
497 /*****************************************************************
498 * Patterns which match block markup constructs which take
499 * special handling...
503 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
506 $blockpats[] = '\|(?:.*\n\|)*';
509 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
511 // Footnote definitions
512 $blockpats[] = '\[\s*(\d+)\s*\]';
515 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
518 $blockpats[] = '!{1,3}[^!]';
520 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
521 . join("|", $blockpats)
526 if ($markup_type != "block") {
527 list ($orig, $repl) = $subs[$markup_type];
528 return preg_replace($orig, $repl, $text);
531 list ($orig, $repl) = $subs['inline'];
533 while (preg_match($block_re, $text, $m)) {
534 $text = substr($text, strlen($m[0]));
535 list (,$leading_text, $block) = $m;
538 if (strchr(" \t", $block[0])) {
541 $suffix = "\n</pre>\n";
543 elseif ($block[0] == '|') {
545 $prefix = "<?plugin OldStyleTable\n";
548 elseif (strchr("#*;", $block[0])) {
549 // Old-style list item
550 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
551 list (,$ind,$bullet) = $m;
552 $block = substr($block, strlen($m[0]));
554 $indent = str_repeat(' ', strlen($ind));
555 if ($bullet[0] == ';') {
556 //$term = ltrim(substr($bullet, 1));
557 //return $indent . $term . "\n" . $indent . ' ';
558 $prefix = $ind . $bullet;
561 $prefix = $indent . $bullet . ' ';
563 elseif ($block[0] == '[') {
564 // Footnote definition
565 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
567 $block = substr($block, strlen($m[0]));
568 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
570 elseif ($block[0] == '<') {
572 // HACK: no inline markup...
576 elseif ($block[0] == '!') {
578 preg_match('/^!{1,3}/', $block, $m);
580 $block = substr($block, strlen($m[0]));
587 $out .= ( preg_replace($orig, $repl, $leading_text)
589 . preg_replace($orig, $repl, $block)
592 return $out . preg_replace($orig, $repl, $text);
598 * Expand tabs in string.
600 * Converts all tabs to (the appropriate number of) spaces.
603 * @param integer $tab_width
606 function expand_tabs($str, $tab_width = 8) {
607 $split = split("\t", $str);
608 $tail = array_pop($split);
610 foreach ($split as $hunk) {
612 $pos = strlen(strrchr($expanded, "\n")) - 1;
613 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
615 return substr($expanded, 1) . $tail;
619 * Split WikiWords in page names.
621 * It has been deemed useful to split WikiWords (into "Wiki Words") in
622 * places like page titles. This is rumored to help search engines
625 * @param $page string The page name.
627 * @return string The split name.
629 function split_pagename ($page) {
631 if (preg_match("/\s/", $page))
632 return $page; // Already split --- don't split any more.
634 // FIXME: this algorithm is Anglo-centric.
637 // This mess splits between a lower-case letter followed by
638 // either an upper-case or a numeral; except that it wont
639 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
640 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
641 // This the single-letter words 'I' and 'A' from any following
642 // capitalized words.
643 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
644 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
645 // Split numerals from following letters.
646 $RE[] = '/(\d)([[:alpha:]])/';
648 foreach ($RE as $key => $val)
649 $RE[$key] = pcre_fix_posix_classes($val);
652 foreach ($RE as $regexp) {
653 $page = preg_replace($regexp, '\\1 \\2', $page);
658 function NoSuchRevision (&$request, $page, $version) {
659 $html = HTML(HTML::h2(_("Revision Not Found")),
660 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
661 $version, WikiLink($page, 'auto'))));
662 include_once('lib/Template.php');
663 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
669 * Get time offset for local time zone.
671 * @param $time time_t Get offset for this time. Default: now.
672 * @param $no_colon boolean Don't put colon between hours and minutes.
673 * @return string Offset as a string in the format +HH:MM.
675 function TimezoneOffset ($time = false, $no_colon = false) {
678 $secs = date('Z', $time);
687 $colon = $no_colon ? '' : ':';
688 $mins = intval(($secs + 30) / 60);
689 return sprintf("%s%02d%s%02d",
690 $sign, $mins / 60, $colon, $mins % 60);
695 * Format time in ISO-8601 format.
697 * @param $time time_t Time. Default: now.
698 * @return string Date and time in ISO-8601 format.
700 function Iso8601DateTime ($time = false) {
703 $tzoff = TimezoneOffset($time);
704 $date = date('Y-m-d', $time);
705 $time = date('H:i:s', $time);
706 return $date . 'T' . $time . $tzoff;
710 * Format time in RFC-2822 format.
712 * @param $time time_t Time. Default: now.
713 * @return string Date and time in RFC-2822 format.
715 function Rfc2822DateTime ($time = false) {
718 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
722 * Format time in RFC-1123 format.
724 * @param $time time_t Time. Default: now.
725 * @return string Date and time in RFC-1123 format.
727 function Rfc1123DateTime ($time = false) {
730 return gmdate('D, d M Y H:i:s \G\M\T', $time);
733 /** Parse date in RFC-1123 format.
735 * According to RFC 1123 we must accept dates in the following
738 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
739 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
740 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
742 * (Though we're only allowed to generate dates in the first format.)
744 function ParseRfc1123DateTime ($timestr) {
745 $timestr = trim($timestr);
746 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
747 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
749 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
751 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
752 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
754 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
755 if ($year < 70) $year += 2000;
756 elseif ($year < 100) $year += 1900;
758 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
759 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
761 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
768 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
770 return false; // failed
775 * Format time to standard 'ctime' format.
777 * @param $time time_t Time. Default: now.
778 * @return string Date and time.
780 function CTime ($time = false)
784 return date("D M j H:i:s Y", $time);
790 * Internationalized printf.
792 * This is essentially the same as PHP's built-in printf
793 * with the following exceptions:
795 * <li> It passes the format string through gettext().
796 * <li> It supports the argument reordering extensions.
803 * __printf("Differences between versions %s and %s of %s",
804 * $new_link, $old_link, $page_link);
807 * Then in locale/po/de.po, one can reorder the printf arguments:
810 * msgid "Differences between %s and %s of %s."
811 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
814 * (Note that while PHP tries to expand $vars within double-quotes,
815 * the values in msgstr undergo no such expansion, so the '$'s
818 * One shouldn't use reordered arguments in the default format string.
819 * Backslashes in the default string would be necessary to escape the
820 * '$'s, and they'll cause all kinds of trouble....
822 function __printf ($fmt) {
823 $args = func_get_args();
825 echo __vsprintf($fmt, $args);
829 * Internationalized sprintf.
831 * This is essentially the same as PHP's built-in printf with the
832 * following exceptions:
835 * <li> It passes the format string through gettext().
836 * <li> It supports the argument reordering extensions.
841 function __sprintf ($fmt) {
842 $args = func_get_args();
844 return __vsprintf($fmt, $args);
848 * Internationalized vsprintf.
850 * This is essentially the same as PHP's built-in printf with the
851 * following exceptions:
854 * <li> It passes the format string through gettext().
855 * <li> It supports the argument reordering extensions.
860 function __vsprintf ($fmt, $args) {
861 $fmt = gettext($fmt);
862 // PHP's sprintf doesn't support variable with specifiers,
863 // like sprintf("%*s", 10, "x"); --- so we won't either.
865 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
866 // Format string has '%2$s' style argument reordering.
867 // PHP doesn't support this.
868 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
869 // literal variable name substitution only to keep locale
870 // strings uncluttered
871 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
872 '%1\$s','%s'), E_USER_WARNING); //php+locale error
874 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
877 // Reorder arguments appropriately.
878 foreach($m[1] as $argnum) {
879 if ($argnum < 1 || $argnum > count($args))
880 trigger_error(sprintf(_("%s: argument index out of range"),
881 $argnum), E_USER_WARNING);
882 $newargs[] = $args[$argnum - 1];
887 // Not all PHP's have vsprintf, so...
888 array_unshift($args, $fmt);
889 return call_user_func_array('sprintf', $args);
895 * Build an array in $this->_fileList of files from $dirname.
896 * Subdirectories are not traversed.
898 * (This was a function LoadDir in lib/loadsave.php)
899 * See also http://www.php.net/manual/en/function.readdir.php
901 function getFiles() {
902 return $this->_fileList;
905 function _filenameSelector($filename) {
906 if (! $this->_pattern)
909 return glob_match ($this->_pattern, $filename, $this->_case);
913 function fileSet($directory, $filepattern = false) {
914 $this->_fileList = array();
915 $this->_pattern = $filepattern;
916 $this->_case = !isWindows();
917 $this->_pathsep = '/';
919 if (empty($directory)) {
920 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
922 return; // early return
925 @ $dir_handle = opendir($dir=$directory);
926 if (empty($dir_handle)) {
927 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
928 $dir), E_USER_NOTICE);
929 return; // early return
932 while ($filename = readdir($dir_handle)) {
933 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
935 if ($this->_filenameSelector($filename)) {
936 array_push($this->_fileList, "$filename");
937 //trigger_error(sprintf(_("found file %s"), $filename),
938 // E_USER_NOTICE); //debugging
941 closedir($dir_handle);
947 // expands a list containing regex's to its matching entries
948 class ListRegexExpand {
949 var $match, $list, $index, $case_sensitive;
950 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
951 $this->match = str_replace('/','\/',$match);
952 $this->list = &$list;
953 $this->case_sensitive = $case_sensitive;
955 function listMatchCallback ($item, $key) {
956 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
957 unset($this->list[$this->index]);
958 $this->list[] = $item;
961 function expandRegex ($index, &$pages) {
962 $this->index = $index;
963 array_walk($pages, array($this, 'listMatchCallback'));
968 // convert fileglob to regex style
969 function glob_to_pcre ($glob) {
970 $re = preg_replace('/\./', '\\.', $glob);
971 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
972 if (!preg_match('/^[\?\*]/',$glob))
974 if (!preg_match('/[\?\*]$/',$glob))
979 function glob_match ($glob, $against, $case_sensitive = true) {
980 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
983 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
984 $list = explode(',',$input);
985 // expand wildcards from list of $allnames
986 if (preg_match('/[\?\*]/',$input)) {
987 for ($i = 0; $i < sizeof($list); $i++) {
989 if (preg_match('/[\?\*]/',$f)) {
991 $expand = new ListRegexExpand(&$list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
992 $expand->expandRegex($i, &$allnames);
999 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1001 function explodePageList($input, $perm = false) {
1002 // expand wildcards from list of all pages
1003 if (preg_match('/[\?\*]/',$input)) {
1004 $dbi = $GLOBALS['request']->_dbi;
1005 $allPagehandles = $dbi->getAllPages($perm);
1006 while ($pagehandle = $allPagehandles->next()) {
1007 $allPages[] = $pagehandle->getName();
1009 return explodeList($input, &$allPages);
1011 return explode(',',$input);
1015 // Class introspections
1017 /** Determine whether object is of a specified type.
1019 * @param $object object An object.
1020 * @param $class string Class name.
1021 * @return bool True iff $object is a $class
1022 * or a sub-type of $class.
1024 function isa ($object, $class)
1026 $lclass = strtolower($class);
1028 return is_object($object)
1029 && ( get_class($object) == strtolower($lclass)
1030 || is_subclass_of($object, $lclass) );
1033 /** Determine whether (possible) object has method.
1035 * @param $object mixed Object
1036 * @param $method string Method name
1037 * @return bool True iff $object is an object with has method $method.
1039 function can ($object, $method)
1041 return is_object($object) && method_exists($object, strtolower($method));
1046 * This is used for generating ETags.
1048 function hash ($x) {
1049 if (is_scalar($x)) {
1052 elseif (is_array($x)) {
1054 return md5(serialize($x));
1056 elseif (is_object($x)) {
1059 trigger_error("Can't hash $x", E_USER_ERROR);
1064 * Seed the random number generator.
1066 * better_srand() ensures the randomizer is seeded only once.
1068 * How random do you want it? See:
1069 * http://www.php.net/manual/en/function.srand.php
1070 * http://www.php.net/manual/en/function.mt-srand.php
1072 function better_srand($seed = '') {
1073 static $wascalled = FALSE;
1075 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1078 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1083 * Recursively count all non-empty elements
1084 * in array of any dimension or mixed - i.e.
1085 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1086 * See http://www.php.net/manual/en/function.count.php
1088 function count_all($arg) {
1089 // skip if argument is empty
1091 //print_r($arg); //debugging
1093 // not an array, return 1 (base case)
1096 // else call recursively for all elements $arg
1097 foreach($arg as $key => $val)
1098 $count += count_all($val);
1103 function isSubPage($pagename) {
1104 return (strstr($pagename, SUBPAGE_SEPARATOR));
1107 function subPageSlice($pagename, $pos) {
1108 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1109 $pages = array_slice($pages,$pos,1);
1116 * Class for "popping up" and alert box. (Except that right now, it doesn't
1120 * This is a hackish and needs to be refactored. However it would be nice to
1121 * unify all the different methods we use for showing Alerts and Dialogs.
1122 * (E.g. "Page deleted", login form, ...)
1127 * @param object $request
1128 * @param mixed $head Header ("title") for alert box.
1129 * @param mixed $body The text in the alert box.
1130 * @param hash $buttons An array mapping button labels to URLs.
1131 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1133 function Alert($head, $body, $buttons=false) {
1134 if ($buttons === false)
1137 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1138 $this->_buttons = $buttons;
1142 * Show the alert box.
1144 function show(&$request) {
1147 $tokens = $this->_tokens;
1148 $tokens['BUTTONS'] = $this->_getButtons();
1150 $request->discardOutput();
1151 $tmpl = new Template('dialog', $request, $tokens);
1157 function _getButtons() {
1160 $buttons = $this->_buttons;
1162 $buttons = array(_("Okay") => $request->getURLtoSelf());
1165 foreach ($buttons as $label => $url)
1166 print "$label $url\n";
1167 $out[] = $Theme->makeButton($label, $url, 'wikiaction');
1168 return new XmlContent($out);
1174 // $Log: not supported by cvs2svn $
1175 // Revision 1.138 2003/02/21 04:12:36 dairiki
1176 // WikiPageName: fixes for new cached links.
1178 // Alert: new class for displaying alerts.
1180 // ExtractWikiPageLinks and friends are now gone.
1182 // LinkBracketLink moved to InlineParser.php
1184 // Revision 1.137 2003/02/18 23:13:40 dairiki
1185 // Wups again. Typo fix.
1187 // Revision 1.136 2003/02/18 21:52:07 dairiki
1188 // Fix so that one can still link to wiki pages with # in their names.
1189 // (This was made difficult by the introduction of named tags, since
1190 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1192 // Now the ~ escape for page names should work: [Page ~#1].
1194 // Revision 1.135 2003/02/18 19:17:04 dairiki
1195 // split_pagename():
1196 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1197 // Cleanup up subpage splitting code.
1199 // Revision 1.134 2003/02/16 19:44:20 dairiki
1200 // New function hash(). This is a helper, primarily for generating
1203 // Revision 1.133 2003/02/16 04:50:09 dairiki
1205 // Rfc1123DateTime(), ParseRfc1123DateTime()
1206 // for converting unix timestamps to and from strings.
1208 // These functions produce and grok the time strings
1209 // in the format specified by RFC 2616 for use in HTTP headers
1210 // (like Last-Modified).
1212 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1213 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1214 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1217 // (c-file-style: "gnu")
1221 // c-basic-offset: 4
1222 // c-hanging-comment-ender-p: nil
1223 // indent-tabs-mode: nil