1 <?php rcs_id('$Id: stdlib.php,v 1.100 2002-02-07 21:17:26 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)
16 class Stack { push($item), pop(), cnt(), top() }
18 split_pagename ($page)
19 NoSuchRevision ($request, $page, $version)
20 TimezoneOffset ($time, $no_colon)
21 Iso8601DateTime ($time)
22 Rfc2822DateTime ($time)
26 __vsprintf ($fmt, $args)
27 better_srand($seed = '')
29 function: LinkInterWikiLink($link, $linktext)
30 moved to: lib/interwiki.php
31 function: linkExistingWikiWord($wikiword, $linktext, $version)
32 moved to: lib/Theme.php
33 function: LinkUnknownWikiWord($wikiword, $linktext)
34 moved to: lib/Theme.php
35 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
36 gone see: lib/plugin/RecentChanges.php
40 function WikiURL($pagename, $args = '', $get_abs_url = false) {
41 if (is_object($pagename)) {
42 if (isa($pagename, 'WikiDB_Page')) {
43 $pagename = $pagename->getName();
45 elseif (isa($pagename, 'WikiDB_PageRevision')) {
46 $page = $pagename->getPage();
47 $args['version'] = $pagename->getVersion();
48 $pagename = $page->getName();
52 if (is_array($args)) {
54 foreach ($args as $key => $val) {
55 $enc_args[] = urlencode($key) . '=' . urlencode($val);
57 $args = join('&', $enc_args);
61 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
62 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
67 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
68 $url .= "?pagename=" . rawurlencode($pagename);
75 function IconForLink($protocol_or_url) {
78 list ($proto) = explode(':', $protocol_or_url, 2);
79 $src = $Theme->getLinkIconURL($proto);
81 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon'));
86 function LinkURL($url, $linktext = '') {
87 // FIXME: Is this needed (or sufficient?)
88 if(ereg("[<>\"]", $url)) {
89 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
90 _("BAD URL -- remove all of <, >, \"")));
93 $link = HTML::a(array('href' => $url),
95 $linktext ? $linktext : $url);
97 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
102 function LinkImage($url, $alt = '[External Image]') {
103 // FIXME: Is this needed (or sufficient?)
104 if(ereg("[<>\"]", $url)) {
105 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
106 _("BAD URL -- remove all of <, >, \"")));
109 $link = HTML::img(array('src' => $url, 'alt' => $alt));
111 $link->setAttr('class', 'inlineimage');
118 var $items = array();
121 function push($item) {
122 $this->items[$this->size] = $item;
128 if ($this->size == 0) {
129 return false; // stack is empty
132 return $this->items[$this->size];
141 return $this->items[$this->size - 1];
147 // end class definition
150 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
151 return HTML::p(HTML::em("MagicPhpWikiURL forms are no longer supported. ",
152 "Use the WikiFormPlugin instead."));
155 function SplitQueryArgs ($query_args = '')
157 $split_args = split('&', $query_args);
159 while (list($key, $val) = each($split_args))
160 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
161 $args[$m[1]] = $m[2];
165 function LinkPhpwikiURL($url, $text = '') {
168 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
169 return HTML::strong(array('class' => 'rawurl'),
170 HTML::u(array('class' => 'baduri'),
171 _("BAD phpwiki: URL")));
175 $pagename = urldecode($m[1]);
178 if (empty($pagename) &&
179 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
180 // Convert old style links (to not break diff links in
182 $pagename = urldecode($m[2]);
183 $args = array("action" => $m[1]);
186 $args = SplitQueryArgs($qargs);
189 if (empty($pagename))
190 $pagename = $GLOBALS['request']->getArg('pagename');
192 if (isset($args['action']) && $args['action'] == 'browse')
193 unset($args['action']);
196 if (empty($args['action']))
198 else if (is_safe_action($args['action']))
199 $class = 'wikiaction';
201 if (empty($args['action']) || is_safe_action($args['action']))
202 $class = 'wikiaction';
204 // Don't allow administrative links on unlocked pages.
205 $page = $GLOBALS['request']->getPage();
206 if (!$page->get('locked'))
207 return HTML::span(array('class' => 'wikiunsafe'),
208 HTML::u(_("Lock page to enable link")));
209 $class = 'wikiadmin';
212 // FIXME: ug, don't like this
213 if (preg_match('/=\d*\(/', $qargs))
214 return MakeWikiForm($pagename, $args, $class, $text);
216 $text = HTML::span(array('class' => 'rawurl'), $url);
218 return HTML::a(array('href' => WikiURL($pagename, $args),
223 function LinkBracketLink($bracketlink) {
224 global $request, $AllowedProtocols, $InlineImages;
226 include_once("lib/interwiki.php");
227 $intermap = InterWikiMap::GetMap($request);
229 // $bracketlink will start and end with brackets; in between will
230 // be either a page name, a URL or both separated by a pipe.
232 // strip brackets and leading space
233 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
234 // match the contents
235 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
237 if (isset($matches[3])) {
238 // named link of the form "[some link name | http://blippy.com/]"
239 $URL = trim($matches[3]);
240 $linkname = trim($matches[1]);
242 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
243 $URL = trim($matches[1]);
247 $dbi = $request->getDbh();
248 if ($dbi->isWikiPage($URL))
249 return WikiLink($URL, 'known', $linkname);
250 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
251 // if it's an image, embed it; otherwise, it's a regular link
252 if (preg_match("/($InlineImages)$/i", $URL))
253 return LinkImage($URL, $linkname);
255 return LinkURL($URL, $linkname);
257 elseif (preg_match("/^phpwiki:/", $URL))
258 return LinkPhpwikiURL($URL, $linkname);
259 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
260 return $intermap->link($URL, $linkname);
262 return WikiLink($URL, 'unknown', $linkname);
267 /* FIXME: this should be done by the transform code */
268 function ExtractWikiPageLinks($content) {
269 global $WikiNameRegexp;
271 if (is_string($content))
272 $content = explode("\n", $content);
274 $wikilinks = array();
275 foreach ($content as $line) {
276 // remove plugin code
277 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
278 // remove escaped '['
279 $line = str_replace('[[', ' ', $line);
281 $line = preg_replace('/[\d+]/', ' ', $line);
283 // bracket links (only type wiki-* is of interest)
284 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
286 for ($i = 0; $i < $numBracketLinks; $i++) {
287 $link = LinkBracketLink($brktlinks[0][$i]);
288 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
289 $wikilinks[$brktlinks[2][$i]] = 1;
291 $brktlink = preg_quote($brktlinks[0][$i]);
292 $line = preg_replace("|$brktlink|", '', $line);
295 // BumpyText old-style wiki links
296 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
297 for ($i = 0; isset($link[0][$i]); $i++) {
298 if($link[0][$i][0] <> '!')
299 $wikilinks[$link[0][$i]] = 1;
303 return array_keys($wikilinks);
307 * Split WikiWords in page names.
309 * It has been deemed useful to split WikiWords (into "Wiki Words") in
310 * places like page titles. This is rumored to help search engines
313 * @param $page string The page name.
315 * @return string The split name.
317 function split_pagename ($page) {
319 if (preg_match("/\s/", $page))
320 return $page; // Already split --- don't split any more.
322 // FIXME: this algorithm is Anglo-centric.
325 // This mess splits between a lower-case letter followed by
326 // either an upper-case or a numeral; except that it wont
327 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
328 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
329 // This the single-letter words 'I' and 'A' from any following
330 // capitalized words.
331 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
332 // Split numerals from following letters.
333 $RE[] = '/(\d)([[:alpha:]])/';
335 foreach ($RE as $key => $val)
336 $RE[$key] = pcre_fix_posix_classes($val);
339 foreach ($RE as $regexp)
340 $page = preg_replace($regexp, '\\1 \\2', $page);
344 function NoSuchRevision (&$request, $page, $version) {
345 $html = HTML(HTML::h2(_("Revision Not Found")),
346 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
347 $version, WikiLink($page, 'auto'))));
348 include_once('lib/Template.php');
349 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
355 * Get time offset for local time zone.
357 * @param $time time_t Get offset for this time. Default: now.
358 * @param $no_colon boolean Don't put colon between hours and minutes.
359 * @return string Offset as a string in the format +HH:MM.
361 function TimezoneOffset ($time = false, $no_colon = false) {
364 $secs = date('Z', $time);
365 return seconds2zoneOffset($secs, $no_colon);
369 * Format a timezone offset from seconds to ±HH:MM format.
371 function seconds2zoneOffset ($secs, $no_colon = false) {
379 $colon = $no_colon ? '' : ':';
380 $mins = intval(($secs + 30) / 60);
381 return sprintf("%s%02d%s%02d",
382 $sign, $mins / 60, $colon, $mins % 60);
386 * Returns the difference between the server's time zone and the
387 * user's time zone in seconds.
389 function PrefTimezoneOffset () {
391 $userOffset = $request->getPref('timeOffset');
392 $serverOffset = TimezoneOffset(false, true);
394 $server_secs = 60 * 60 * (floor($serverOffset/100) + substr($serverOffset,-2)/60);
395 $user_secs = 60 * (floor($userOffset/100)*60 + substr($userOffset,-2));
396 $offset_secs = $user_secs - $server_secs;
401 function istoday($time_secs) {
402 return date("Ymd", time()) == date("Ymd", $time_secs);
404 function isyesterday($time_secs) {
405 return date("Ymd", time()-60*60*24) == date("Ymd", $time_secs);
409 * Format time in ISO-8601 format.
411 * @param $time time_t Time. Default: now.
412 * @return string Date and time in ISO-8601 format.
414 function Iso8601DateTime ($time = false) {
417 $tzoff = TimezoneOffset($time);
418 $date = date('Y-m-d', $time);
419 $time = date('H:i:s', $time);
420 return $date . 'T' . $time . $tzoff;
424 * Format time in RFC-2822 format.
426 * @param $time time_t Time. Default: now.
427 * @return string Date and time in RFC-2822 format.
429 function Rfc2822DateTime ($time = false) {
432 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
436 * Format time to standard 'ctime' format.
438 * @param $time time_t Time. Default: now.
439 * @return string Date and time in RFC-2822 format.
441 function CTime ($time = false)
445 return date("D M j H:i:s Y", $time);
451 * Internationalized printf.
453 * This is essentially the same as PHP's built-in printf
454 * with the following exceptions:
456 * <li> It passes the format string through gettext().
457 * <li> It supports the argument reordering extensions.
464 * __printf("Differences between versions %s and %s of %s",
465 * $new_link, $old_link, $page_link);
468 * Then in locale/po/de.po, one can reorder the printf arguments:
471 * msgid "Differences between %s and %s of %s."
472 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
475 * (Note that while PHP tries to expand $vars within double-quotes,
476 * the values in msgstr undergo no such expansion, so the '$'s
479 * One shouldn't use reordered arguments in the default format string.
480 * Backslashes in the default string would be necessary to escape the
481 * '$'s, and they'll cause all kinds of trouble....
483 function __printf ($fmt) {
484 $args = func_get_args();
486 echo __vsprintf($fmt, $args);
490 * Internationalized sprintf.
492 * This is essentially the same as PHP's built-in printf with the
493 * following exceptions:
496 * <li> It passes the format string through gettext().
497 * <li> It supports the argument reordering extensions.
502 function __sprintf ($fmt) {
503 $args = func_get_args();
505 return __vsprintf($fmt, $args);
509 * Internationalized vsprintf.
511 * This is essentially the same as PHP's built-in printf with the
512 * following exceptions:
515 * <li> It passes the format string through gettext().
516 * <li> It supports the argument reordering extensions.
521 function __vsprintf ($fmt, $args) {
522 $fmt = gettext($fmt);
523 // PHP's sprintf doesn't support variable with specifiers,
524 // like sprintf("%*s", 10, "x"); --- so we won't either.
526 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
527 // Format string has '%2$s' style argument reordering.
528 // PHP doesn't support this.
529 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
530 // literal variable name substitution only to keep locale
531 // strings uncluttered
532 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
533 '%1\$s','%s'), E_USER_WARNING); //php+locale error
535 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
538 // Reorder arguments appropriately.
539 foreach($m[1] as $argnum) {
540 if ($argnum < 1 || $argnum > count($args))
541 trigger_error(sprintf(_("%s: argument index out of range"),
542 $argnum), E_USER_WARNING);
543 $newargs[] = $args[$argnum - 1];
548 // Not all PHP's have vsprintf, so...
549 array_unshift($args, $fmt);
550 return call_user_func_array('sprintf', $args);
556 * Build an array in $this->_fileList of files from $dirname.
557 * Subdirectories are not traversed.
559 * (This was a function LoadDir in lib/loadsave.php)
560 * See also http://www.php.net/manual/en/function.readdir.php
562 function getFiles() {
563 return $this->_fileList;
566 function _filenameSelector($filename) {
567 // Default selects all filenames, override as needed.
571 function fileSet($directory) {
572 $this->_fileList = array();
574 if (empty($directory)) {
575 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
577 return; // early return
580 @ $dir_handle = opendir($dir=$directory);
581 if (empty($dir_handle)) {
582 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
583 $dir), E_USER_NOTICE);
584 return; // early return
587 while ($filename = readdir($dir_handle)) {
588 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
590 if ($this->_filenameSelector($filename)) {
591 array_push($this->_fileList, "$filename");
592 //trigger_error(sprintf(_("found file %s"), $filename),
593 // E_USER_NOTICE); //debugging
596 closedir($dir_handle);
601 // Class introspections
603 /** Determine whether object is of a specified type.
605 * @param $object object An object.
606 * @param $class string Class name.
607 * @return bool True iff $object is a $class
608 * or a sub-type of $class.
610 function isa ($object, $class)
612 $lclass = strtolower($class);
614 return is_object($object)
615 && ( get_class($object) == strtolower($lclass)
616 || is_subclass_of($object, $lclass) );
619 /** Determine whether (possible) object has method.
621 * @param $object mixed Object
622 * @param $method string Method name
623 * @return bool True iff $object is an object with has method $method.
625 function can ($object, $method)
627 return is_object($object) && method_exists($object, strtolower($method));
631 * Seed the random number generator.
633 * better_srand() ensures the randomizer is seeded only once.
635 * How random do you want it? See:
636 * http://www.php.net/manual/en/function.srand.php
637 * http://www.php.net/manual/en/function.mt-srand.php
639 function better_srand($seed = '') {
640 static $wascalled = FALSE;
642 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
645 //trigger_error("new random seed", E_USER_NOTICE); //debugging
649 // (c-file-style: "gnu")
654 // c-hanging-comment-ender-p: nil
655 // indent-tabs-mode: nil