1 <?php rcs_id('$Id: stdlib.php,v 1.98 2002-02-03 19:03:44 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)
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 $form = HTML::form(array('action' => USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME,
154 'accept-charset' => CHARSET));
157 while (list($key, $val) = each($args)) {
158 $i = HTML::input(array('name' => $key, 'value' => $val, 'type' => 'hidden'));
160 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
161 $i->setAttr('size', $m[1] ? $m[1] : 30);
162 $i->setAttr('value', $m[2]);
164 $i->setAttr('type', 'text');
167 $i->setAttr('type', 'file');
168 $form->setAttr('enctype', 'multipart/form-data');
169 $form->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
170 'value' => MAX_UPLOAD_SIZE,
171 'type' => 'hidden')));
172 $form->setAttr('method', 'post');
174 $td->pushContent($i);
177 $form->pushContent($i);
182 if (!empty($button_text))
183 $tr->pushContent(HTML::td(HTML::input(array('type' => 'submit',
185 'value' => $button_text))));
186 $form->pushContent(HTML::table(array('cellspacing' => 0,
193 function SplitQueryArgs ($query_args = '')
195 $split_args = split('&', $query_args);
197 while (list($key, $val) = each($split_args))
198 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
199 $args[$m[1]] = $m[2];
203 function LinkPhpwikiURL($url, $text = '') {
206 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
207 return HTML::strong(array('class' => 'rawurl'),
208 HTML::u(array('class' => 'baduri'),
209 _("BAD phpwiki: URL")));
213 $pagename = urldecode($m[1]);
216 if (empty($pagename) &&
217 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
218 // Convert old style links (to not break diff links in
220 $pagename = urldecode($m[2]);
221 $args = array("action" => $m[1]);
224 $args = SplitQueryArgs($qargs);
227 if (empty($pagename))
228 $pagename = $GLOBALS['request']->getArg('pagename');
230 if (isset($args['action']) && $args['action'] == 'browse')
231 unset($args['action']);
234 if (empty($args['action']))
236 else if (is_safe_action($args['action']))
237 $class = 'wikiaction';
239 if (empty($args['action']) || is_safe_action($args['action']))
240 $class = 'wikiaction';
242 // Don't allow administrative links on unlocked pages.
243 $page = $GLOBALS['request']->getPage();
244 if (!$page->get('locked'))
245 return HTML::span(array('class' => 'wikiunsafe'),
246 HTML::u(_("Lock page to enable link")));
247 $class = 'wikiadmin';
250 // FIXME: ug, don't like this
251 if (preg_match('/=\d*\(/', $qargs))
252 return MakeWikiForm($pagename, $args, $class, $text);
254 $text = HTML::span(array('class' => 'rawurl'), $url);
256 return HTML::a(array('href' => WikiURL($pagename, $args),
261 function LinkBracketLink($bracketlink) {
262 global $request, $AllowedProtocols, $InlineImages;
264 include_once("lib/interwiki.php");
265 $intermap = InterWikiMap::GetMap($request);
267 // $bracketlink will start and end with brackets; in between will
268 // be either a page name, a URL or both separated by a pipe.
270 // strip brackets and leading space
271 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
272 // match the contents
273 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
275 if (isset($matches[3])) {
276 // named link of the form "[some link name | http://blippy.com/]"
277 $URL = trim($matches[3]);
278 $linkname = trim($matches[1]);
280 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
281 $URL = trim($matches[1]);
285 $dbi = $request->getDbh();
286 if ($dbi->isWikiPage($URL))
287 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 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 $wikilinks[$brktlinks[2][$i]] = 1;
329 $brktlink = preg_quote($brktlinks[0][$i]);
330 $line = preg_replace("|$brktlink|", '', $line);
333 // BumpyText old-style wiki links
334 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
335 for ($i = 0; isset($link[0][$i]); $i++) {
336 if($link[0][$i][0] <> '!')
337 $wikilinks[$link[0][$i]] = 1;
341 return array_keys($wikilinks);
345 * Split WikiWords in page names.
347 * It has been deemed useful to split WikiWords (into "Wiki Words") in
348 * places like page titles. This is rumored to help search engines
351 * @param $page string The page name.
353 * @return string The split name.
355 function split_pagename ($page) {
357 if (preg_match("/\s/", $page))
358 return $page; // Already split --- don't split any more.
360 // FIXME: this algorithm is Anglo-centric.
363 // This mess splits between a lower-case letter followed by
364 // either an upper-case or a numeral; except that it wont
365 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
366 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
367 // This the single-letter words 'I' and 'A' from any following
368 // capitalized words.
369 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
370 // Split numerals from following letters.
371 $RE[] = '/(\d)([[:alpha:]])/';
373 foreach ($RE as $key => $val)
374 $RE[$key] = pcre_fix_posix_classes($val);
377 foreach ($RE as $regexp)
378 $page = preg_replace($regexp, '\\1 \\2', $page);
382 function NoSuchRevision (&$request, $page, $version) {
383 $html = HTML(HTML::h2(_("Revision Not Found")),
384 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
385 $version, WikiLink($page, 'auto'))));
386 include_once('lib/Template.php');
387 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
393 * Get time offset for local time zone.
395 * @param $time time_t Get offset for this time. Default: now.
396 * @param $no_colon boolean Don't put colon between hours and minutes.
397 * @return string Offset as a string in the format +HH:MM.
399 function TimezoneOffset ($time = false, $no_colon = false) {
402 $secs = date('Z', $time);
403 return seconds2zoneOffset($secs, $no_colon);
407 * Format a timezone offset from seconds to ±HH:MM format.
409 function seconds2zoneOffset ($secs, $no_colon = false) {
417 $colon = $no_colon ? '' : ':';
418 $mins = intval(($secs + 30) / 60);
419 return sprintf("%s%02d%s%02d",
420 $sign, $mins / 60, $colon, $mins % 60);
424 * Returns the difference between the server's time zone and the
425 * user's time zone in seconds.
427 function PrefTimezoneOffset () {
429 $userOffset = $request->getPref('timeOffset');
430 $serverOffset = TimezoneOffset(false, true);
432 $server_secs = 60 * 60 * (floor($serverOffset/100) + substr($serverOffset,-2)/60);
433 $user_secs = 60 * (floor($userOffset/100)*60 + substr($userOffset,-2));
434 $offset_secs = $user_secs - $server_secs;
440 * Format time in ISO-8601 format.
442 * @param $time time_t Time. Default: now.
443 * @return string Date and time in ISO-8601 format.
445 function Iso8601DateTime ($time = false) {
448 $tzoff = TimezoneOffset($time);
449 $date = date('Y-m-d', $time);
450 $time = date('H:i:s', $time);
451 return $date . 'T' . $time . $tzoff;
455 * Format time in RFC-2822 format.
457 * @param $time time_t Time. Default: now.
458 * @return string Date and time in RFC-2822 format.
460 function Rfc2822DateTime ($time = false) {
463 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
467 * Format time to standard 'ctime' format.
469 * @param $time time_t Time. Default: now.
470 * @return string Date and time in RFC-2822 format.
472 function CTime ($time = false)
476 return date("D M j H:i:s Y", $time);
482 * Internationalized printf.
484 * This is essentially the same as PHP's built-in printf
485 * with the following exceptions:
487 * <li> It passes the format string through gettext().
488 * <li> It supports the argument reordering extensions.
495 * __printf("Differences between versions %s and %s of %s",
496 * $new_link, $old_link, $page_link);
499 * Then in locale/po/de.po, one can reorder the printf arguments:
502 * msgid "Differences between %s and %s of %s."
503 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
506 * (Note that while PHP tries to expand $vars within double-quotes,
507 * the values in msgstr undergo no such expansion, so the '$'s
510 * One shouldn't use reordered arguments in the default format string.
511 * Backslashes in the default string would be necessary to escape the
512 * '$'s, and they'll cause all kinds of trouble....
514 function __printf ($fmt) {
515 $args = func_get_args();
517 echo __vsprintf($fmt, $args);
521 * Internationalized sprintf.
523 * This is essentially the same as PHP's built-in printf with the
524 * following exceptions:
527 * <li> It passes the format string through gettext().
528 * <li> It supports the argument reordering extensions.
533 function __sprintf ($fmt) {
534 $args = func_get_args();
536 return __vsprintf($fmt, $args);
540 * Internationalized vsprintf.
542 * This is essentially the same as PHP's built-in printf with the
543 * following exceptions:
546 * <li> It passes the format string through gettext().
547 * <li> It supports the argument reordering extensions.
552 function __vsprintf ($fmt, $args) {
553 $fmt = gettext($fmt);
554 // PHP's sprintf doesn't support variable with specifiers,
555 // like sprintf("%*s", 10, "x"); --- so we won't either.
557 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
558 // Format string has '%2$s' style argument reordering.
559 // PHP doesn't support this.
560 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
561 // literal variable name substitution only to keep locale
562 // strings uncluttered
563 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
564 '%1\$s','%s'), E_USER_WARNING); //php+locale error
566 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
569 // Reorder arguments appropriately.
570 foreach($m[1] as $argnum) {
571 if ($argnum < 1 || $argnum > count($args))
572 trigger_error(sprintf(_("%s: argument index out of range"),
573 $argnum), E_USER_WARNING);
574 $newargs[] = $args[$argnum - 1];
579 // Not all PHP's have vsprintf, so...
580 array_unshift($args, $fmt);
581 return call_user_func_array('sprintf', $args);
587 * Build an array in $this->_fileList of files from $dirname.
588 * Subdirectories are not traversed.
590 * (This was a function LoadDir in lib/loadsave.php)
591 * See also http://www.php.net/manual/en/function.readdir.php
593 function getFiles() {
594 return $this->_fileList;
597 function _filenameSelector($filename) {
598 // Default selects all filenames, override as needed.
602 function fileSet($directory) {
603 $this->_fileList = array();
605 if (empty($directory)) {
606 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
608 return; // early return
611 @ $dir_handle = opendir($dir=$directory);
612 if (empty($dir_handle)) {
613 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
614 $dir), E_USER_NOTICE);
615 return; // early return
618 while ($filename = readdir($dir_handle)) {
619 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
621 if ($this->_filenameSelector($filename)) {
622 array_push($this->_fileList, "$filename");
623 //trigger_error(sprintf(_("found file %s"), $filename),
624 // E_USER_NOTICE); //debugging
627 closedir($dir_handle);
632 // Class introspections
634 /** Determine whether object is of a specified type.
636 * @param $object object An object.
637 * @param $class string Class name.
638 * @return bool True iff $object is a $class
639 * or a sub-type of $class.
641 function isa ($object, $class)
643 $lclass = strtolower($class);
645 return is_object($object)
646 && ( get_class($object) == strtolower($lclass)
647 || is_subclass_of($object, $lclass) );
650 /** Determine whether (possible) object has method.
652 * @param $object mixed Object
653 * @param $method string Method name
654 * @return bool True iff $object is an object with has method $method.
656 function can ($object, $method)
658 return is_object($object) && method_exists($object, strtolower($method));
662 * Seed the random number generator.
664 * better_srand() ensures the randomizer is seeded only once.
666 * How random do you want it? See:
667 * http://www.php.net/manual/en/function.srand.php
668 * http://www.php.net/manual/en/function.mt-srand.php
670 function better_srand($seed = '') {
671 static $wascalled = FALSE;
673 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
676 //trigger_error("new random seed", E_USER_NOTICE); //debugging
680 // (c-file-style: "gnu")
685 // c-hanging-comment-ender-p: nil
686 // indent-tabs-mode: nil