1 <?php rcs_id('$Id: stdlib.php,v 1.107 2002-02-08 17:49:37 carstenklapp 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 <, >, \"")));
102 $link = HTML::a(array('href' => $url/*, 'type' => 'application/x-gzip'*/),
103 // do any browsers support use of <a href= type=?/?
104 // (instead of wiki creating an IconForLink for the doc type?)
106 $linktext ? $linktext : str_replace("mailto:", "", $url));
108 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
113 function LinkImage($url, $alt = '[External Image]') {
114 // FIXME: Is this needed (or sufficient?)
115 if(ereg("[<>\"]", $url)) {
116 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
117 _("BAD URL -- remove all of <, >, \"")));
120 $link = HTML::img(array('src' => $url, 'alt' => $alt));
122 $link->setAttr('class', 'inlineimage');
129 var $items = array();
132 function push($item) {
133 $this->items[$this->size] = $item;
139 if ($this->size == 0) {
140 return false; // stack is empty
143 return $this->items[$this->size];
152 return $this->items[$this->size - 1];
158 // end class definition
161 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
162 // HACK: so as to not completely break old PhpWikiAdministration pages.
163 trigger_error("MagicPhpWikiURL forms are no longer supported. "
164 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
167 $loader = new WikiPluginLoader;
168 @$action = (string)$args['action'];
169 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
172 function SplitQueryArgs ($query_args = '')
174 $split_args = split('&', $query_args);
176 while (list($key, $val) = each($split_args))
177 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
178 $args[$m[1]] = $m[2];
182 function LinkPhpwikiURL($url, $text = '') {
185 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
186 return HTML::strong(array('class' => 'rawurl'),
187 HTML::u(array('class' => 'baduri'),
188 _("BAD phpwiki: URL")));
192 $pagename = urldecode($m[1]);
195 if (empty($pagename) &&
196 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
197 // Convert old style links (to not break diff links in
199 $pagename = urldecode($m[2]);
200 $args = array("action" => $m[1]);
203 $args = SplitQueryArgs($qargs);
206 if (empty($pagename))
207 $pagename = $GLOBALS['request']->getArg('pagename');
209 if (isset($args['action']) && $args['action'] == 'browse')
210 unset($args['action']);
213 if (empty($args['action']))
215 else if (is_safe_action($args['action']))
216 $class = 'wikiaction';
218 if (empty($args['action']) || is_safe_action($args['action']))
219 $class = 'wikiaction';
221 // Don't allow administrative links on unlocked pages.
222 $page = $GLOBALS['request']->getPage();
223 if (!$page->get('locked'))
224 return HTML::span(array('class' => 'wikiunsafe'),
225 HTML::u(_("Lock page to enable link")));
226 $class = 'wikiadmin';
229 // FIXME: ug, don't like this
230 if (preg_match('/=\d*\(/', $qargs))
231 return MakeWikiForm($pagename, $args, $class, $text);
233 $text = HTML::span(array('class' => 'rawurl'), $url);
235 return HTML::a(array('href' => WikiURL($pagename, $args),
240 function LinkBracketLink($bracketlink) {
241 global $request, $AllowedProtocols, $InlineImages;
243 include_once("lib/interwiki.php");
244 $intermap = InterWikiMap::GetMap($request);
246 // $bracketlink will start and end with brackets; in between will
247 // be either a page name, a URL or both separated by a pipe.
249 // strip brackets and leading space
250 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
251 // match the contents
252 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
254 if (isset($matches[3])) {
255 // named link of the form "[some link name | http://blippy.com/]"
256 $URL = trim($matches[3]);
257 $linkname = trim($matches[1]);
259 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
260 $URL = trim($matches[1]);
264 $dbi = $request->getDbh();
265 if ($dbi->isWikiPage($URL))
266 return WikiLink($URL, 'known', $linkname);
267 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
268 // if it's an image, embed it; otherwise, it's a regular link
269 if (preg_match("/($InlineImages)$/i", $URL))
270 return LinkImage($URL, $linkname);
272 return LinkURL($URL, $linkname);
274 elseif (preg_match("/^phpwiki:/", $URL))
275 return LinkPhpwikiURL($URL, $linkname);
276 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
277 return $intermap->link($URL, $linkname);
279 return WikiLink($URL, 'unknown', $linkname);
284 /* FIXME: this should be done by the transform code */
285 function ExtractWikiPageLinks($content) {
286 global $WikiNameRegexp;
288 if (is_string($content))
289 $content = explode("\n", $content);
291 $wikilinks = array();
292 foreach ($content as $line) {
293 // remove plugin code
294 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
295 // remove escaped '['
296 $line = str_replace('[[', ' ', $line);
298 $line = preg_replace('/[\d+]/', ' ', $line);
300 // bracket links (only type wiki-* is of interest)
301 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
303 for ($i = 0; $i < $numBracketLinks; $i++) {
304 $link = LinkBracketLink($brktlinks[0][$i]);
305 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
306 $wikilinks[$brktlinks[2][$i]] = 1;
308 $brktlink = preg_quote($brktlinks[0][$i]);
309 $line = preg_replace("|$brktlink|", '', $line);
312 // BumpyText old-style wiki links
313 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
314 for ($i = 0; isset($link[0][$i]); $i++) {
315 if($link[0][$i][0] <> '!')
316 $wikilinks[$link[0][$i]] = 1;
320 return array_keys($wikilinks);
324 * Convert old page markup to new-style markup.
326 * @param $text string Old-style wiki markup.
328 * @param $just_links bool Only convert old-style links.
329 * (Really this only converts escaped old-style links.)
331 * @return string New-style wiki markup.
333 * @bugs FIXME: footnotes and old-style tables are known to be broken.
335 function ConvertOldMarkup ($text, $just_links = false) {
337 static $orig, $repl, $link_orig, $link_repl;
340 /*****************************************************************
341 * Conversions for inline markup:
348 // escape escaped brackets
352 // change ! escapes to ~'s.
353 global $AllowedProtocols, $WikiNameRegexp, $request;
354 include_once('lib/interwiki.php');
355 $map = InterWikiMap::GetMap($request);
356 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
357 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
358 $bang_esc[] = $WikiNameRegexp;
359 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
366 /*****************************************************************
367 * Conversions for block markup
369 // convert indented blocks to <pre></pre>.
370 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
371 $repl[] = "<pre>\n\\0</pre>\n";
374 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
375 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
380 return preg_replace($link_orig, $link_repl, $text);
382 return preg_replace($orig, $repl, $text);
385 function _ConvertOldListMarkup ($indent, $bullet) {
386 $indent = str_repeat(' ', strlen($indent));
387 if ($bullet[0] == ';') {
388 $term = ltrim(substr($bullet, 1));
389 return $indent . $term . "\n" . $indent . ' ';
392 return $indent . $bullet . ' ';
398 * Split WikiWords in page names.
400 * It has been deemed useful to split WikiWords (into "Wiki Words") in
401 * places like page titles. This is rumored to help search engines
404 * @param $page string The page name.
406 * @return string The split name.
408 function split_pagename ($page) {
410 if (preg_match("/\s/", $page))
411 return $page; // Already split --- don't split any more.
413 // FIXME: this algorithm is Anglo-centric.
416 // This mess splits between a lower-case letter followed by
417 // either an upper-case or a numeral; except that it wont
418 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
419 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
420 // This the single-letter words 'I' and 'A' from any following
421 // capitalized words.
422 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
423 // Split numerals from following letters.
424 $RE[] = '/(\d)([[:alpha:]])/';
426 foreach ($RE as $key => $val)
427 $RE[$key] = pcre_fix_posix_classes($val);
430 foreach ($RE as $regexp)
431 $page = preg_replace($regexp, '\\1 \\2', $page);
435 function NoSuchRevision (&$request, $page, $version) {
436 $html = HTML(HTML::h2(_("Revision Not Found")),
437 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
438 $version, WikiLink($page, 'auto'))));
439 include_once('lib/Template.php');
440 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
446 * Get time offset for local time zone.
448 * @param $time time_t Get offset for this time. Default: now.
449 * @param $no_colon boolean Don't put colon between hours and minutes.
450 * @return string Offset as a string in the format +HH:MM.
452 function TimezoneOffset ($time = false, $no_colon = false) {
455 $secs = date('Z', $time);
456 return seconds2zoneOffset($secs, $no_colon);
460 * Format a timezone offset from seconds to ±HH:MM format.
462 function seconds2zoneOffset ($secs, $no_colon = false) {
470 $colon = $no_colon ? '' : ':';
471 $mins = intval(($secs + 30) / 60);
472 return sprintf("%s%02d%s%02d",
473 $sign, $mins / 60, $colon, $mins % 60);
477 * Returns the user's offset time in seconds.
479 function PrefTimezoneOffset () {
481 $userOffset = $request->getPref('timeOffset');
482 $offset_secs = 60 * (floor($userOffset/100)*60 + substr($userOffset,-2));
486 function istoday($time_secs) {
487 return date("Ymd", time()) == date("Ymd", $time_secs);
489 function isyesterday($time_secs) {
490 return date("Ymd", time()-60*60*24) == date("Ymd", $time_secs);
494 * Format time in ISO-8601 format.
496 * @param $time time_t Time. Default: now.
497 * @return string Date and time in ISO-8601 format.
499 function Iso8601DateTime ($time = false) {
502 $tzoff = TimezoneOffset($time);
503 $date = date('Y-m-d', $time);
504 $time = date('H:i:s', $time);
505 return $date . 'T' . $time . $tzoff;
509 * Format time in RFC-2822 format.
511 * @param $time time_t Time. Default: now.
512 * @return string Date and time in RFC-2822 format.
514 function Rfc2822DateTime ($time = false) {
517 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
521 * Format time to standard 'ctime' format.
523 * @param $time time_t Time. Default: now.
524 * @return string Date and time.
526 function CTime ($time = false)
530 return date("D M j H:i:s Y", $time);
536 * Internationalized printf.
538 * This is essentially the same as PHP's built-in printf
539 * with the following exceptions:
541 * <li> It passes the format string through gettext().
542 * <li> It supports the argument reordering extensions.
549 * __printf("Differences between versions %s and %s of %s",
550 * $new_link, $old_link, $page_link);
553 * Then in locale/po/de.po, one can reorder the printf arguments:
556 * msgid "Differences between %s and %s of %s."
557 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
560 * (Note that while PHP tries to expand $vars within double-quotes,
561 * the values in msgstr undergo no such expansion, so the '$'s
564 * One shouldn't use reordered arguments in the default format string.
565 * Backslashes in the default string would be necessary to escape the
566 * '$'s, and they'll cause all kinds of trouble....
568 function __printf ($fmt) {
569 $args = func_get_args();
571 echo __vsprintf($fmt, $args);
575 * Internationalized sprintf.
577 * This is essentially the same as PHP's built-in printf with the
578 * following exceptions:
581 * <li> It passes the format string through gettext().
582 * <li> It supports the argument reordering extensions.
587 function __sprintf ($fmt) {
588 $args = func_get_args();
590 return __vsprintf($fmt, $args);
594 * Internationalized vsprintf.
596 * This is essentially the same as PHP's built-in printf with the
597 * following exceptions:
600 * <li> It passes the format string through gettext().
601 * <li> It supports the argument reordering extensions.
606 function __vsprintf ($fmt, $args) {
607 $fmt = gettext($fmt);
608 // PHP's sprintf doesn't support variable with specifiers,
609 // like sprintf("%*s", 10, "x"); --- so we won't either.
611 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
612 // Format string has '%2$s' style argument reordering.
613 // PHP doesn't support this.
614 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
615 // literal variable name substitution only to keep locale
616 // strings uncluttered
617 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
618 '%1\$s','%s'), E_USER_WARNING); //php+locale error
620 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
623 // Reorder arguments appropriately.
624 foreach($m[1] as $argnum) {
625 if ($argnum < 1 || $argnum > count($args))
626 trigger_error(sprintf(_("%s: argument index out of range"),
627 $argnum), E_USER_WARNING);
628 $newargs[] = $args[$argnum - 1];
633 // Not all PHP's have vsprintf, so...
634 array_unshift($args, $fmt);
635 return call_user_func_array('sprintf', $args);
641 * Build an array in $this->_fileList of files from $dirname.
642 * Subdirectories are not traversed.
644 * (This was a function LoadDir in lib/loadsave.php)
645 * See also http://www.php.net/manual/en/function.readdir.php
647 function getFiles() {
648 return $this->_fileList;
651 function _filenameSelector($filename) {
652 // Default selects all filenames, override as needed.
656 function fileSet($directory) {
657 $this->_fileList = array();
659 if (empty($directory)) {
660 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
662 return; // early return
665 @ $dir_handle = opendir($dir=$directory);
666 if (empty($dir_handle)) {
667 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
668 $dir), E_USER_NOTICE);
669 return; // early return
672 while ($filename = readdir($dir_handle)) {
673 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
675 if ($this->_filenameSelector($filename)) {
676 array_push($this->_fileList, "$filename");
677 //trigger_error(sprintf(_("found file %s"), $filename),
678 // E_USER_NOTICE); //debugging
681 closedir($dir_handle);
686 // Class introspections
688 /** Determine whether object is of a specified type.
690 * @param $object object An object.
691 * @param $class string Class name.
692 * @return bool True iff $object is a $class
693 * or a sub-type of $class.
695 function isa ($object, $class)
697 $lclass = strtolower($class);
699 return is_object($object)
700 && ( get_class($object) == strtolower($lclass)
701 || is_subclass_of($object, $lclass) );
704 /** Determine whether (possible) object has method.
706 * @param $object mixed Object
707 * @param $method string Method name
708 * @return bool True iff $object is an object with has method $method.
710 function can ($object, $method)
712 return is_object($object) && method_exists($object, strtolower($method));
716 * Seed the random number generator.
718 * better_srand() ensures the randomizer is seeded only once.
720 * How random do you want it? See:
721 * http://www.php.net/manual/en/function.srand.php
722 * http://www.php.net/manual/en/function.mt-srand.php
724 function better_srand($seed = '') {
725 static $wascalled = FALSE;
727 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
730 //trigger_error("new random seed", E_USER_NOTICE); //debugging
734 // (c-file-style: "gnu")
739 // c-hanging-comment-ender-p: nil
740 // indent-tabs-mode: nil