1 <?php //rcs_id('$Id: stdlib.php,v 1.119 2002-09-14 22:58:06 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 function WikiURL($pagename, $args = '', $get_abs_url = false) {
46 if (is_object($pagename)) {
47 if (isa($pagename, 'WikiDB_Page')) {
48 $pagename = $pagename->getName();
50 elseif (isa($pagename, 'WikiDB_PageRevision')) {
51 $page = $pagename->getPage();
52 $args['version'] = $pagename->getVersion();
53 $pagename = $page->getName();
57 if (is_array($args)) {
59 foreach ($args as $key => $val) {
60 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
61 $enc_args[] = urlencode($key) . '=' . urlencode($val);
63 $args = join('&', $enc_args);
67 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
68 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
73 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
74 $url .= "?pagename=" . rawurlencode($pagename);
81 function IconForLink($protocol_or_url) {
83 if ($filename_suffix = false) {
84 // display apache style icon for file type instead of protocol icon
85 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
86 // - document: html, htm, text, txt, rtf, pdf, doc
87 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
88 // - audio: mp3,mp2,aiff,aif,au
89 // - multimedia: mpeg,mpg,mov,qt
91 list ($proto) = explode(':', $protocol_or_url, 2);
92 $src = $Theme->getLinkIconURL($proto);
94 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
100 function LinkURL($url, $linktext = '') {
101 // FIXME: Is this needed (or sufficient?)
102 if(ereg("[<>\"]", $url)) {
103 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
104 _("BAD URL -- remove all of <, >, \"")));
108 $linktext = preg_replace("/mailto:/A", "", $url);
110 $link = HTML::a(array('href' => $url),
111 IconForLink($url), $linktext);
114 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
119 function LinkImage($url, $alt = false) {
120 // FIXME: Is this needed (or sufficient?)
121 if(ereg("[<>\"]", $url)) {
122 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
123 _("BAD URL -- remove all of <, >, \"")));
128 $link = HTML::img(array('src' => $url, 'alt' => $alt));
130 $link->setAttr('class', 'inlineimage');
137 var $items = array();
140 function push($item) {
141 $this->items[$this->size] = $item;
147 if ($this->size == 0) {
148 return false; // stack is empty
151 return $this->items[$this->size];
160 return $this->items[$this->size - 1];
166 // end class definition
169 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
170 // HACK: so as to not completely break old PhpWikiAdministration pages.
171 trigger_error("MagicPhpWikiURL forms are no longer supported. "
172 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
175 $loader = new WikiPluginLoader;
176 @$action = (string)$args['action'];
177 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
180 function SplitQueryArgs ($query_args = '')
182 $split_args = split('&', $query_args);
184 while (list($key, $val) = each($split_args))
185 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
186 $args[$m[1]] = $m[2];
190 function LinkPhpwikiURL($url, $text = '') {
193 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
194 return HTML::strong(array('class' => 'rawurl'),
195 HTML::u(array('class' => 'baduri'),
196 _("BAD phpwiki: URL")));
200 $pagename = urldecode($m[1]);
203 if (empty($pagename) &&
204 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
205 // Convert old style links (to not break diff links in
207 $pagename = urldecode($m[2]);
208 $args = array("action" => $m[1]);
211 $args = SplitQueryArgs($qargs);
214 if (empty($pagename))
215 $pagename = $GLOBALS['request']->getArg('pagename');
217 if (isset($args['action']) && $args['action'] == 'browse')
218 unset($args['action']);
221 if (empty($args['action']))
223 else if (is_safe_action($args['action']))
224 $class = 'wikiaction';
226 if (empty($args['action']) || is_safe_action($args['action']))
227 $class = 'wikiaction';
229 // Don't allow administrative links on unlocked pages.
230 $page = $GLOBALS['request']->getPage();
231 if (!$page->get('locked'))
232 return HTML::span(array('class' => 'wikiunsafe'),
233 HTML::u(_("Lock page to enable link")));
234 $class = 'wikiadmin';
237 // FIXME: ug, don't like this
238 if (preg_match('/=\d*\(/', $qargs))
239 return MakeWikiForm($pagename, $args, $class, $text);
241 $text = HTML::span(array('class' => 'rawurl'), $url);
243 return HTML::a(array('href' => WikiURL($pagename, $args),
248 function LinkBracketLink($bracketlink) {
249 global $request, $AllowedProtocols, $InlineImages;
251 include_once("lib/interwiki.php");
252 $intermap = InterWikiMap::GetMap($request);
254 // $bracketlink will start and end with brackets; in between will
255 // be either a page name, a URL or both separated by a pipe.
257 // strip brackets and leading space
258 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
259 // match the contents
260 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
262 if (isset($matches[3])) {
263 // named link of the form "[some link name | http://blippy.com/]"
264 $URL = trim($matches[3]);
265 $linkname = trim($matches[1]);
267 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
268 $URL = trim($matches[1]);
272 $dbi = $request->getDbh();
273 if (substr($URL,0,1) == SUBPAGE_SEPARATOR) { // relative link to page below
274 if (!$linkname) $linkname = $URL;
275 $URL = $request->getArg('pagename') . $URL;
277 if ($dbi->isWikiPage($URL)) {
278 // if it's an image, it's an named image link [img|link]
279 if (preg_match("/($InlineImages)$/i", $linkname))
280 if (preg_match("#^($AllowedProtocols):#", $URL)) {
281 return WikiLink($URL, 'known', LinkImage($linkname,$URL));
284 // linkname like 'images/next.gif'.
286 return WikiLink($URL, 'known', LinkImage($Theme->getImageURL($linkname),$URL));
289 return WikiLink($URL, 'known', $linkname);
292 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
293 // if it's an image, embed it; otherwise, it's a regular link
294 if (preg_match("/($InlineImages)$/i", $URL))
295 // no image link, just the src. see [img|link] above
296 return LinkImage($URL, $linkname);
298 return LinkURL($URL, $linkname);
300 elseif (preg_match("/^phpwiki:/", $URL))
301 return LinkPhpwikiURL($URL, $linkname);
302 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
303 return $intermap->link($URL, $linkname);
305 return WikiLink($URL, 'unknown', $linkname);
310 /* FIXME: this should be done by the transform code */
311 function ExtractWikiPageLinks($content) {
312 global $WikiNameRegexp;
314 if (is_string($content))
315 $content = explode("\n", $content);
317 $wikilinks = array();
318 foreach ($content as $line) {
319 // remove plugin code
320 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
321 // remove escaped '['
322 $line = str_replace('[[', ' ', $line);
324 $line = preg_replace('/\[\d+\]/', ' ', $line);
326 // bracket links (only type wiki-* is of interest)
327 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
329 for ($i = 0; $i < $numBracketLinks; $i++) {
330 $link = LinkBracketLink($brktlinks[0][$i]);
331 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
332 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
334 $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
336 $wikilinks[$brktlinks[2][$i]] = 1;
339 $brktlink = preg_quote($brktlinks[0][$i]);
340 $line = preg_replace("|$brktlink|", '', $line);
343 // BumpyText old-style wiki links
344 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
345 for ($i = 0; isset($link[0][$i]); $i++) {
346 if($link[0][$i][0] <> '!') {
347 if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
349 $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
351 $wikilinks[$link[0][$i]] = 1;
357 return array_keys($wikilinks);
361 * Convert old page markup to new-style markup.
363 * @param $text string Old-style wiki markup.
365 * @param $just_links bool Only convert old-style links.
366 * (Really this only converts escaped old-style links.)
368 * @return string New-style wiki markup.
370 * @bugs FIXME: footnotes and old-style tables are known to be broken.
372 function ConvertOldMarkup ($text, $just_links = false) {
374 static $orig, $repl, $link_orig, $link_repl;
377 /*****************************************************************
378 * Conversions for inline markup:
385 // escape escaped brackets
389 // change ! escapes to ~'s.
390 global $AllowedProtocols, $WikiNameRegexp, $request;
391 include_once('lib/interwiki.php');
392 $map = InterWikiMap::GetMap($request);
393 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
394 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
395 $bang_esc[] = $WikiNameRegexp;
396 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
403 /*****************************************************************
404 * Conversions for block markup
406 // convert indented blocks to <pre></pre>.
407 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
408 $repl[] = "<pre>\n\\0</pre>\n";
411 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
412 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
417 return preg_replace($link_orig, $link_repl, $text);
419 return preg_replace($orig, $repl, $text);
422 function _ConvertOldListMarkup ($indent, $bullet) {
423 $indent = str_repeat(' ', strlen($indent));
424 if ($bullet[0] == ';') {
425 $term = ltrim(substr($bullet, 1));
426 return $indent . $term . "\n" . $indent . ' ';
429 return $indent . $bullet . ' ';
435 * Split WikiWords in page names.
437 * It has been deemed useful to split WikiWords (into "Wiki Words") in
438 * places like page titles. This is rumored to help search engines
441 * @param $page string The page name.
443 * @return string The split name.
445 function split_pagename ($page) {
447 if (preg_match("/\s/", $page))
448 return $page; // Already split --- don't split any more.
450 // FIXME: this algorithm is Anglo-centric.
453 // This mess splits between a lower-case letter followed by
454 // either an upper-case or a numeral; except that it wont
455 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
456 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
457 // This the single-letter words 'I' and 'A' from any following
458 // capitalized words.
459 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
460 // Split numerals from following letters.
461 $RE[] = '/(\d)([[:alpha:]])/';
463 foreach ($RE as $key => $val)
464 $RE[$key] = pcre_fix_posix_classes($val);
466 if (isSubPage($page)) {
467 $pages = explode(SUBPAGE_SEPARATOR,$page);
468 $new_page = $pages[0] ? split_pagename($pages[0]) : '';
469 for ($i=1; $i < sizeof($pages); $i++) {
470 $new_page .= (SUBPAGE_SEPARATOR . ($pages[$i] ? split_pagename($pages[$i]) : ''));
474 foreach ($RE as $regexp) {
475 $page = preg_replace($regexp, '\\1 \\2', $page);
481 function NoSuchRevision (&$request, $page, $version) {
482 $html = HTML(HTML::h2(_("Revision Not Found")),
483 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
484 $version, WikiLink($page, 'auto'))));
485 include_once('lib/Template.php');
486 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
492 * Get time offset for local time zone.
494 * @param $time time_t Get offset for this time. Default: now.
495 * @param $no_colon boolean Don't put colon between hours and minutes.
496 * @return string Offset as a string in the format +HH:MM.
498 function TimezoneOffset ($time = false, $no_colon = false) {
501 $secs = date('Z', $time);
510 $colon = $no_colon ? '' : ':';
511 $mins = intval(($secs + 30) / 60);
512 return sprintf("%s%02d%s%02d",
513 $sign, $mins / 60, $colon, $mins % 60);
518 * Format time in ISO-8601 format.
520 * @param $time time_t Time. Default: now.
521 * @return string Date and time in ISO-8601 format.
523 function Iso8601DateTime ($time = false) {
526 $tzoff = TimezoneOffset($time);
527 $date = date('Y-m-d', $time);
528 $time = date('H:i:s', $time);
529 return $date . 'T' . $time . $tzoff;
533 * Format time in RFC-2822 format.
535 * @param $time time_t Time. Default: now.
536 * @return string Date and time in RFC-2822 format.
538 function Rfc2822DateTime ($time = false) {
541 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
545 * Format time to standard 'ctime' format.
547 * @param $time time_t Time. Default: now.
548 * @return string Date and time.
550 function CTime ($time = false)
554 return date("D M j H:i:s Y", $time);
560 * Internationalized printf.
562 * This is essentially the same as PHP's built-in printf
563 * with the following exceptions:
565 * <li> It passes the format string through gettext().
566 * <li> It supports the argument reordering extensions.
573 * __printf("Differences between versions %s and %s of %s",
574 * $new_link, $old_link, $page_link);
577 * Then in locale/po/de.po, one can reorder the printf arguments:
580 * msgid "Differences between %s and %s of %s."
581 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
584 * (Note that while PHP tries to expand $vars within double-quotes,
585 * the values in msgstr undergo no such expansion, so the '$'s
588 * One shouldn't use reordered arguments in the default format string.
589 * Backslashes in the default string would be necessary to escape the
590 * '$'s, and they'll cause all kinds of trouble....
592 function __printf ($fmt) {
593 $args = func_get_args();
595 echo __vsprintf($fmt, $args);
599 * Internationalized sprintf.
601 * This is essentially the same as PHP's built-in printf with the
602 * following exceptions:
605 * <li> It passes the format string through gettext().
606 * <li> It supports the argument reordering extensions.
611 function __sprintf ($fmt) {
612 $args = func_get_args();
614 return __vsprintf($fmt, $args);
618 * Internationalized vsprintf.
620 * This is essentially the same as PHP's built-in printf with the
621 * following exceptions:
624 * <li> It passes the format string through gettext().
625 * <li> It supports the argument reordering extensions.
630 function __vsprintf ($fmt, $args) {
631 $fmt = gettext($fmt);
632 // PHP's sprintf doesn't support variable with specifiers,
633 // like sprintf("%*s", 10, "x"); --- so we won't either.
635 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
636 // Format string has '%2$s' style argument reordering.
637 // PHP doesn't support this.
638 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
639 // literal variable name substitution only to keep locale
640 // strings uncluttered
641 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
642 '%1\$s','%s'), E_USER_WARNING); //php+locale error
644 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
647 // Reorder arguments appropriately.
648 foreach($m[1] as $argnum) {
649 if ($argnum < 1 || $argnum > count($args))
650 trigger_error(sprintf(_("%s: argument index out of range"),
651 $argnum), E_USER_WARNING);
652 $newargs[] = $args[$argnum - 1];
657 // Not all PHP's have vsprintf, so...
658 array_unshift($args, $fmt);
659 return call_user_func_array('sprintf', $args);
665 * Build an array in $this->_fileList of files from $dirname.
666 * Subdirectories are not traversed.
668 * (This was a function LoadDir in lib/loadsave.php)
669 * See also http://www.php.net/manual/en/function.readdir.php
671 function getFiles() {
672 return $this->_fileList;
675 function _filenameSelector($filename) {
676 if (! $this->_pattern)
679 return glob_match ($this->_pattern, $filename, $this->_case);
683 function fileSet($directory, $filepattern = false) {
684 $this->_fileList = array();
685 $this->_pattern = $filepattern;
686 $this->_case = !isWindows();
687 $this->_pathsep = '/';
689 if (empty($directory)) {
690 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
692 return; // early return
695 @ $dir_handle = opendir($dir=$directory);
696 if (empty($dir_handle)) {
697 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
698 $dir), E_USER_NOTICE);
699 return; // early return
702 while ($filename = readdir($dir_handle)) {
703 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
705 if ($this->_filenameSelector($filename)) {
706 array_push($this->_fileList, "$filename");
707 //trigger_error(sprintf(_("found file %s"), $filename),
708 // E_USER_NOTICE); //debugging
711 closedir($dir_handle);
717 // expands a list containing regex's to its matching entries
718 class ListRegexExpand {
719 var $match, $list, $index, $case_sensitive;
720 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
721 $this->match = str_replace('/','\/',$match);
722 $this->list = &$list;
723 $this->case_sensitive = $case_sensitive;
725 function listMatchCallback ($item, $key) {
726 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
727 unset($this->list[$this->index]);
728 $this->list[] = $item;
731 function expandRegex ($index, &$pages) {
732 $this->index = $index;
733 array_walk($pages, array($this, 'listMatchCallback'));
738 // convert fileglob to regex style
739 function glob_to_pcre ($glob) {
740 $re = preg_replace('/\./', '\\.', $glob);
741 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
742 if (!preg_match('/^[\?\*]/',$glob))
744 if (!preg_match('/[\?\*]$/',$glob))
749 function glob_match ($glob, $against, $case_sensitive = true) {
750 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
753 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
754 $list = explode(',',$input);
755 // expand wildcards from list of $allnames
756 if (preg_match('/[\?\*]/',$input)) {
757 for ($i = 0; $i <= sizeof($list); $i++) {
759 if (preg_match('/[\?\*]/',$f)) {
761 $expand = new ListRegexExpand(&$list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
762 $expand->expandRegex($i, &$allnames);
769 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
771 function explodePageList($input, $perm = false) {
772 // expand wildcards from list of all pages
773 if (preg_match('/[\?\*]/',$input)) {
774 $dbi = $GLOBALS['request']->_dbi;
775 $allPagehandles = $dbi->getAllPages($perm);
776 while ($pagehandle = $allPagehandles->next()) {
777 $allPages[] = $pagehandle->getName();
779 return explodeList($input, &$allPages);
781 return explode(',',$input);
785 // Class introspections
787 /** Determine whether object is of a specified type.
789 * @param $object object An object.
790 * @param $class string Class name.
791 * @return bool True iff $object is a $class
792 * or a sub-type of $class.
794 function isa ($object, $class)
796 $lclass = strtolower($class);
798 return is_object($object)
799 && ( get_class($object) == strtolower($lclass)
800 || is_subclass_of($object, $lclass) );
803 /** Determine whether (possible) object has method.
805 * @param $object mixed Object
806 * @param $method string Method name
807 * @return bool True iff $object is an object with has method $method.
809 function can ($object, $method)
811 return is_object($object) && method_exists($object, strtolower($method));
815 * Seed the random number generator.
817 * better_srand() ensures the randomizer is seeded only once.
819 * How random do you want it? See:
820 * http://www.php.net/manual/en/function.srand.php
821 * http://www.php.net/manual/en/function.mt-srand.php
823 function better_srand($seed = '') {
824 static $wascalled = FALSE;
826 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
829 //trigger_error("new random seed", E_USER_NOTICE); //debugging
834 * Recursively count all non-empty elements
835 * in array of any dimension or mixed - i.e.
836 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
837 * See http://www.php.net/manual/en/function.count.php
839 function count_all($arg) {
840 // skip if argument is empty
842 //print_r($arg); //debugging
844 // not an array, return 1 (base case)
847 // else call recursively for all elements $arg
848 foreach($arg as $key => $val)
849 $count += count_all($val);
854 function isSubPage($pagename) {
855 return (strstr($pagename, SUBPAGE_SEPARATOR));
858 function subPageSlice($pagename, $pos) {
859 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
860 $pages = array_slice($pages,$pos,1);
865 // (c-file-style: "gnu")
870 // c-hanging-comment-ender-p: nil
871 // indent-tabs-mode: nil