1 <?php rcs_id('$Id: stdlib.php,v 1.115 2002-08-24 13:18:56 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 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
57 $enc_args[] = urlencode($key) . '=' . urlencode($val);
59 $args = join('&', $enc_args);
63 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
64 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
69 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
70 $url .= "?pagename=" . rawurlencode($pagename);
77 function IconForLink($protocol_or_url) {
79 if ($filename_suffix = false) {
80 // display apache style icon for file type instead of protocol icon
81 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
82 // - document: html, htm, text, txt, rtf, pdf, doc
83 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
84 // - audio: mp3,mp2,aiff,aif,au
85 // - multimedia: mpeg,mpg,mov,qt
87 list ($proto) = explode(':', $protocol_or_url, 2);
88 $src = $Theme->getLinkIconURL($proto);
90 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
96 function LinkURL($url, $linktext = '') {
97 // FIXME: Is this needed (or sufficient?)
98 if(ereg("[<>\"]", $url)) {
99 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
100 _("BAD URL -- remove all of <, >, \"")));
104 $linktext = preg_replace("/mailto:/A", "", $url);
106 $link = HTML::a(array('href' => $url),
107 IconForLink($url), $linktext);
110 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
115 function LinkImage($url, $alt = false) {
116 // FIXME: Is this needed (or sufficient?)
117 if(ereg("[<>\"]", $url)) {
118 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
119 _("BAD URL -- remove all of <, >, \"")));
124 $link = HTML::img(array('src' => $url, 'alt' => $alt));
126 $link->setAttr('class', 'inlineimage');
133 var $items = array();
136 function push($item) {
137 $this->items[$this->size] = $item;
143 if ($this->size == 0) {
144 return false; // stack is empty
147 return $this->items[$this->size];
156 return $this->items[$this->size - 1];
162 // end class definition
165 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
166 // HACK: so as to not completely break old PhpWikiAdministration pages.
167 trigger_error("MagicPhpWikiURL forms are no longer supported. "
168 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
171 $loader = new WikiPluginLoader;
172 @$action = (string)$args['action'];
173 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
176 function SplitQueryArgs ($query_args = '')
178 $split_args = split('&', $query_args);
180 while (list($key, $val) = each($split_args))
181 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
182 $args[$m[1]] = $m[2];
186 function LinkPhpwikiURL($url, $text = '') {
189 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
190 return HTML::strong(array('class' => 'rawurl'),
191 HTML::u(array('class' => 'baduri'),
192 _("BAD phpwiki: URL")));
196 $pagename = urldecode($m[1]);
199 if (empty($pagename) &&
200 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
201 // Convert old style links (to not break diff links in
203 $pagename = urldecode($m[2]);
204 $args = array("action" => $m[1]);
207 $args = SplitQueryArgs($qargs);
210 if (empty($pagename))
211 $pagename = $GLOBALS['request']->getArg('pagename');
213 if (isset($args['action']) && $args['action'] == 'browse')
214 unset($args['action']);
217 if (empty($args['action']))
219 else if (is_safe_action($args['action']))
220 $class = 'wikiaction';
222 if (empty($args['action']) || is_safe_action($args['action']))
223 $class = 'wikiaction';
225 // Don't allow administrative links on unlocked pages.
226 $page = $GLOBALS['request']->getPage();
227 if (!$page->get('locked'))
228 return HTML::span(array('class' => 'wikiunsafe'),
229 HTML::u(_("Lock page to enable link")));
230 $class = 'wikiadmin';
233 // FIXME: ug, don't like this
234 if (preg_match('/=\d*\(/', $qargs))
235 return MakeWikiForm($pagename, $args, $class, $text);
237 $text = HTML::span(array('class' => 'rawurl'), $url);
239 return HTML::a(array('href' => WikiURL($pagename, $args),
244 function LinkBracketLink($bracketlink) {
245 global $request, $AllowedProtocols, $InlineImages;
247 include_once("lib/interwiki.php");
248 $intermap = InterWikiMap::GetMap($request);
250 // $bracketlink will start and end with brackets; in between will
251 // be either a page name, a URL or both separated by a pipe.
253 // strip brackets and leading space
254 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
255 // match the contents
256 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
258 if (isset($matches[3])) {
259 // named link of the form "[some link name | http://blippy.com/]"
260 $URL = trim($matches[3]);
261 $linkname = trim($matches[1]);
263 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
264 $URL = trim($matches[1]);
268 $dbi = $request->getDbh();
269 if (substr($URL,0,1) == SUBPAGE_SEPARATOR) { // relative link to page below
270 if (!$linkname) $linkname = $URL;
271 $URL = $request->getArg('pagename') . $URL;
273 if ($dbi->isWikiPage($URL)) {
274 // if it's an image, it's an named image link [img|link]
275 if (preg_match("/($InlineImages)$/i", $linkname))
276 if (preg_match("#^($AllowedProtocols):#", $URL)) {
277 return WikiLink($URL, 'known', LinkImage($linkname,$URL));
280 // linkname like 'images/next.gif'.
282 return WikiLink($URL, 'known', LinkImage($Theme->getImageURL($linkname),$URL));
285 return WikiLink($URL, 'known', $linkname);
288 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
289 // if it's an image, embed it; otherwise, it's a regular link
290 if (preg_match("/($InlineImages)$/i", $URL))
291 // no image link, just the src. see [img|link] above
292 return LinkImage($URL, $linkname);
294 return LinkURL($URL, $linkname);
296 elseif (preg_match("/^phpwiki:/", $URL))
297 return LinkPhpwikiURL($URL, $linkname);
298 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
299 return $intermap->link($URL, $linkname);
301 return WikiLink($URL, 'unknown', $linkname);
306 /* FIXME: this should be done by the transform code */
307 function ExtractWikiPageLinks($content) {
308 global $WikiNameRegexp;
310 if (is_string($content))
311 $content = explode("\n", $content);
313 $wikilinks = array();
314 foreach ($content as $line) {
315 // remove plugin code
316 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
317 // remove escaped '['
318 $line = str_replace('[[', ' ', $line);
320 $line = preg_replace('/[\d+]/', ' ', $line);
322 // bracket links (only type wiki-* is of interest)
323 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
325 for ($i = 0; $i < $numBracketLinks; $i++) {
326 $link = LinkBracketLink($brktlinks[0][$i]);
327 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
328 if ($brktlinks[2][$i][0] == SUBPAGE_SEPARATOR) {
330 $wikilinks[$request->getArg('pagename') . $brktlinks[2][$i]] = 1;
332 $wikilinks[$brktlinks[2][$i]] = 1;
335 $brktlink = preg_quote($brktlinks[0][$i]);
336 $line = preg_replace("|$brktlink|", '', $line);
339 // BumpyText old-style wiki links
340 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
341 for ($i = 0; isset($link[0][$i]); $i++) {
342 if($link[0][$i][0] <> '!') {
343 if ($link[0][$i][0] == SUBPAGE_SEPARATOR) {
345 $wikilinks[$request->getArg('pagename') . $link[0][$i]] = 1;
347 $wikilinks[$link[0][$i]] = 1;
353 return array_keys($wikilinks);
357 * Convert old page markup to new-style markup.
359 * @param $text string Old-style wiki markup.
361 * @param $just_links bool Only convert old-style links.
362 * (Really this only converts escaped old-style links.)
364 * @return string New-style wiki markup.
366 * @bugs FIXME: footnotes and old-style tables are known to be broken.
368 function ConvertOldMarkup ($text, $just_links = false) {
370 static $orig, $repl, $link_orig, $link_repl;
373 /*****************************************************************
374 * Conversions for inline markup:
381 // escape escaped brackets
385 // change ! escapes to ~'s.
386 global $AllowedProtocols, $WikiNameRegexp, $request;
387 include_once('lib/interwiki.php');
388 $map = InterWikiMap::GetMap($request);
389 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
390 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
391 $bang_esc[] = $WikiNameRegexp;
392 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
399 /*****************************************************************
400 * Conversions for block markup
402 // convert indented blocks to <pre></pre>.
403 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
404 $repl[] = "<pre>\n\\0</pre>\n";
407 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
408 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
413 return preg_replace($link_orig, $link_repl, $text);
415 return preg_replace($orig, $repl, $text);
418 function _ConvertOldListMarkup ($indent, $bullet) {
419 $indent = str_repeat(' ', strlen($indent));
420 if ($bullet[0] == ';') {
421 $term = ltrim(substr($bullet, 1));
422 return $indent . $term . "\n" . $indent . ' ';
425 return $indent . $bullet . ' ';
431 * Split WikiWords in page names.
433 * It has been deemed useful to split WikiWords (into "Wiki Words") in
434 * places like page titles. This is rumored to help search engines
437 * @param $page string The page name.
439 * @return string The split name.
441 function split_pagename ($page) {
443 if (preg_match("/\s/", $page))
444 return $page; // Already split --- don't split any more.
446 // FIXME: this algorithm is Anglo-centric.
449 // This mess splits between a lower-case letter followed by
450 // either an upper-case or a numeral; except that it wont
451 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
452 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
453 // This the single-letter words 'I' and 'A' from any following
454 // capitalized words.
455 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
456 // Split numerals from following letters.
457 $RE[] = '/(\d)([[:alpha:]])/';
459 foreach ($RE as $key => $val)
460 $RE[$key] = pcre_fix_posix_classes($val);
463 foreach ($RE as $regexp)
464 $page = preg_replace($regexp, '\\1 \\2', $page);
468 function NoSuchRevision (&$request, $page, $version) {
469 $html = HTML(HTML::h2(_("Revision Not Found")),
470 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
471 $version, WikiLink($page, 'auto'))));
472 include_once('lib/Template.php');
473 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
479 * Get time offset for local time zone.
481 * @param $time time_t Get offset for this time. Default: now.
482 * @param $no_colon boolean Don't put colon between hours and minutes.
483 * @return string Offset as a string in the format +HH:MM.
485 function TimezoneOffset ($time = false, $no_colon = false) {
488 $secs = date('Z', $time);
497 $colon = $no_colon ? '' : ':';
498 $mins = intval(($secs + 30) / 60);
499 return sprintf("%s%02d%s%02d",
500 $sign, $mins / 60, $colon, $mins % 60);
505 * Format time in ISO-8601 format.
507 * @param $time time_t Time. Default: now.
508 * @return string Date and time in ISO-8601 format.
510 function Iso8601DateTime ($time = false) {
513 $tzoff = TimezoneOffset($time);
514 $date = date('Y-m-d', $time);
515 $time = date('H:i:s', $time);
516 return $date . 'T' . $time . $tzoff;
520 * Format time in RFC-2822 format.
522 * @param $time time_t Time. Default: now.
523 * @return string Date and time in RFC-2822 format.
525 function Rfc2822DateTime ($time = false) {
528 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
532 * Format time to standard 'ctime' format.
534 * @param $time time_t Time. Default: now.
535 * @return string Date and time.
537 function CTime ($time = false)
541 return date("D M j H:i:s Y", $time);
547 * Internationalized printf.
549 * This is essentially the same as PHP's built-in printf
550 * with the following exceptions:
552 * <li> It passes the format string through gettext().
553 * <li> It supports the argument reordering extensions.
560 * __printf("Differences between versions %s and %s of %s",
561 * $new_link, $old_link, $page_link);
564 * Then in locale/po/de.po, one can reorder the printf arguments:
567 * msgid "Differences between %s and %s of %s."
568 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
571 * (Note that while PHP tries to expand $vars within double-quotes,
572 * the values in msgstr undergo no such expansion, so the '$'s
575 * One shouldn't use reordered arguments in the default format string.
576 * Backslashes in the default string would be necessary to escape the
577 * '$'s, and they'll cause all kinds of trouble....
579 function __printf ($fmt) {
580 $args = func_get_args();
582 echo __vsprintf($fmt, $args);
586 * Internationalized sprintf.
588 * This is essentially the same as PHP's built-in printf with the
589 * following exceptions:
592 * <li> It passes the format string through gettext().
593 * <li> It supports the argument reordering extensions.
598 function __sprintf ($fmt) {
599 $args = func_get_args();
601 return __vsprintf($fmt, $args);
605 * Internationalized vsprintf.
607 * This is essentially the same as PHP's built-in printf with the
608 * following exceptions:
611 * <li> It passes the format string through gettext().
612 * <li> It supports the argument reordering extensions.
617 function __vsprintf ($fmt, $args) {
618 $fmt = gettext($fmt);
619 // PHP's sprintf doesn't support variable with specifiers,
620 // like sprintf("%*s", 10, "x"); --- so we won't either.
622 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
623 // Format string has '%2$s' style argument reordering.
624 // PHP doesn't support this.
625 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
626 // literal variable name substitution only to keep locale
627 // strings uncluttered
628 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
629 '%1\$s','%s'), E_USER_WARNING); //php+locale error
631 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
634 // Reorder arguments appropriately.
635 foreach($m[1] as $argnum) {
636 if ($argnum < 1 || $argnum > count($args))
637 trigger_error(sprintf(_("%s: argument index out of range"),
638 $argnum), E_USER_WARNING);
639 $newargs[] = $args[$argnum - 1];
644 // Not all PHP's have vsprintf, so...
645 array_unshift($args, $fmt);
646 return call_user_func_array('sprintf', $args);
652 * Build an array in $this->_fileList of files from $dirname.
653 * Subdirectories are not traversed.
655 * (This was a function LoadDir in lib/loadsave.php)
656 * See also http://www.php.net/manual/en/function.readdir.php
658 function getFiles() {
659 return $this->_fileList;
662 function _filenameSelector($filename) {
663 // Default selects all filenames, override as needed.
667 function fileSet($directory) {
668 $this->_fileList = array();
670 if (empty($directory)) {
671 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
673 return; // early return
676 @ $dir_handle = opendir($dir=$directory);
677 if (empty($dir_handle)) {
678 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
679 $dir), E_USER_NOTICE);
680 return; // early return
683 while ($filename = readdir($dir_handle)) {
684 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
686 if ($this->_filenameSelector($filename)) {
687 array_push($this->_fileList, "$filename");
688 //trigger_error(sprintf(_("found file %s"), $filename),
689 // E_USER_NOTICE); //debugging
692 closedir($dir_handle);
697 // Class introspections
699 /** Determine whether object is of a specified type.
701 * @param $object object An object.
702 * @param $class string Class name.
703 * @return bool True iff $object is a $class
704 * or a sub-type of $class.
706 function isa ($object, $class)
708 $lclass = strtolower($class);
710 return is_object($object)
711 && ( get_class($object) == strtolower($lclass)
712 || is_subclass_of($object, $lclass) );
715 /** Determine whether (possible) object has method.
717 * @param $object mixed Object
718 * @param $method string Method name
719 * @return bool True iff $object is an object with has method $method.
721 function can ($object, $method)
723 return is_object($object) && method_exists($object, strtolower($method));
727 * Seed the random number generator.
729 * better_srand() ensures the randomizer is seeded only once.
731 * How random do you want it? See:
732 * http://www.php.net/manual/en/function.srand.php
733 * http://www.php.net/manual/en/function.mt-srand.php
735 function better_srand($seed = '') {
736 static $wascalled = FALSE;
738 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
741 //trigger_error("new random seed", E_USER_NOTICE); //debugging
746 * Recursively count all non-empty elements
747 * in array of any dimension or mixed - i.e.
748 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
749 * See http://www.php.net/manual/en/function.count.php
751 function count_all($arg) {
752 // skip if argument is empty
754 //print_r($arg); //debugging
756 // not an array, return 1 (base case)
759 // else call recursively for all elements $arg
760 foreach($arg as $key => $val)
761 $count += count_all($val);
766 function isSubPage($pagename) {
767 return (strstr($pagename, SUBPAGE_SEPARATOR));
770 function subPageSlice($pagename, $pos) {
771 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
772 $pages = array_slice($pages,$pos,1);
777 // (c-file-style: "gnu")
782 // c-hanging-comment-ender-p: nil
783 // indent-tabs-mode: nil