1 <?php rcs_id('$Id: stdlib.php,v 1.114 2002-08-22 23:28: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 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 = '')
30 function: LinkInterWikiLink($link, $linktext)
31 moved to: lib/interwiki.php
32 function: linkExistingWikiWord($wikiword, $linktext, $version)
33 moved to: lib/Theme.php
34 function: LinkUnknownWikiWord($wikiword, $linktext)
35 moved to: lib/Theme.php
36 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
37 gone see: lib/plugin/RecentChanges.php
41 function WikiURL($pagename, $args = '', $get_abs_url = false) {
42 if (is_object($pagename)) {
43 if (isa($pagename, 'WikiDB_Page')) {
44 $pagename = $pagename->getName();
46 elseif (isa($pagename, 'WikiDB_PageRevision')) {
47 $page = $pagename->getPage();
48 $args['version'] = $pagename->getVersion();
49 $pagename = $page->getName();
53 if (is_array($args)) {
55 foreach ($args as $key => $val) {
56 $enc_args[] = urlencode($key) . '=' . urlencode($val);
58 $args = join('&', $enc_args);
62 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
63 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
68 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
69 $url .= "?pagename=" . rawurlencode($pagename);
76 function IconForLink($protocol_or_url) {
78 if ($filename_suffix = false) {
79 // display apache style icon for file type instead of protocol icon
80 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
81 // - document: html, htm, text, txt, rtf, pdf, doc
82 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
83 // - audio: mp3,mp2,aiff,aif,au
84 // - multimedia: mpeg,mpg,mov,qt
86 list ($proto) = explode(':', $protocol_or_url, 2);
87 $src = $Theme->getLinkIconURL($proto);
89 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
95 function LinkURL($url, $linktext = '') {
96 // FIXME: Is this needed (or sufficient?)
97 if(ereg("[<>\"]", $url)) {
98 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
99 _("BAD URL -- remove all of <, >, \"")));
103 $linktext = preg_replace("/mailto:/A", "", $url);
105 $link = HTML::a(array('href' => $url),
106 IconForLink($url), $linktext);
109 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
114 function LinkImage($url, $alt = false) {
115 // FIXME: Is this needed (or sufficient?)
116 if(ereg("[<>\"]", $url)) {
117 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
118 _("BAD URL -- remove all of <, >, \"")));
123 $link = HTML::img(array('src' => $url, 'alt' => $alt));
125 $link->setAttr('class', 'inlineimage');
132 var $items = array();
135 function push($item) {
136 $this->items[$this->size] = $item;
142 if ($this->size == 0) {
143 return false; // stack is empty
146 return $this->items[$this->size];
155 return $this->items[$this->size - 1];
161 // end class definition
164 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
165 // HACK: so as to not completely break old PhpWikiAdministration pages.
166 trigger_error("MagicPhpWikiURL forms are no longer supported. "
167 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
170 $loader = new WikiPluginLoader;
171 @$action = (string)$args['action'];
172 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
175 function SplitQueryArgs ($query_args = '')
177 $split_args = split('&', $query_args);
179 while (list($key, $val) = each($split_args))
180 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
181 $args[$m[1]] = $m[2];
185 function LinkPhpwikiURL($url, $text = '') {
188 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
189 return HTML::strong(array('class' => 'rawurl'),
190 HTML::u(array('class' => 'baduri'),
191 _("BAD phpwiki: URL")));
195 $pagename = urldecode($m[1]);
198 if (empty($pagename) &&
199 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
200 // Convert old style links (to not break diff links in
202 $pagename = urldecode($m[2]);
203 $args = array("action" => $m[1]);
206 $args = SplitQueryArgs($qargs);
209 if (empty($pagename))
210 $pagename = $GLOBALS['request']->getArg('pagename');
212 if (isset($args['action']) && $args['action'] == 'browse')
213 unset($args['action']);
216 if (empty($args['action']))
218 else if (is_safe_action($args['action']))
219 $class = 'wikiaction';
221 if (empty($args['action']) || is_safe_action($args['action']))
222 $class = 'wikiaction';
224 // Don't allow administrative links on unlocked pages.
225 $page = $GLOBALS['request']->getPage();
226 if (!$page->get('locked'))
227 return HTML::span(array('class' => 'wikiunsafe'),
228 HTML::u(_("Lock page to enable link")));
229 $class = 'wikiadmin';
232 // FIXME: ug, don't like this
233 if (preg_match('/=\d*\(/', $qargs))
234 return MakeWikiForm($pagename, $args, $class, $text);
236 $text = HTML::span(array('class' => 'rawurl'), $url);
238 return HTML::a(array('href' => WikiURL($pagename, $args),
243 function LinkBracketLink($bracketlink) {
244 global $request, $AllowedProtocols, $InlineImages;
246 include_once("lib/interwiki.php");
247 $intermap = InterWikiMap::GetMap($request);
249 // $bracketlink will start and end with brackets; in between will
250 // be either a page name, a URL or both separated by a pipe.
252 // strip brackets and leading space
253 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
254 // match the contents
255 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
257 if (isset($matches[3])) {
258 // named link of the form "[some link name | http://blippy.com/]"
259 $URL = trim($matches[3]);
260 $linkname = trim($matches[1]);
262 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
263 $URL = trim($matches[1]);
267 $dbi = $request->getDbh();
268 if (substr($URL,0,1) == SUBPAGE_SEPARATOR) { // relative link to page below
269 if (!$linkname) $linkname = $URL;
270 $URL = $request->getArg('pagename') . $URL;
272 if ($dbi->isWikiPage($URL)) {
273 // if it's an image, it's an named image link [img|link]
274 if (preg_match("/($InlineImages)$/i", $linkname))
275 if (preg_match("#^($AllowedProtocols):#", $URL)) {
276 return WikiLink($URL, 'known', LinkImage($linkname,$URL));
279 // linkname like 'images/next.gif'.
281 return WikiLink($URL, 'known', LinkImage($Theme->getImageURL($linkname),$URL));
284 return WikiLink($URL, 'known', $linkname);
287 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
288 // if it's an image, embed it; otherwise, it's a regular link
289 if (preg_match("/($InlineImages)$/i", $URL))
290 // no image link, just the src. see [img|link] above
291 return LinkImage($URL, $linkname);
293 return LinkURL($URL, $linkname);
295 elseif (preg_match("/^phpwiki:/", $URL))
296 return LinkPhpwikiURL($URL, $linkname);
297 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
298 return $intermap->link($URL, $linkname);
300 return WikiLink($URL, 'unknown', $linkname);
305 /* FIXME: this should be done by the transform code */
306 function ExtractWikiPageLinks($content) {
307 global $WikiNameRegexp;
309 if (is_string($content))
310 $content = explode("\n", $content);
312 $wikilinks = array();
313 foreach ($content as $line) {
314 // remove plugin code
315 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
316 // remove escaped '['
317 $line = str_replace('[[', ' ', $line);
319 $line = preg_replace('/[\d+]/', ' ', $line);
321 // bracket links (only type wiki-* is of interest)
322 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
324 for ($i = 0; $i < $numBracketLinks; $i++) {
325 $link = LinkBracketLink($brktlinks[0][$i]);
326 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
327 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
329 $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
331 $wikilinks[$brktlinks[2][$i]] = 1;
334 $brktlink = preg_quote($brktlinks[0][$i]);
335 $line = preg_replace("|$brktlink|", '', $line);
338 // BumpyText old-style wiki links
339 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
340 for ($i = 0; isset($link[0][$i]); $i++) {
341 if($link[0][$i][0] <> '!') {
342 if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
344 $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
346 $wikilinks[$link[0][$i]] = 1;
352 return array_keys($wikilinks);
356 * Convert old page markup to new-style markup.
358 * @param $text string Old-style wiki markup.
360 * @param $just_links bool Only convert old-style links.
361 * (Really this only converts escaped old-style links.)
363 * @return string New-style wiki markup.
365 * @bugs FIXME: footnotes and old-style tables are known to be broken.
367 function ConvertOldMarkup ($text, $just_links = false) {
369 static $orig, $repl, $link_orig, $link_repl;
372 /*****************************************************************
373 * Conversions for inline markup:
380 // escape escaped brackets
384 // change ! escapes to ~'s.
385 global $AllowedProtocols, $WikiNameRegexp, $request;
386 include_once('lib/interwiki.php');
387 $map = InterWikiMap::GetMap($request);
388 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
389 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
390 $bang_esc[] = $WikiNameRegexp;
391 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
398 /*****************************************************************
399 * Conversions for block markup
401 // convert indented blocks to <pre></pre>.
402 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
403 $repl[] = "<pre>\n\\0</pre>\n";
406 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
407 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
412 return preg_replace($link_orig, $link_repl, $text);
414 return preg_replace($orig, $repl, $text);
417 function _ConvertOldListMarkup ($indent, $bullet) {
418 $indent = str_repeat(' ', strlen($indent));
419 if ($bullet[0] == ';') {
420 $term = ltrim(substr($bullet, 1));
421 return $indent . $term . "\n" . $indent . ' ';
424 return $indent . $bullet . ' ';
430 * Split WikiWords in page names.
432 * It has been deemed useful to split WikiWords (into "Wiki Words") in
433 * places like page titles. This is rumored to help search engines
436 * @param $page string The page name.
438 * @return string The split name.
440 function split_pagename ($page) {
442 if (preg_match("/\s/", $page))
443 return $page; // Already split --- don't split any more.
445 // FIXME: this algorithm is Anglo-centric.
448 // This mess splits between a lower-case letter followed by
449 // either an upper-case or a numeral; except that it wont
450 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
451 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
452 // This the single-letter words 'I' and 'A' from any following
453 // capitalized words.
454 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
455 // Split numerals from following letters.
456 $RE[] = '/(\d)([[:alpha:]])/';
458 foreach ($RE as $key => $val)
459 $RE[$key] = pcre_fix_posix_classes($val);
462 foreach ($RE as $regexp)
463 $page = preg_replace($regexp, '\\1 \\2', $page);
467 function NoSuchRevision (&$request, $page, $version) {
468 $html = HTML(HTML::h2(_("Revision Not Found")),
469 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
470 $version, WikiLink($page, 'auto'))));
471 include_once('lib/Template.php');
472 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
478 * Get time offset for local time zone.
480 * @param $time time_t Get offset for this time. Default: now.
481 * @param $no_colon boolean Don't put colon between hours and minutes.
482 * @return string Offset as a string in the format +HH:MM.
484 function TimezoneOffset ($time = false, $no_colon = false) {
487 $secs = date('Z', $time);
496 $colon = $no_colon ? '' : ':';
497 $mins = intval(($secs + 30) / 60);
498 return sprintf("%s%02d%s%02d",
499 $sign, $mins / 60, $colon, $mins % 60);
504 * Format time in ISO-8601 format.
506 * @param $time time_t Time. Default: now.
507 * @return string Date and time in ISO-8601 format.
509 function Iso8601DateTime ($time = false) {
512 $tzoff = TimezoneOffset($time);
513 $date = date('Y-m-d', $time);
514 $time = date('H:i:s', $time);
515 return $date . 'T' . $time . $tzoff;
519 * Format time in RFC-2822 format.
521 * @param $time time_t Time. Default: now.
522 * @return string Date and time in RFC-2822 format.
524 function Rfc2822DateTime ($time = false) {
527 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
531 * Format time to standard 'ctime' format.
533 * @param $time time_t Time. Default: now.
534 * @return string Date and time.
536 function CTime ($time = false)
540 return date("D M j H:i:s Y", $time);
546 * Internationalized printf.
548 * This is essentially the same as PHP's built-in printf
549 * with the following exceptions:
551 * <li> It passes the format string through gettext().
552 * <li> It supports the argument reordering extensions.
559 * __printf("Differences between versions %s and %s of %s",
560 * $new_link, $old_link, $page_link);
563 * Then in locale/po/de.po, one can reorder the printf arguments:
566 * msgid "Differences between %s and %s of %s."
567 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
570 * (Note that while PHP tries to expand $vars within double-quotes,
571 * the values in msgstr undergo no such expansion, so the '$'s
574 * One shouldn't use reordered arguments in the default format string.
575 * Backslashes in the default string would be necessary to escape the
576 * '$'s, and they'll cause all kinds of trouble....
578 function __printf ($fmt) {
579 $args = func_get_args();
581 echo __vsprintf($fmt, $args);
585 * Internationalized sprintf.
587 * This is essentially the same as PHP's built-in printf with the
588 * following exceptions:
591 * <li> It passes the format string through gettext().
592 * <li> It supports the argument reordering extensions.
597 function __sprintf ($fmt) {
598 $args = func_get_args();
600 return __vsprintf($fmt, $args);
604 * Internationalized vsprintf.
606 * This is essentially the same as PHP's built-in printf with the
607 * following exceptions:
610 * <li> It passes the format string through gettext().
611 * <li> It supports the argument reordering extensions.
616 function __vsprintf ($fmt, $args) {
617 $fmt = gettext($fmt);
618 // PHP's sprintf doesn't support variable with specifiers,
619 // like sprintf("%*s", 10, "x"); --- so we won't either.
621 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
622 // Format string has '%2$s' style argument reordering.
623 // PHP doesn't support this.
624 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
625 // literal variable name substitution only to keep locale
626 // strings uncluttered
627 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
628 '%1\$s','%s'), E_USER_WARNING); //php+locale error
630 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
633 // Reorder arguments appropriately.
634 foreach($m[1] as $argnum) {
635 if ($argnum < 1 || $argnum > count($args))
636 trigger_error(sprintf(_("%s: argument index out of range"),
637 $argnum), E_USER_WARNING);
638 $newargs[] = $args[$argnum - 1];
643 // Not all PHP's have vsprintf, so...
644 array_unshift($args, $fmt);
645 return call_user_func_array('sprintf', $args);
651 * Build an array in $this->_fileList of files from $dirname.
652 * Subdirectories are not traversed.
654 * (This was a function LoadDir in lib/loadsave.php)
655 * See also http://www.php.net/manual/en/function.readdir.php
657 function getFiles() {
658 return $this->_fileList;
661 function _filenameSelector($filename) {
662 // Default selects all filenames, override as needed.
666 function fileSet($directory) {
667 $this->_fileList = array();
669 if (empty($directory)) {
670 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
672 return; // early return
675 @ $dir_handle = opendir($dir=$directory);
676 if (empty($dir_handle)) {
677 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
678 $dir), E_USER_NOTICE);
679 return; // early return
682 while ($filename = readdir($dir_handle)) {
683 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
685 if ($this->_filenameSelector($filename)) {
686 array_push($this->_fileList, "$filename");
687 //trigger_error(sprintf(_("found file %s"), $filename),
688 // E_USER_NOTICE); //debugging
691 closedir($dir_handle);
696 // Class introspections
698 /** Determine whether object is of a specified type.
700 * @param $object object An object.
701 * @param $class string Class name.
702 * @return bool True iff $object is a $class
703 * or a sub-type of $class.
705 function isa ($object, $class)
707 $lclass = strtolower($class);
709 return is_object($object)
710 && ( get_class($object) == strtolower($lclass)
711 || is_subclass_of($object, $lclass) );
714 /** Determine whether (possible) object has method.
716 * @param $object mixed Object
717 * @param $method string Method name
718 * @return bool True iff $object is an object with has method $method.
720 function can ($object, $method)
722 return is_object($object) && method_exists($object, strtolower($method));
726 * Seed the random number generator.
728 * better_srand() ensures the randomizer is seeded only once.
730 * How random do you want it? See:
731 * http://www.php.net/manual/en/function.srand.php
732 * http://www.php.net/manual/en/function.mt-srand.php
734 function better_srand($seed = '') {
735 static $wascalled = FALSE;
737 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
740 //trigger_error("new random seed", E_USER_NOTICE); //debugging
745 * Recursively count all non-empty elements
746 * in array of any dimension or mixed - i.e.
747 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
748 * See http://www.php.net/manual/en/function.count.php
750 function count_all($arg) {
751 // skip if argument is empty
753 //print_r($arg); //debugging
755 // not an array, return 1 (base case)
758 // else call recursively for all elements $arg
759 foreach($arg as $key => $val)
760 $count += count_all($val);
765 function isSubPage($pagename) {
766 return (strstr($pagename, SUBPAGE_SEPARATOR));
769 function subPageSlice($pagename, $pos) {
770 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
771 $pages = array_slice($pages,$pos,1);
776 // (c-file-style: "gnu")
781 // c-hanging-comment-ender-p: nil
782 // indent-tabs-mode: nil