1 <?php rcs_id('$Id: stdlib.php,v 1.83 2002-01-19 20:37:21 carstenklapp Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
7 Element($tag, $args, $content)
8 QElement($tag, $args, $content)
9 IconForLink($protocol_or_url)
10 LinkURL($url, $linktext)
11 LinkWikiWord($wikiword, $linktext)
12 LinkExistingWikiWord($wikiword, $linktext)
14 class Stack { push($item), pop(), cnt(), top() }
15 CookSpaces($pagearray)
16 MakeWikiForm ($pagename, $args, $class, $button_text)
17 SplitQueryArgs ($query_args)
18 LinkPhpwikiURL($url, $text)
19 ParseAndLink($bracketlink)
20 ExtractWikiPageLinks($content)
21 LinkRelatedPages($dbi, $pagename)
22 split_pagename ($page)
23 NoSuchRevision ($page, $version)
24 TimezoneOffset ($time, $no_colon)
25 Iso8601DateTime ($time)
26 Rfc2822DateTime ($time)
30 __vsprintf ($fmt, $args)
32 function moved => LinkInterWikiLink($link, $linktext)
33 (see /lib/interwiki.php)
34 function moved => LinkUnknownWikiWord($wikiword, $linktext)
36 function gone => UpdateRecentChanges($dbi, $pagename, $isnewpage)
37 (see /lib/plugin/RecentChanges.php)
42 function WikiURL($pagename, $args = '', $get_abs_url = false) {
43 if (is_array($args)) {
45 foreach ($args as $key => $val) {
46 $enc_args[] = urlencode($key) . '=' . urlencode($val);
48 $args = join('&', $enc_args);
52 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
53 $url .= rawurlencode($pagename);
58 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
59 $url .= "?pagename=" . rawurlencode($pagename);
66 define('NO_END_TAG_PAT',
67 '/^' . join('|', array('area', 'base', 'basefont',
70 'isindex', 'link', 'meta',
73 function StartTag($tag, $args = '') {
75 if (is_array($args)) {
76 while (list($key, $val) = each($args))
78 if (is_string($val) || is_numeric($val))
79 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
81 $s .= " $key=\"$key\"";
88 function Element($tag, $args = '', $content = '') {
90 if (!is_array($args)) {
94 $html = StartTag($tag, $args);
95 if (preg_match(NO_END_TAG_PAT, $tag)) {
97 return preg_replace('/>$/', " />", $html);
100 $html .= "</$tag>";//FIXME: newline might not always be desired.
105 function QElement($tag, $args = '', $content = '')
108 return Element($tag, $args, htmlspecialchars($content));
111 return Element($tag, htmlspecialchars($content));
115 function IconForLink($protocol_or_url) {
118 list ($proto) = explode(':', $protocol_or_url, 2);
119 $src = $Theme->getLinkIconURL($proto);
123 return Element('img', array('src' => $src,
125 'class' => 'linkicon'));
129 function LinkURL($url, $linktext = '') {
130 // FIXME: Is this needed (or sufficient?)
131 if(ereg("[<>\"]", $url)) {
132 return Element('strong',
133 QElement('u', array('class' => 'baduri'),
134 _("BAD URL -- remove all of <, >, \"")));
137 $attr['href'] = $url;
139 if (empty($linktext)) {
141 $attr['class'] = 'rawurl';
143 $attr['class'] = 'namedurl';
145 return Element('a', $attr,
146 IconForLink($url) . htmlspecialchars($linktext));
149 function LinkWikiWord($wikiword, $linktext = '', $version = false) {
151 if ($dbi->isWikiPage($wikiword))
152 return LinkExistingWikiWord($wikiword, $linktext);
155 return $Theme->LinkUnknownWikiWord($wikiword, $linktext);
158 //This function will be deleted once all references to it are updated.
159 function LinkExistingWikiWord($wikiword, $linktext = '', $version = false) {
161 return $Theme->LinkExistingWikiWord($wikiword, $linktext, $version);
165 function LinkImage($url, $alt = '[External Image]') {
166 // FIXME: Is this needed (or sufficient?)
167 // As long as the src in htmlspecialchars()ed I think it's safe.
168 if(ereg("[<>\"]", $url)) {
169 return Element('strong',
170 QElement('u', array('class' => 'baduri'),
171 _("BAD URL -- remove all of <, >, \"")));
173 return Element('img', array('src' => $url, 'alt' => $alt));
176 // converts spaces to tabs
177 function CookSpaces($pagearray) {
178 return preg_replace("/ {3,8}/", "\t", $pagearray);
183 var $items = array();
186 function push($item) {
187 $this->items[$this->size] = $item;
193 if ($this->size == 0) {
194 return false; // stack is empty
197 return $this->items[$this->size];
206 return $this->items[$this->size - 1];
212 // end class definition
215 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
216 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
217 $formargs['method'] = 'get';
218 $formargs['class'] = $class;
223 while (list($key, $val) = each($args)) {
224 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
226 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
229 $a['size'] = $m[1] ? $m[1] : 30;
234 $formargs['enctype'] = 'multipart/form-data';
235 $contents .= Element('input',
236 array('name' => 'MAX_FILE_SIZE',
237 'value' => MAX_UPLOAD_SIZE,
238 'type' => 'hidden'));
239 $formargs['method'] = 'post';
243 $contents .= Element('input', $a);
246 $row = Element('td', $contents);
248 if (!empty($button_text)) {
249 $row .= Element('td',
250 Element('input', array('type' => 'submit',
252 'value' => $button_text)));
255 return Element('form', $formargs,
256 Element('table', array('cellspacing' => 0,
259 Element('tr', $row)));
262 function SplitQueryArgs ($query_args = '')
264 $split_args = split('&', $query_args);
266 while (list($key, $val) = each($split_args))
267 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
268 $args[$m[1]] = $m[2];
272 function LinkPhpwikiURL($url, $text = '') {
275 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
276 return Element('strong',
277 QElement('u', array('class' => 'baduri'),
278 'BAD phpwiki: URL'));
280 $pagename = urldecode($m[1]);
283 if (empty($pagename) &&
284 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m))
286 // Convert old style links (to not break diff links in
288 $pagename = urldecode($m[2]);
289 $args = array("action" => $m[1]);
292 $args = SplitQueryArgs($qargs);
295 if (empty($pagename))
296 $pagename = $GLOBALS['pagename'];
298 if (isset($args['action']) && $args['action'] == 'browse')
299 unset($args['action']);
301 if (empty($args['action']))
303 else if (is_safe_action($args['action']))
304 $class = 'wikiaction';
306 if (empty($args['action']) || is_safe_action($args['action']))
307 $class = 'wikiaction';
309 // Don't allow administrative links on unlocked pages.
310 // FIXME: Ugh: don't like this...
312 $page = $dbi->getPage($GLOBALS['pagename']);
313 if (!$page->get('locked'))
314 return QElement('u', array('class' => 'wikiunsafe'),
315 _("Lock page to enable link"));
317 $class = 'wikiadmin';
320 // FIXME: ug, don't like this
321 if (preg_match('/=\d*\(/', $qargs))
322 return MakeWikiForm($pagename, $args, $class, $text);
324 $text = htmlspecialchars($text);
326 $text = QElement('span', array('class' => 'rawurl'), $url);
328 return Element('a', array('href' => WikiURL($pagename, $args),
333 function ParseAndLink($bracketlink) {
334 global $dbi, $AllowedProtocols, $InlineImages;
335 global $InterWikiLinkRegexp;
337 // $bracketlink will start and end with brackets; in between will
338 // be either a page name, a URL or both separated by a pipe.
340 // strip brackets and leading space
341 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
342 // match the contents
343 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
345 if (isset($matches[3])) {
346 // named link of the form "[some link name | http://blippy.com/]"
347 $URL = trim($matches[3]);
348 $linkname = trim($matches[1]);
351 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
352 $URL = trim($matches[1]);
354 $linktype = 'simple';
357 if ($dbi->isWikiPage($URL)) {
358 $link['type'] = "wiki-$linktype";
359 $link['link'] = LinkExistingWikiWord($URL, $linkname);
360 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
361 // if it's an image, embed it; otherwise, it's a regular link
362 if (preg_match("/($InlineImages)$/i", $URL)) {
363 $link['type'] = "image-$linktype";
364 $link['link'] = LinkImage($URL, $linkname);
366 $link['type'] = "url-$linktype";
367 $link['link'] = LinkURL($URL, $linkname);
369 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
370 $link['type'] = "url-wiki-$linktype";
371 $link['link'] = LinkPhpwikiURL($URL, $linkname);
372 } elseif (preg_match("#^\d+$#", $URL)) {
373 $link['type'] = "footnote-$linktype";
374 $link['link'] = $URL;
375 } elseif (function_exists('LinkInterWikiLink') &&
376 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
377 $link['type'] = "interwiki-$linktype";
378 $link['link'] = LinkInterWikiLink($URL, $linkname);
380 $link['type'] = "wiki-unknown-$linktype";
382 $link['link'] = $Theme->LinkUnknownWikiWord($URL, $linkname);
389 function ExtractWikiPageLinks($content) {
390 global $WikiNameRegexp;
392 if (is_string($content))
393 $content = explode("\n", $content);
395 $wikilinks = array();
396 foreach ($content as $line) {
397 // remove plugin code
398 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
399 // remove escaped '['
400 $line = str_replace('[[', ' ', $line);
402 // bracket links (only type wiki-* is of interest)
403 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
405 for ($i = 0; $i < $numBracketLinks; $i++) {
406 $link = ParseAndLink($brktlinks[0][$i]);
407 if (preg_match("#^wiki#", $link['type']))
408 $wikilinks[$brktlinks[2][$i]] = 1;
410 $brktlink = preg_quote($brktlinks[0][$i]);
411 $line = preg_replace("|$brktlink|", '', $line);
414 // BumpyText old-style wiki links
415 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
416 for ($i = 0; isset($link[0][$i]); $i++) {
417 if($link[0][$i][0] <> '!')
418 $wikilinks[$link[0][$i]] = 1;
422 return array_keys($wikilinks);
425 function LinkRelatedPages($dbi, $pagename)
427 // currently not supported everywhere
428 if(!function_exists('GetWikiPageLinks'))
431 //FIXME: fix or toss?
432 $links = GetWikiPageLinks($dbi, $pagename);
434 $txt = QElement('strong',
435 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
436 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
437 if(isset($links['in'][$i])) {
438 list($name, $score) = $links['in'][$i];
439 $txt .= LinkExistingWikiWord($name) . " ($score), ";
443 $txt .= "\n" . Element('br');
444 $txt .= Element('strong',
445 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
446 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
447 if(isset($links['out'][$i])) {
448 list($name, $score) = $links['out'][$i];
449 if($dbi->isWikiPage($name))
450 $txt .= LinkExistingWikiWord($name) . " ($score), ";
454 $txt .= "\n" . Element('br');
455 $txt .= Element('strong',
456 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
457 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
458 if(isset($links['popular'][$i])) {
459 list($name, $score) = $links['popular'][$i];
460 $txt .= LinkExistingWikiWord($name) . " ($score), ";
469 * Split WikiWords in page names.
471 * It has been deemed useful to split WikiWords (into "Wiki Words") in
472 * places like page titles. This is rumored to help search engines
475 * @param $page string The page name.
477 * @return string The split name.
479 function split_pagename ($page) {
481 if (preg_match("/\s/", $page))
482 return $page; // Already split --- don't split any more.
484 // FIXME: this algorithm is Anglo-centric.
487 // This mess splits between a lower-case letter followed by
488 // either an upper-case or a numeral; except that it wont
489 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
490 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
491 // This the single-letter words 'I' and 'A' from any following
492 // capitalized words.
493 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
494 // Split numerals from following letters.
495 $RE[] = '/(\d)([[:alpha:]])/';
497 foreach ($RE as $key => $val)
498 $RE[$key] = pcre_fix_posix_classes($val);
501 foreach ($RE as $regexp)
502 $page = preg_replace($regexp, '\\1 \\2', $page);
506 function NoSuchRevision ($page, $version) {
507 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
508 $html .= QElement('p',
509 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
510 $version, $page->getName())) . "\n";
512 include_once('lib/Template.php');
513 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
519 * Get time offset for local time zone.
521 * @param $time time_t Get offset for this time. Default: now.
522 * @param $no_colon boolean Don't put colon between hours and minutes.
523 * @return string Offset as a string in the format +HH:MM.
525 function TimezoneOffset ($time = false, $no_colon = false) {
528 $secs = date('Z', $time);
536 $colon = $no_colon ? '' : ':';
537 $mins = intval(($secs + 30) / 60);
538 return sprintf("%s%02d%s%02d",
539 $sign, $mins / 60, $colon, $mins % 60);
543 * Format time in ISO-8601 format.
545 * @param $time time_t Time. Default: now.
546 * @return string Date and time in ISO-8601 format.
548 function Iso8601DateTime ($time = false) {
551 $tzoff = TimezoneOffset($time);
552 $date = date('Y-m-d', $time);
553 $time = date('H:i:s', $time);
554 return $date . 'T' . $time . $tzoff;
558 * Format time in RFC-2822 format.
560 * @param $time time_t Time. Default: now.
561 * @return string Date and time in RFC-2822 format.
563 function Rfc2822DateTime ($time = false) {
566 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
570 * Format time to standard 'ctime' format.
572 * @param $time time_t Time. Default: now.
573 * @return string Date and time in RFC-2822 format.
575 function CTime ($time = false)
579 return date("D M j H:i:s Y", $time);
585 * Internationalized printf.
587 * This is essentially the same as PHP's built-in printf
588 * with the following exceptions:
590 * <li> It passes the format string through gettext().
591 * <li> It supports the argument reordering extensions.
598 * __printf("Differences between versions %s and %s of %s",
599 * $new_link, $old_link, $page_link);
602 * Then in locale/po/de.po, one can reorder the printf arguments:
605 * msgid "Differences between %s and %s of %s."
606 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
609 * (Note that while PHP tries to expand $vars within double-quotes,
610 * the values in msgstr undergo no such expansion, so the '$'s
613 * One shouldn't use reordered arguments in the default format string.
614 * Backslashes in the default string would be necessary to escape the
615 * '$'s, and they'll cause all kinds of trouble....
617 function __printf ($fmt) {
618 $args = func_get_args();
620 echo __vsprintf($fmt, $args);
624 * Internationalized sprintf.
626 * This is essentially the same as PHP's built-in printf with the
627 * following exceptions:
630 * <li> It passes the format string through gettext().
631 * <li> It supports the argument reordering extensions.
636 function __sprintf ($fmt) {
637 $args = func_get_args();
639 return __vsprintf($fmt, $args);
643 * Internationalized vsprintf.
645 * This is essentially the same as PHP's built-in printf with the
646 * following exceptions:
649 * <li> It passes the format string through gettext().
650 * <li> It supports the argument reordering extensions.
655 function __vsprintf ($fmt, $args) {
656 $fmt = gettext($fmt);
657 // PHP's sprintf doesn't support variable with specifiers,
658 // like sprintf("%*s", 10, "x"); --- so we won't either.
660 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
661 // Format string has '%2$s' style argument reordering.
662 // PHP doesn't support this.
663 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
664 // literal variable name substitution only to keep locale
665 // strings uncluttered
666 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
667 '%1\$s','%s'), E_USER_WARNING);
669 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
672 // Reorder arguments appropriately.
673 foreach($m[1] as $argnum) {
674 if ($argnum < 1 || $argnum > count($args))
675 trigger_error(sprintf(_("%s: argument index out of range"),
676 $argnum), E_USER_WARNING);
677 $newargs[] = $args[$argnum - 1];
682 // Not all PHP's have vsprintf, so...
683 array_unshift($args, $fmt);
684 return call_user_func_array('sprintf', $args);
688 // Class introspections
690 /** Determine whether object is of a specified type.
692 * @param $object object An object.
693 * @param $class string Class name.
694 * @return bool True iff $object is a $class
695 * or a sub-type of $class.
697 function isa ($object, $class)
699 $lclass = strtolower($class);
701 return get_class($object) == strtolower($lclass)
702 || is_subclass_of($object, $lclass);
705 // (c-file-style: "gnu")
710 // c-hanging-comment-ender-p: nil
711 // indent-tabs-mode: nil