1 <?php rcs_id('$Id: stdlib.php,v 1.73 2002-01-13 19:18:18 dairiki Exp $');
4 Standard functions for Wiki functionality
7 WikiURL($pagename, $args, $get_abs_url)
9 Element($tag, $args, $content)
10 QElement($tag, $args, $content)
11 IconForLink($protocol_or_url)
12 LinkURL($url, $linktext)
13 LinkWikiWord($wikiword, $linktext)
14 LinkExistingWikiWord($wikiword, $linktext)
15 LinkUnknownWikiWord($wikiword, $linktext)
17 class Stack { push($item), pop(), cnt(), top() }
18 CookSpaces($pagearray)
19 MakeWikiForm ($pagename, $args, $class, $button_text)
20 SplitQueryArgs ($query_args)
21 LinkPhpwikiURL($url, $text)
22 ParseAndLink($bracketlink)
23 ExtractWikiPageLinks($content)
24 LinkRelatedPages($dbi, $pagename)
25 split_pagename ($page)
26 NoSuchRevision ($page, $version)
27 TimezoneOffset ($time, $no_colon)
28 Iso8601DateTime ($time)
29 Rfc2822DateTime ($time)
33 __vsprintf ($fmt, $args)
35 function moved => LinkInterWikiLink($link, $linktext)
36 (see /lib/interwiki.php)
37 function gone => UpdateRecentChanges($dbi, $pagename, $isnewpage)
38 (see /lib/plugin/RecentChanges.php)
43 function DataURL($url) {
44 if (preg_match('@^(\w+:|/)@', $url))
46 return SERVER_URL . DATA_PATH . "/$url";
50 return SERVER_URL . DATA_PATH . "/";
53 function WikiURL($pagename, $args = '', $get_abs_url = false) {
54 if (is_array($args)) {
56 foreach ($args as $key => $val) {
57 $enc_args[] = urlencode($key) . '=' . urlencode($val);
59 $args = join('&', $enc_args);
64 SERVER_URL . VIRTUAL_PATH . "/" : VIRTUAL_PATH . "/";
65 $url .= rawurlencode($pagename);
70 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
71 $url .= "?pagename=" . rawurlencode($pagename);
78 define('NO_END_TAG_PAT',
79 '/^' . join('|', array('area', 'base', 'basefont',
82 'isindex', 'link', 'meta',
85 function StartTag($tag, $args = '') {
87 if (is_array($args)) {
88 while (list($key, $val) = each($args))
90 if (is_string($val) || is_numeric($val))
91 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
93 $s .= " $key=\"$key\"";
100 function Element($tag, $args = '', $content = '') {
102 if (!is_array($args)) {
106 $html = StartTag($tag, $args);
107 if (preg_match(NO_END_TAG_PAT, $tag)) {
109 return preg_replace('/>$/', " />", $html);
112 $html .= "</$tag>";//FIXME: newline might not always be desired.
117 function QElement($tag, $args = '', $content = '')
120 return Element($tag, $args, htmlspecialchars($content));
123 return Element($tag, htmlspecialchars($content));
127 function IconForLink($protocol_or_url) {
128 global $URL_LINK_ICONS;
130 list ($proto) = explode(':', $protocol_or_url, 2);
132 if (isset($URL_LINK_ICONS[$proto])) {
133 $linkimg = $URL_LINK_ICONS[$proto];
135 elseif (isset($URL_LINK_ICONS['*'])) {
136 $linkimg = $URL_LINK_ICONS['*'];
142 return Element('img', array('src' => DataURL($linkimg),
144 'class' => 'linkicon'));
148 function LinkURL($url, $linktext = '') {
149 // FIXME: Is this needed (or sufficient?)
150 if(ereg("[<>\"]", $url)) {
151 return Element('strong',
152 QElement('u', array('class' => 'baduri'),
153 _("BAD URL -- remove all of <, >, \"")));
156 $attr['href'] = $url;
158 if (empty($linktext)) {
160 $attr['class'] = 'rawurl';
162 $attr['class'] = 'namedurl';
164 return Element('a', $attr,
165 IconForLink($url) . htmlspecialchars($linktext));
168 function LinkWikiWord($wikiword, $linktext = '') {
170 if ($dbi->isWikiPage($wikiword))
171 return LinkExistingWikiWord($wikiword, $linktext);
173 return LinkUnknownWikiWord($wikiword, $linktext);
176 function LinkExistingWikiWord($wikiword, $linktext = '') {
177 if (empty($linktext)) {
178 $linktext = $wikiword;
179 if (defined("autosplit_wikiwords"))
180 $linktext=split_pagename($linktext);
183 $class = 'named-wiki';
185 return QElement('a', array('href' => WikiURL($wikiword),
190 function LinkUnknownWikiWord($wikiword, $linktext = '') {
191 if (empty($linktext)) {
192 $linktext = $wikiword;
193 if (defined("autosplit_wikiwords"))
194 $linktext=split_pagename($linktext);
195 $class = 'wikiunknown';
197 $class = 'named-wikiunknown';
199 return Element('span', array('class' => $class),
201 array('href' => WikiURL($wikiword,
202 array('action' => 'edit'))),
203 '?') . Element('u', $linktext));
206 function LinkImage($url, $alt = '[External Image]') {
207 // FIXME: Is this needed (or sufficient?)
208 // As long as the src in htmlspecialchars()ed I think it's safe.
209 if(ereg("[<>\"]", $url)) {
210 return Element('strong',
211 QElement('u', array('class' => 'baduri'),
212 _("BAD URL -- remove all of <, >, \"")));
214 return Element('img', array('src' => $url, 'alt' => $alt));
217 // converts spaces to tabs
218 function CookSpaces($pagearray) {
219 return preg_replace("/ {3,8}/", "\t", $pagearray);
224 var $items = array();
227 function push($item) {
228 $this->items[$this->size] = $item;
234 if ($this->size == 0) {
235 return false; // stack is empty
238 return $this->items[$this->size];
247 return $this->items[$this->size - 1];
253 // end class definition
256 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
257 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
258 $formargs['method'] = 'get';
259 $formargs['class'] = $class;
264 while (list($key, $val) = each($args)) {
265 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
267 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
270 $a['size'] = $m[1] ? $m[1] : 30;
275 $formargs['enctype'] = 'multipart/form-data';
276 $contents .= Element('input',
277 array('name' => 'MAX_FILE_SIZE',
278 'value' => MAX_UPLOAD_SIZE,
279 'type' => 'hidden'));
280 $formargs['method'] = 'post';
284 $contents .= Element('input', $a);
287 $row = Element('td', $contents);
289 if (!empty($button_text)) {
290 $row .= Element('td',
291 Element('input', array('type' => 'submit',
293 'value' => $button_text)));
296 return Element('form', $formargs,
297 Element('table', array('cellspacing' => 0,
300 Element('tr', $row)));
303 function SplitQueryArgs ($query_args = '')
305 $split_args = split('&', $query_args);
307 while (list($key, $val) = each($split_args))
308 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
309 $args[$m[1]] = $m[2];
313 function LinkPhpwikiURL($url, $text = '') {
316 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
317 return Element('strong',
318 QElement('u', array('class' => 'baduri'),
319 'BAD phpwiki: URL'));
321 $pagename = urldecode($m[1]);
324 if (empty($pagename) &&
325 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m))
327 // Convert old style links (to not break diff links in
329 $pagename = urldecode($m[2]);
330 $args = array("action" => $m[1]);
333 $args = SplitQueryArgs($qargs);
336 if (empty($pagename))
337 $pagename = $GLOBALS['pagename'];
339 if (isset($args['action']) && $args['action'] == 'browse')
340 unset($args['action']);
342 if (empty($args['action']))
344 else if (is_safe_action($args['action']))
345 $class = 'wikiaction';
347 if (empty($args['action']) || is_safe_action($args['action']))
348 $class = 'wikiaction';
350 // Don't allow administrative links on unlocked pages.
351 // FIXME: Ugh: don't like this...
353 $page = $dbi->getPage($GLOBALS['pagename']);
354 if (!$page->get('locked'))
355 return QElement('u', array('class' => 'wikiunsafe'),
356 _("Lock page to enable link"));
358 $class = 'wikiadmin';
361 // FIXME: ug, don't like this
362 if (preg_match('/=\d*\(/', $qargs))
363 return MakeWikiForm($pagename, $args, $class, $text);
365 $text = htmlspecialchars($text);
367 $text = QElement('span', array('class' => 'rawurl'), $url);
369 return Element('a', array('href' => WikiURL($pagename, $args),
374 function ParseAndLink($bracketlink) {
375 global $dbi, $AllowedProtocols, $InlineImages;
376 global $InterWikiLinkRegexp;
378 // $bracketlink will start and end with brackets; in between will
379 // be either a page name, a URL or both separated by a pipe.
381 // strip brackets and leading space
382 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
383 // match the contents
384 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
386 if (isset($matches[3])) {
387 // named link of the form "[some link name | http://blippy.com/]"
388 $URL = trim($matches[3]);
389 $linkname = trim($matches[1]);
392 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
393 $URL = trim($matches[1]);
395 $linktype = 'simple';
398 if ($dbi->isWikiPage($URL)) {
399 $link['type'] = "wiki-$linktype";
400 $link['link'] = LinkExistingWikiWord($URL, $linkname);
401 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
402 // if it's an image, embed it; otherwise, it's a regular link
403 if (preg_match("/($InlineImages)$/i", $URL)) {
404 $link['type'] = "image-$linktype";
405 $link['link'] = LinkImage($URL, $linkname);
407 $link['type'] = "url-$linktype";
408 $link['link'] = LinkURL($URL, $linkname);
410 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
411 $link['type'] = "url-wiki-$linktype";
412 $link['link'] = LinkPhpwikiURL($URL, $linkname);
413 } elseif (preg_match("#^\d+$#", $URL)) {
414 $link['type'] = "footnote-$linktype";
415 $link['link'] = $URL;
416 } elseif (function_exists('LinkInterWikiLink') &&
417 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
418 $link['type'] = "interwiki-$linktype";
419 $link['link'] = LinkInterWikiLink($URL, $linkname);
421 $link['type'] = "wiki-unknown-$linktype";
422 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
429 function ExtractWikiPageLinks($content) {
430 global $WikiNameRegexp;
432 if (is_string($content))
433 $content = explode("\n", $content);
435 $wikilinks = array();
436 foreach ($content as $line) {
437 // remove plugin code
438 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
439 // remove escaped '['
440 $line = str_replace('[[', ' ', $line);
442 // bracket links (only type wiki-* is of interest)
443 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
445 for ($i = 0; $i < $numBracketLinks; $i++) {
446 $link = ParseAndLink($brktlinks[0][$i]);
447 if (preg_match("#^wiki#", $link['type']))
448 $wikilinks[$brktlinks[2][$i]] = 1;
450 $brktlink = preg_quote($brktlinks[0][$i]);
451 $line = preg_replace("|$brktlink|", '', $line);
454 // BumpyText old-style wiki links
455 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
456 for ($i = 0; isset($link[0][$i]); $i++) {
457 if($link[0][$i][0] <> '!')
458 $wikilinks[$link[0][$i]] = 1;
462 return array_keys($wikilinks);
465 function LinkRelatedPages($dbi, $pagename)
467 // currently not supported everywhere
468 if(!function_exists('GetWikiPageLinks'))
471 //FIXME: fix or toss?
472 $links = GetWikiPageLinks($dbi, $pagename);
474 $txt = QElement('strong',
475 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
476 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
477 if(isset($links['in'][$i])) {
478 list($name, $score) = $links['in'][$i];
479 $txt .= LinkExistingWikiWord($name) . " ($score), ";
483 $txt .= "\n" . Element('br');
484 $txt .= Element('strong',
485 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
486 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
487 if(isset($links['out'][$i])) {
488 list($name, $score) = $links['out'][$i];
489 if($dbi->isWikiPage($name))
490 $txt .= LinkExistingWikiWord($name) . " ($score), ";
494 $txt .= "\n" . Element('br');
495 $txt .= Element('strong',
496 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
497 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
498 if(isset($links['popular'][$i])) {
499 list($name, $score) = $links['popular'][$i];
500 $txt .= LinkExistingWikiWord($name) . " ($score), ";
509 * Split WikiWords in page names.
511 * It has been deemed useful to split WikiWords (into "Wiki Words") in
512 * places like page titles. This is rumored to help search engines
515 * @param $page string The page name.
517 * @return string The split name.
519 function split_pagename ($page) {
521 if (preg_match("/\s/", $page))
522 return $page; // Already split --- don't split any more.
524 // FIXME: this algorithm is Anglo-centric.
527 // This mess splits between a lower-case letter followed by
528 // either an upper-case or a numeral; except that it wont
529 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
530 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
531 // This the single-letter words 'I' and 'A' from any following
532 // capitalized words.
533 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
534 // Split numerals from following letters.
535 $RE[] = '/(\d)([[:alpha:]])/';
537 foreach ($RE as $key => $val)
538 $RE[$key] = pcre_fix_posix_classes($val);
541 foreach ($RE as $regexp)
542 $page = preg_replace($regexp, '\\1 \\2', $page);
546 function NoSuchRevision ($page, $version) {
547 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
548 $html .= QElement('p',
549 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
550 $version, $page->getName())) . "\n";
552 include_once('lib/Template.php');
553 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
559 * Get time offset for local time zone.
561 * @param $time time_t Get offset for this time. Default: now.
562 * @param $no_colon boolean Don't put colon between hours and minutes.
563 * @return string Offset as a string in the format +HH:MM.
565 function TimezoneOffset ($time = false, $no_colon = false) {
568 $secs = date('Z', $time);
576 $colon = $no_colon ? '' : ':';
577 $mins = intval(($secs + 30) / 60);
578 return sprintf("%s%02d%s%02d",
579 $sign, $mins / 60, $colon, $mins % 60);
583 * Format time in ISO-8601 format.
585 * @param $time time_t Time. Default: now.
586 * @return string Date and time in ISO-8601 format.
588 function Iso8601DateTime ($time = false) {
591 $tzoff = TimezoneOffset($time);
592 $date = date('Y-m-d', $time);
593 $time = date('H:i:s', $time);
594 return $date . 'T' . $time . $tzoff;
598 * Format time in RFC-2822 format.
600 * @param $time time_t Time. Default: now.
601 * @return string Date and time in RFC-2822 format.
603 function Rfc2822DateTime ($time = false) {
606 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
610 * Format time to standard 'ctime' format.
612 * @param $time time_t Time. Default: now.
613 * @return string Date and time in RFC-2822 format.
615 function CTime ($time = false)
619 return date("D M j H:i:s Y", $time);
625 * Internationalized printf.
627 * This is essentially the same as PHP's built-in printf
628 * with the following exceptions:
630 * <li> It passes the format string through gettext().
631 * <li> It supports the argument reordering extensions.
638 * __printf("Differences between versions %s and %s of %s",
639 * $new_link, $old_link, $page_link);
642 * Then in locale/po/de.po, one can reorder the printf arguments:
645 * msgid "Differences between %s and %s of %s."
646 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
649 * (Note that while PHP tries to expand $vars within double-quotes,
650 * the values in msgstr undergo no such expansion, so the '$'s
653 * One shouldn't use reordered arguments in the default format string.
654 * Backslashes in the default string would be necessary to escape the
655 * '$'s, and they'll cause all kinds of trouble....
657 function __printf ($fmt) {
658 $args = func_get_args();
660 echo __vsprintf($fmt, $args);
664 * Internationalized sprintf.
666 * This is essentially the same as PHP's built-in printf with the
667 * following exceptions:
670 * <li> It passes the format string through gettext().
671 * <li> It supports the argument reordering extensions.
676 function __sprintf ($fmt) {
677 $args = func_get_args();
679 return __vsprintf($fmt, $args);
683 * Internationalized vsprintf.
685 * This is essentially the same as PHP's built-in printf with the
686 * following exceptions:
689 * <li> It passes the format string through gettext().
690 * <li> It supports the argument reordering extensions.
695 function __vsprintf ($fmt, $args) {
696 $fmt = gettext($fmt);
697 // PHP's sprintf doesn't support variable with specifiers,
698 // like sprintf("%*s", 10, "x"); --- so we won't either.
700 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
701 // Format string has '%2$s' style argument reordering.
702 // PHP doesn't support this.
703 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
704 // literal variable name substitution only to keep locale
705 // strings uncluttered
706 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
707 '%1\$s','%s'), E_USER_WARNING);
709 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
712 // Reorder arguments appropriately.
713 foreach($m[1] as $argnum) {
714 if ($argnum < 1 || $argnum > count($args))
715 trigger_error(sprintf(_("%s: argument index out of range"),
716 $argnum), E_USER_WARNING);
717 $newargs[] = $args[$argnum - 1];
722 // Not all PHP's have vsprintf, so...
723 array_unshift($args, $fmt);
724 return call_user_func_array('sprintf', $args);
728 // (c-file-style: "gnu")
733 // c-hanging-comment-ender-p: nil
734 // indent-tabs-mode: nil