1 <?php rcs_id('$Id: stdlib.php,v 1.103 2002-02-08 03:17:09 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 = '')
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) {
79 list ($proto) = explode(':', $protocol_or_url, 2);
80 $src = $Theme->getLinkIconURL($proto);
82 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon'));
87 function LinkURL($url, $linktext = '') {
88 // FIXME: Is this needed (or sufficient?)
89 if(ereg("[<>\"]", $url)) {
90 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
91 _("BAD URL -- remove all of <, >, \"")));
94 $link = HTML::a(array('href' => $url),
96 $linktext ? $linktext : $url);
98 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
103 function LinkImage($url, $alt = '[External Image]') {
104 // FIXME: Is this needed (or sufficient?)
105 if(ereg("[<>\"]", $url)) {
106 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
107 _("BAD URL -- remove all of <, >, \"")));
110 $link = HTML::img(array('src' => $url, 'alt' => $alt));
112 $link->setAttr('class', 'inlineimage');
119 var $items = array();
122 function push($item) {
123 $this->items[$this->size] = $item;
129 if ($this->size == 0) {
130 return false; // stack is empty
133 return $this->items[$this->size];
142 return $this->items[$this->size - 1];
148 // end class definition
151 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
152 return HTML::p(HTML::em("MagicPhpWikiURL forms are no longer supported. ",
153 "Use the WikiFormPlugin instead."));
156 function SplitQueryArgs ($query_args = '')
158 $split_args = split('&', $query_args);
160 while (list($key, $val) = each($split_args))
161 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
162 $args[$m[1]] = $m[2];
166 function LinkPhpwikiURL($url, $text = '') {
169 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
170 return HTML::strong(array('class' => 'rawurl'),
171 HTML::u(array('class' => 'baduri'),
172 _("BAD phpwiki: URL")));
176 $pagename = urldecode($m[1]);
179 if (empty($pagename) &&
180 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
181 // Convert old style links (to not break diff links in
183 $pagename = urldecode($m[2]);
184 $args = array("action" => $m[1]);
187 $args = SplitQueryArgs($qargs);
190 if (empty($pagename))
191 $pagename = $GLOBALS['request']->getArg('pagename');
193 if (isset($args['action']) && $args['action'] == 'browse')
194 unset($args['action']);
197 if (empty($args['action']))
199 else if (is_safe_action($args['action']))
200 $class = 'wikiaction';
202 if (empty($args['action']) || is_safe_action($args['action']))
203 $class = 'wikiaction';
205 // Don't allow administrative links on unlocked pages.
206 $page = $GLOBALS['request']->getPage();
207 if (!$page->get('locked'))
208 return HTML::span(array('class' => 'wikiunsafe'),
209 HTML::u(_("Lock page to enable link")));
210 $class = 'wikiadmin';
213 // FIXME: ug, don't like this
214 if (preg_match('/=\d*\(/', $qargs))
215 return MakeWikiForm($pagename, $args, $class, $text);
217 $text = HTML::span(array('class' => 'rawurl'), $url);
219 return HTML::a(array('href' => WikiURL($pagename, $args),
224 function LinkBracketLink($bracketlink) {
225 global $request, $AllowedProtocols, $InlineImages;
227 include_once("lib/interwiki.php");
228 $intermap = InterWikiMap::GetMap($request);
230 // $bracketlink will start and end with brackets; in between will
231 // be either a page name, a URL or both separated by a pipe.
233 // strip brackets and leading space
234 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
235 // match the contents
236 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
238 if (isset($matches[3])) {
239 // named link of the form "[some link name | http://blippy.com/]"
240 $URL = trim($matches[3]);
241 $linkname = trim($matches[1]);
243 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
244 $URL = trim($matches[1]);
248 $dbi = $request->getDbh();
249 if ($dbi->isWikiPage($URL))
250 return WikiLink($URL, 'known', $linkname);
251 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
252 // if it's an image, embed it; otherwise, it's a regular link
253 if (preg_match("/($InlineImages)$/i", $URL))
254 return LinkImage($URL, $linkname);
256 return LinkURL($URL, $linkname);
258 elseif (preg_match("/^phpwiki:/", $URL))
259 return LinkPhpwikiURL($URL, $linkname);
260 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
261 return $intermap->link($URL, $linkname);
263 return WikiLink($URL, 'unknown', $linkname);
268 /* FIXME: this should be done by the transform code */
269 function ExtractWikiPageLinks($content) {
270 global $WikiNameRegexp;
272 if (is_string($content))
273 $content = explode("\n", $content);
275 $wikilinks = array();
276 foreach ($content as $line) {
277 // remove plugin code
278 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
279 // remove escaped '['
280 $line = str_replace('[[', ' ', $line);
282 $line = preg_replace('/[\d+]/', ' ', $line);
284 // bracket links (only type wiki-* is of interest)
285 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
287 for ($i = 0; $i < $numBracketLinks; $i++) {
288 $link = LinkBracketLink($brktlinks[0][$i]);
289 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
290 $wikilinks[$brktlinks[2][$i]] = 1;
292 $brktlink = preg_quote($brktlinks[0][$i]);
293 $line = preg_replace("|$brktlink|", '', $line);
296 // BumpyText old-style wiki links
297 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
298 for ($i = 0; isset($link[0][$i]); $i++) {
299 if($link[0][$i][0] <> '!')
300 $wikilinks[$link[0][$i]] = 1;
304 return array_keys($wikilinks);
308 * Convert old page markup to new-style markup.
310 * @param $text string Old-style wiki markup.
312 * @param $just_links bool Only convert old-style links.
313 * (Really this only converts escaped old-style links.)
315 * @return string New-style wiki markup.
317 * @bugs FIXME: footnotes and old-style tables are known to be broken.
319 function ConvertOldMarkup ($text, $just_links = false) {
321 static $orig, $repl, $link_orig, $link_repl;
324 /*****************************************************************
325 * Conversions for inline markup:
332 // escape escaped brackets
336 // change ! escapes to ~'s.
337 global $AllowedProtocols, $WikiNameRegexp, $request;
338 include_once('lib/interwiki.php');
339 $map = InterWikiMap::GetMap($request);
340 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
341 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
342 $bang_esc[] = $WikiNameRegexp;
343 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
350 /*****************************************************************
351 * Conversions for block markup
353 // convert indented blocks to <pre></pre>.
354 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
355 $repl[] = "<pre>\n\\0</pre>\n";
358 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
359 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
364 return preg_replace($link_orig, $link_repl, $text);
366 return preg_replace($orig, $repl, $text);
369 function _ConvertOldListMarkup ($indent, $bullet) {
370 $indent = str_repeat(' ', strlen($indent));
371 if ($bullet[0] == ';') {
372 $term = ltrim(substr($bullet, 1));
373 return $indent . $term . "\n" . $indent . ' ';
376 return $indent . $bullet . ' ';
382 * Split WikiWords in page names.
384 * It has been deemed useful to split WikiWords (into "Wiki Words") in
385 * places like page titles. This is rumored to help search engines
388 * @param $page string The page name.
390 * @return string The split name.
392 function split_pagename ($page) {
394 if (preg_match("/\s/", $page))
395 return $page; // Already split --- don't split any more.
397 // FIXME: this algorithm is Anglo-centric.
400 // This mess splits between a lower-case letter followed by
401 // either an upper-case or a numeral; except that it wont
402 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
403 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
404 // This the single-letter words 'I' and 'A' from any following
405 // capitalized words.
406 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
407 // Split numerals from following letters.
408 $RE[] = '/(\d)([[:alpha:]])/';
410 foreach ($RE as $key => $val)
411 $RE[$key] = pcre_fix_posix_classes($val);
414 foreach ($RE as $regexp)
415 $page = preg_replace($regexp, '\\1 \\2', $page);
419 function NoSuchRevision (&$request, $page, $version) {
420 $html = HTML(HTML::h2(_("Revision Not Found")),
421 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
422 $version, WikiLink($page, 'auto'))));
423 include_once('lib/Template.php');
424 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
430 * Get time offset for local time zone.
432 * @param $time time_t Get offset for this time. Default: now.
433 * @param $no_colon boolean Don't put colon between hours and minutes.
434 * @return string Offset as a string in the format +HH:MM.
436 function TimezoneOffset ($time = false, $no_colon = false) {
439 $secs = date('Z', $time);
440 return seconds2zoneOffset($secs, $no_colon);
444 * Format a timezone offset from seconds to ±HH:MM format.
446 function seconds2zoneOffset ($secs, $no_colon = false) {
454 $colon = $no_colon ? '' : ':';
455 $mins = intval(($secs + 30) / 60);
456 return sprintf("%s%02d%s%02d",
457 $sign, $mins / 60, $colon, $mins % 60);
461 * Returns the difference between the server's time zone and the
462 * user's time zone in seconds.
464 function PrefTimezoneOffset () {
466 $userOffset = $request->getPref('timeOffset');
467 $serverOffset = TimezoneOffset(false, true);
469 $server_secs = 60 * 60 * (floor($serverOffset/100) + substr($serverOffset,-2)/60);
470 $user_secs = 60 * (floor($userOffset/100)*60 + substr($userOffset,-2));
471 $offset_secs = $user_secs - $server_secs;
476 function istoday($time_secs) {
477 return date("Ymd", time()) == date("Ymd", $time_secs);
479 function isyesterday($time_secs) {
480 return date("Ymd", time()-60*60*24) == date("Ymd", $time_secs);
484 * Format time in ISO-8601 format.
486 * @param $time time_t Time. Default: now.
487 * @return string Date and time in ISO-8601 format.
489 function Iso8601DateTime ($time = false) {
492 $tzoff = TimezoneOffset($time);
493 $date = date('Y-m-d', $time);
494 $time = date('H:i:s', $time);
495 return $date . 'T' . $time . $tzoff;
499 * Format time in RFC-2822 format.
501 * @param $time time_t Time. Default: now.
502 * @return string Date and time in RFC-2822 format.
504 function Rfc2822DateTime ($time = false) {
507 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
511 * Format time to standard 'ctime' format.
513 * @param $time time_t Time. Default: now.
514 * @return string Date and time.
516 function CTime ($time = false)
520 return date("D M j H:i:s Y", $time);
526 * Internationalized printf.
528 * This is essentially the same as PHP's built-in printf
529 * with the following exceptions:
531 * <li> It passes the format string through gettext().
532 * <li> It supports the argument reordering extensions.
539 * __printf("Differences between versions %s and %s of %s",
540 * $new_link, $old_link, $page_link);
543 * Then in locale/po/de.po, one can reorder the printf arguments:
546 * msgid "Differences between %s and %s of %s."
547 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
550 * (Note that while PHP tries to expand $vars within double-quotes,
551 * the values in msgstr undergo no such expansion, so the '$'s
554 * One shouldn't use reordered arguments in the default format string.
555 * Backslashes in the default string would be necessary to escape the
556 * '$'s, and they'll cause all kinds of trouble....
558 function __printf ($fmt) {
559 $args = func_get_args();
561 echo __vsprintf($fmt, $args);
565 * Internationalized sprintf.
567 * This is essentially the same as PHP's built-in printf with the
568 * following exceptions:
571 * <li> It passes the format string through gettext().
572 * <li> It supports the argument reordering extensions.
577 function __sprintf ($fmt) {
578 $args = func_get_args();
580 return __vsprintf($fmt, $args);
584 * Internationalized vsprintf.
586 * This is essentially the same as PHP's built-in printf with the
587 * following exceptions:
590 * <li> It passes the format string through gettext().
591 * <li> It supports the argument reordering extensions.
596 function __vsprintf ($fmt, $args) {
597 $fmt = gettext($fmt);
598 // PHP's sprintf doesn't support variable with specifiers,
599 // like sprintf("%*s", 10, "x"); --- so we won't either.
601 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
602 // Format string has '%2$s' style argument reordering.
603 // PHP doesn't support this.
604 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
605 // literal variable name substitution only to keep locale
606 // strings uncluttered
607 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
608 '%1\$s','%s'), E_USER_WARNING); //php+locale error
610 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
613 // Reorder arguments appropriately.
614 foreach($m[1] as $argnum) {
615 if ($argnum < 1 || $argnum > count($args))
616 trigger_error(sprintf(_("%s: argument index out of range"),
617 $argnum), E_USER_WARNING);
618 $newargs[] = $args[$argnum - 1];
623 // Not all PHP's have vsprintf, so...
624 array_unshift($args, $fmt);
625 return call_user_func_array('sprintf', $args);
631 * Build an array in $this->_fileList of files from $dirname.
632 * Subdirectories are not traversed.
634 * (This was a function LoadDir in lib/loadsave.php)
635 * See also http://www.php.net/manual/en/function.readdir.php
637 function getFiles() {
638 return $this->_fileList;
641 function _filenameSelector($filename) {
642 // Default selects all filenames, override as needed.
646 function fileSet($directory) {
647 $this->_fileList = array();
649 if (empty($directory)) {
650 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
652 return; // early return
655 @ $dir_handle = opendir($dir=$directory);
656 if (empty($dir_handle)) {
657 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
658 $dir), E_USER_NOTICE);
659 return; // early return
662 while ($filename = readdir($dir_handle)) {
663 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
665 if ($this->_filenameSelector($filename)) {
666 array_push($this->_fileList, "$filename");
667 //trigger_error(sprintf(_("found file %s"), $filename),
668 // E_USER_NOTICE); //debugging
671 closedir($dir_handle);
676 // Class introspections
678 /** Determine whether object is of a specified type.
680 * @param $object object An object.
681 * @param $class string Class name.
682 * @return bool True iff $object is a $class
683 * or a sub-type of $class.
685 function isa ($object, $class)
687 $lclass = strtolower($class);
689 return is_object($object)
690 && ( get_class($object) == strtolower($lclass)
691 || is_subclass_of($object, $lclass) );
694 /** Determine whether (possible) object has method.
696 * @param $object mixed Object
697 * @param $method string Method name
698 * @return bool True iff $object is an object with has method $method.
700 function can ($object, $method)
702 return is_object($object) && method_exists($object, strtolower($method));
706 * Seed the random number generator.
708 * better_srand() ensures the randomizer is seeded only once.
710 * How random do you want it? See:
711 * http://www.php.net/manual/en/function.srand.php
712 * http://www.php.net/manual/en/function.mt-srand.php
714 function better_srand($seed = '') {
715 static $wascalled = FALSE;
717 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
720 //trigger_error("new random seed", E_USER_NOTICE); //debugging
724 // (c-file-style: "gnu")
729 // c-hanging-comment-ender-p: nil
730 // indent-tabs-mode: nil