1 <?php rcs_id('$Id: stdlib.php,v 1.71 2002-01-11 04:06:56 carstenklapp Exp $');
4 Standard functions for Wiki functionality
7 WikiURL($pagename, $args, $get_abs_url)
8 CSS_URL($CSS_URLS, $CSS_DEFAULT)
10 Element($tag, $args, $content)
11 QElement($tag, $args, $content)
12 IconForLink($protocol_or_url)
13 LinkURL($url, $linktext)
14 LinkWikiWord($wikiword, $linktext)
15 LinkExistingWikiWord($wikiword, $linktext)
16 LinkUnknownWikiWord($wikiword, $linktext)
18 class Stack { push($item), pop(), cnt(), top() }
19 CookSpaces($pagearray)
20 MakeWikiForm ($pagename, $args, $class, $button_text)
21 SplitQueryArgs ($query_args)
22 LinkPhpwikiURL($url, $text)
23 ParseAndLink($bracketlink)
24 ExtractWikiPageLinks($content)
25 LinkRelatedPages($dbi, $pagename)
26 split_pagename ($page)
27 NoSuchRevision ($page, $version)
28 TimezoneOffset ($time, $no_colon)
29 Iso8601DateTime ($time)
30 Rfc2822DateTime ($time)
34 __vsprintf ($fmt, $args)
36 function moved => LinkInterWikiLink($link, $linktext)
37 (see /lib/interwiki.php)
38 function gone => UpdateRecentChanges($dbi, $pagename, $isnewpage)
39 (see /lib/plugin/RecentChanges.php)
44 function DataURL($url) {
45 if (preg_match('@^(\w+:|/)@', $url))
47 return SERVER_URL . DATA_PATH . "/$url";
51 return SERVER_URL . DATA_PATH . "/";
54 function WikiURL($pagename, $args = '', $get_abs_url = false) {
55 if (is_array($args)) {
57 foreach ($args as $key => $val) {
58 $enc_args[] = urlencode($key) . '=' . urlencode($val);
60 $args = join('&', $enc_args);
65 SERVER_URL . VIRTUAL_PATH . "/" : VIRTUAL_PATH . "/";
66 $url .= rawurlencode($pagename);
71 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
72 $url .= "?pagename=" . rawurlencode($pagename);
79 function CSS_URL($CSS_URLS, $CSS_DEFAULT) {
81 foreach ($CSS_URLS as $key => $val) {
82 $css = array('rel' => (($CSS_DEFAULT == $key) ?
83 'stylesheet' : 'alternate stylesheet'),
84 'title' => htmlspecialchars(_($key)),
85 'href' => DataURL(htmlspecialchars($val)),
87 'charset' => CHARSET);
88 // The next line is also used by xgettext to localise the word
89 // "Printer" used in the stylesheet's 'title' (see above).
90 if ($key == _("Printer")) {
91 $css = array_merge($css, array('media' => 'print'));
93 $html .= QElement('link', $css) ."\n";
98 define('NO_END_TAG_PAT',
99 '/^' . join('|', array('area', 'base', 'basefont',
100 'br', 'col', 'frame',
101 'hr', 'img', 'input',
102 'isindex', 'link', 'meta',
105 function StartTag($tag, $args = '') {
107 if (is_array($args)) {
108 while (list($key, $val) = each($args))
110 if (is_string($val) || is_numeric($val))
111 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
113 $s .= " $key=\"$key\"";
120 function Element($tag, $args = '', $content = '') {
122 if (!is_array($args)) {
126 $html = StartTag($tag, $args);
127 if (preg_match(NO_END_TAG_PAT, $tag)) {
129 return preg_replace('/>$/', " />", $html);
132 $html .= "</$tag>";//FIXME: newline might not always be desired.
137 function QElement($tag, $args = '', $content = '')
140 return Element($tag, $args, htmlspecialchars($content));
143 return Element($tag, htmlspecialchars($content));
147 function IconForLink($protocol_or_url) {
148 global $URL_LINK_ICONS;
150 list ($proto) = explode(':', $protocol_or_url, 2);
152 if (isset($URL_LINK_ICONS[$proto])) {
153 $linkimg = $URL_LINK_ICONS[$proto];
155 elseif (isset($URL_LINK_ICONS['*'])) {
156 $linkimg = $URL_LINK_ICONS['*'];
162 return Element('img', array('src' => DataURL($linkimg),
164 'class' => 'linkicon'));
168 function LinkURL($url, $linktext = '') {
169 // FIXME: Is this needed (or sufficient?)
170 if(ereg("[<>\"]", $url)) {
171 return Element('strong',
172 QElement('u', array('class' => 'baduri'),
173 _("BAD URL -- remove all of <, >, \"")));
176 $attr['href'] = $url;
178 if (empty($linktext)) {
180 $attr['class'] = 'rawurl';
182 $attr['class'] = 'namedurl';
184 return Element('a', $attr,
185 IconForLink($url) . htmlspecialchars($linktext));
188 function LinkWikiWord($wikiword, $linktext = '') {
190 if ($dbi->isWikiPage($wikiword))
191 return LinkExistingWikiWord($wikiword, $linktext);
193 return LinkUnknownWikiWord($wikiword, $linktext);
196 function LinkExistingWikiWord($wikiword, $linktext = '') {
197 if (empty($linktext)) {
198 $linktext = $wikiword;
199 if (defined("autosplit_wikiwords"))
200 $linktext=split_pagename($linktext);
203 $class = 'named-wiki';
205 return QElement('a', array('href' => WikiURL($wikiword),
210 function LinkUnknownWikiWord($wikiword, $linktext = '') {
211 if (empty($linktext)) {
212 $linktext = $wikiword;
213 if (defined("autosplit_wikiwords"))
214 $linktext=split_pagename($linktext);
215 $class = 'wikiunknown';
217 $class = 'named-wikiunknown';
219 return Element('span', array('class' => $class),
221 array('href' => WikiURL($wikiword,
222 array('action' => 'edit'))),
223 '?') . Element('u', $linktext));
226 function LinkImage($url, $alt = '[External Image]') {
227 // FIXME: Is this needed (or sufficient?)
228 // As long as the src in htmlspecialchars()ed I think it's safe.
229 if(ereg("[<>\"]", $url)) {
230 return Element('strong',
231 QElement('u', array('class' => 'baduri'),
232 _("BAD URL -- remove all of <, >, \"")));
234 return Element('img', array('src' => $url, 'alt' => $alt));
237 // converts spaces to tabs
238 function CookSpaces($pagearray) {
239 return preg_replace("/ {3,8}/", "\t", $pagearray);
244 var $items = array();
247 function push($item) {
248 $this->items[$this->size] = $item;
254 if ($this->size == 0) {
255 return false; // stack is empty
258 return $this->items[$this->size];
267 return $this->items[$this->size - 1];
273 // end class definition
276 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
277 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
278 $formargs['method'] = 'get';
279 $formargs['class'] = $class;
284 while (list($key, $val) = each($args)) {
285 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
287 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
290 $a['size'] = $m[1] ? $m[1] : 30;
295 $formargs['enctype'] = 'multipart/form-data';
296 $contents .= Element('input',
297 array('name' => 'MAX_FILE_SIZE',
298 'value' => MAX_UPLOAD_SIZE,
299 'type' => 'hidden'));
300 $formargs['method'] = 'post';
304 $contents .= Element('input', $a);
307 $row = Element('td', $contents);
309 if (!empty($button_text)) {
310 $row .= Element('td',
311 Element('input', array('type' => 'submit',
313 'value' => $button_text)));
316 return Element('form', $formargs,
317 Element('table', array('cellspacing' => 0,
320 Element('tr', $row)));
323 function SplitQueryArgs ($query_args = '')
325 $split_args = split('&', $query_args);
327 while (list($key, $val) = each($split_args))
328 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
329 $args[$m[1]] = $m[2];
333 function LinkPhpwikiURL($url, $text = '') {
336 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
337 return Element('strong',
338 QElement('u', array('class' => 'baduri'),
339 'BAD phpwiki: URL'));
341 $pagename = urldecode($m[1]);
344 if (empty($pagename) &&
345 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m))
347 // Convert old style links (to not break diff links in
349 $pagename = urldecode($m[2]);
350 $args = array("action" => $m[1]);
353 $args = SplitQueryArgs($qargs);
356 if (empty($pagename))
357 $pagename = $GLOBALS['pagename'];
359 if (isset($args['action']) && $args['action'] == 'browse')
360 unset($args['action']);
362 if (empty($args['action']))
364 else if (is_safe_action($args['action']))
365 $class = 'wikiaction';
367 if (empty($args['action']) || is_safe_action($args['action']))
368 $class = 'wikiaction';
370 // Don't allow administrative links on unlocked pages.
371 // FIXME: Ugh: don't like this...
373 $page = $dbi->getPage($GLOBALS['pagename']);
374 if (!$page->get('locked'))
375 return QElement('u', array('class' => 'wikiunsafe'),
376 _("Lock page to enable link"));
378 $class = 'wikiadmin';
381 // FIXME: ug, don't like this
382 if (preg_match('/=\d*\(/', $qargs))
383 return MakeWikiForm($pagename, $args, $class, $text);
385 $text = htmlspecialchars($text);
387 $text = QElement('span', array('class' => 'rawurl'), $url);
389 return Element('a', array('href' => WikiURL($pagename, $args),
394 function ParseAndLink($bracketlink) {
395 global $dbi, $AllowedProtocols, $InlineImages;
396 global $InterWikiLinkRegexp;
398 // $bracketlink will start and end with brackets; in between will
399 // be either a page name, a URL or both separated by a pipe.
401 // strip brackets and leading space
402 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
403 // match the contents
404 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
406 if (isset($matches[3])) {
407 // named link of the form "[some link name | http://blippy.com/]"
408 $URL = trim($matches[3]);
409 $linkname = trim($matches[1]);
412 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
413 $URL = trim($matches[1]);
415 $linktype = 'simple';
418 if ($dbi->isWikiPage($URL)) {
419 $link['type'] = "wiki-$linktype";
420 $link['link'] = LinkExistingWikiWord($URL, $linkname);
421 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
422 // if it's an image, embed it; otherwise, it's a regular link
423 if (preg_match("/($InlineImages)$/i", $URL)) {
424 $link['type'] = "image-$linktype";
425 $link['link'] = LinkImage($URL, $linkname);
427 $link['type'] = "url-$linktype";
428 $link['link'] = LinkURL($URL, $linkname);
430 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
431 $link['type'] = "url-wiki-$linktype";
432 $link['link'] = LinkPhpwikiURL($URL, $linkname);
433 } elseif (preg_match("#^\d+$#", $URL)) {
434 $link['type'] = "footnote-$linktype";
435 $link['link'] = $URL;
436 } elseif (function_exists('LinkInterWikiLink') &&
437 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
438 $link['type'] = "interwiki-$linktype";
439 $link['link'] = LinkInterWikiLink($URL, $linkname);
441 $link['type'] = "wiki-unknown-$linktype";
442 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
449 function ExtractWikiPageLinks($content) {
450 global $WikiNameRegexp;
452 if (is_string($content))
453 $content = explode("\n", $content);
455 $wikilinks = array();
456 foreach ($content as $line) {
457 // remove plugin code
458 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
459 // remove escaped '['
460 $line = str_replace('[[', ' ', $line);
462 // bracket links (only type wiki-* is of interest)
463 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
465 for ($i = 0; $i < $numBracketLinks; $i++) {
466 $link = ParseAndLink($brktlinks[0][$i]);
467 if (preg_match("#^wiki#", $link['type']))
468 $wikilinks[$brktlinks[2][$i]] = 1;
470 $brktlink = preg_quote($brktlinks[0][$i]);
471 $line = preg_replace("|$brktlink|", '', $line);
474 // BumpyText old-style wiki links
475 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
476 for ($i = 0; isset($link[0][$i]); $i++) {
477 if($link[0][$i][0] <> '!')
478 $wikilinks[$link[0][$i]] = 1;
482 return array_keys($wikilinks);
485 function LinkRelatedPages($dbi, $pagename)
487 // currently not supported everywhere
488 if(!function_exists('GetWikiPageLinks'))
491 //FIXME: fix or toss?
492 $links = GetWikiPageLinks($dbi, $pagename);
494 $txt = QElement('strong',
495 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
496 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
497 if(isset($links['in'][$i])) {
498 list($name, $score) = $links['in'][$i];
499 $txt .= LinkExistingWikiWord($name) . " ($score), ";
503 $txt .= "\n" . Element('br');
504 $txt .= Element('strong',
505 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
506 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
507 if(isset($links['out'][$i])) {
508 list($name, $score) = $links['out'][$i];
509 if($dbi->isWikiPage($name))
510 $txt .= LinkExistingWikiWord($name) . " ($score), ";
514 $txt .= "\n" . Element('br');
515 $txt .= Element('strong',
516 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
517 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
518 if(isset($links['popular'][$i])) {
519 list($name, $score) = $links['popular'][$i];
520 $txt .= LinkExistingWikiWord($name) . " ($score), ";
529 * Split WikiWords in page names.
531 * It has been deemed useful to split WikiWords (into "Wiki Words") in
532 * places like page titles. This is rumored to help search engines
535 * @param $page string The page name.
537 * @return string The split name.
539 function split_pagename ($page) {
541 if (preg_match("/\s/", $page))
542 return $page; // Already split --- don't split any more.
544 // FIXME: this algorithm is Anglo-centric.
547 // This mess splits between a lower-case letter followed by
548 // either an upper-case or a numeral; except that it wont
549 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
550 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
551 // This the single-letter words 'I' and 'A' from any following
552 // capitalized words.
553 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
554 // Split numerals from following letters.
555 $RE[] = '/(\d)([[:alpha:]])/';
557 foreach ($RE as $key => $val)
558 $RE[$key] = pcre_fix_posix_classes($val);
561 foreach ($RE as $regexp)
562 $page = preg_replace($regexp, '\\1 \\2', $page);
566 function NoSuchRevision ($page, $version) {
567 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
568 $html .= QElement('p',
569 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
570 $version, $page->getName())) . "\n";
572 include_once('lib/Template.php');
573 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
579 * Get time offset for local time zone.
581 * @param $time time_t Get offset for this time. Default: now.
582 * @param $no_colon boolean Don't put colon between hours and minutes.
583 * @return string Offset as a string in the format +HH:MM.
585 function TimezoneOffset ($time = false, $no_colon = false) {
588 $secs = date('Z', $time);
596 $colon = $no_colon ? '' : ':';
597 $mins = intval(($secs + 30) / 60);
598 return sprintf("%s%02d%s%02d",
599 $sign, $mins / 60, $colon, $mins % 60);
603 * Format time in ISO-8601 format.
605 * @param $time time_t Time. Default: now.
606 * @return string Date and time in ISO-8601 format.
608 function Iso8601DateTime ($time = false) {
611 $tzoff = TimezoneOffset($time);
612 $date = date('Y-m-d', $time);
613 $time = date('H:i:s', $time);
614 return $date . 'T' . $time . $tzoff;
618 * Format time in RFC-2822 format.
620 * @param $time time_t Time. Default: now.
621 * @return string Date and time in RFC-2822 format.
623 function Rfc2822DateTime ($time = false) {
626 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
630 * Format time to standard 'ctime' format.
632 * @param $time time_t Time. Default: now.
633 * @return string Date and time in RFC-2822 format.
635 function CTime ($time = false)
639 return date("D M j H:i:s Y", $time);
645 * Internationalized printf.
647 * This is essentially the same as PHP's built-in printf
648 * with the following exceptions:
650 * <li> It passes the format string through gettext().
651 * <li> It supports the argument reordering extensions.
658 * __printf("Differences between versions %s and %s of %s",
659 * $new_link, $old_link, $page_link);
662 * Then in locale/po/de.po, one can reorder the printf arguments:
665 * msgid "Differences between %s and %s of %s."
666 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
669 * (Note that while PHP tries to expand $vars within double-quotes,
670 * the values in msgstr undergo no such expansion, so the '$'s
673 * One shouldn't use reordered arguments in the default format string.
674 * Backslashes in the default string would be necessary to escape the
675 * '$'s, and they'll cause all kinds of trouble....
677 function __printf ($fmt) {
678 $args = func_get_args();
680 echo __vsprintf($fmt, $args);
684 * Internationalized sprintf.
686 * This is essentially the same as PHP's built-in printf with the
687 * following exceptions:
690 * <li> It passes the format string through gettext().
691 * <li> It supports the argument reordering extensions.
696 function __sprintf ($fmt) {
697 $args = func_get_args();
699 return __vsprintf($fmt, $args);
703 * Internationalized vsprintf.
705 * This is essentially the same as PHP's built-in printf with the
706 * following exceptions:
709 * <li> It passes the format string through gettext().
710 * <li> It supports the argument reordering extensions.
715 function __vsprintf ($fmt, $args) {
716 $fmt = gettext($fmt);
717 // PHP's sprintf doesn't support variable with specifiers,
718 // like sprintf("%*s", 10, "x"); --- so we won't either.
720 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
721 // Format string has '%2$s' style argument reordering.
722 // PHP doesn't support this.
723 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
724 // literal variable name substitution only to keep locale
725 // strings uncluttered
726 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
727 '%1\$s','%s'), E_USER_WARNING);
729 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
732 // Reorder arguments appropriately.
733 foreach($m[1] as $argnum) {
734 if ($argnum < 1 || $argnum > count($args))
735 trigger_error(sprintf(_("%s: argument index out of range"),
736 $argnum), E_USER_WARNING);
737 $newargs[] = $args[$argnum - 1];
742 // Not all PHP's have vsprintf, so...
743 array_unshift($args, $fmt);
744 return call_user_func_array('sprintf', $args);
748 // (c-file-style: "gnu")
753 // c-hanging-comment-ender-p: nil
754 // indent-tabs-mode: nil