1 <?php rcs_id('$Id: stdlib.php,v 1.70 2002-01-08 03:17:41 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) {
80 // FIXME: This is a kludge to allow xgettext to localize the title
81 // of the printer stylesheet. Think up a more elegant way which
82 // will also work with n stylesheets...
83 $PrinterStylesheetTitle = _("Printer");
86 foreach ($CSS_URLS as $key => $val) {
87 $html .= QElement('link',
88 array('rel' => (($CSS_DEFAULT == $key) ?
89 'stylesheet' : 'alternate stylesheet'),
90 'title' => htmlspecialchars(_($key)),
91 'href' => DataURL(htmlspecialchars($val)),
92 'type' => 'text/css'))."\n";
97 define('NO_END_TAG_PAT',
98 '/^' . join('|', array('area', 'base', 'basefont',
100 'hr', 'img', 'input',
101 'isindex', 'link', 'meta',
104 function StartTag($tag, $args = '') {
106 if (is_array($args)) {
107 while (list($key, $val) = each($args))
109 if (is_string($val) || is_numeric($val))
110 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
112 $s .= " $key=\"$key\"";
119 function Element($tag, $args = '', $content = '') {
121 if (!is_array($args)) {
125 $html = StartTag($tag, $args);
126 if (preg_match(NO_END_TAG_PAT, $tag)) {
128 return preg_replace('/>$/', " />", $html);
131 $html .= "</$tag>";//FIXME: newline might not always be desired.
136 function QElement($tag, $args = '', $content = '')
139 return Element($tag, $args, htmlspecialchars($content));
142 return Element($tag, htmlspecialchars($content));
146 function IconForLink($protocol_or_url) {
147 global $URL_LINK_ICONS;
149 list ($proto) = explode(':', $protocol_or_url, 2);
151 if (isset($URL_LINK_ICONS[$proto])) {
152 $linkimg = $URL_LINK_ICONS[$proto];
154 elseif (isset($URL_LINK_ICONS['*'])) {
155 $linkimg = $URL_LINK_ICONS['*'];
161 return Element('img', array('src' => DataURL($linkimg),
163 'class' => 'linkicon'));
167 function LinkURL($url, $linktext = '') {
168 // FIXME: Is this needed (or sufficient?)
169 if(ereg("[<>\"]", $url)) {
170 return Element('strong',
171 QElement('u', array('class' => 'baduri'),
172 _("BAD URL -- remove all of <, >, \"")));
175 $attr['href'] = $url;
177 if (empty($linktext)) {
179 $attr['class'] = 'rawurl';
181 $attr['class'] = 'namedurl';
183 return Element('a', $attr,
184 IconForLink($url) . htmlspecialchars($linktext));
187 function LinkWikiWord($wikiword, $linktext = '') {
189 if ($dbi->isWikiPage($wikiword))
190 return LinkExistingWikiWord($wikiword, $linktext);
192 return LinkUnknownWikiWord($wikiword, $linktext);
195 function LinkExistingWikiWord($wikiword, $linktext = '') {
196 if (empty($linktext)) {
197 $linktext = $wikiword;
198 if (defined("autosplit_wikiwords"))
199 $linktext=split_pagename($linktext);
202 $class = 'named-wiki';
204 return QElement('a', array('href' => WikiURL($wikiword),
209 function LinkUnknownWikiWord($wikiword, $linktext = '') {
210 if (empty($linktext)) {
211 $linktext = $wikiword;
212 if (defined("autosplit_wikiwords"))
213 $linktext=split_pagename($linktext);
214 $class = 'wikiunknown';
216 $class = 'named-wikiunknown';
218 return Element('span', array('class' => $class),
220 array('href' => WikiURL($wikiword,
221 array('action' => 'edit'))),
222 '?') . Element('u', $linktext));
225 function LinkImage($url, $alt = '[External Image]') {
226 // FIXME: Is this needed (or sufficient?)
227 // As long as the src in htmlspecialchars()ed I think it's safe.
228 if(ereg("[<>\"]", $url)) {
229 return Element('strong',
230 QElement('u', array('class' => 'baduri'),
231 _("BAD URL -- remove all of <, >, \"")));
233 return Element('img', array('src' => $url, 'alt' => $alt));
236 // converts spaces to tabs
237 function CookSpaces($pagearray) {
238 return preg_replace("/ {3,8}/", "\t", $pagearray);
243 var $items = array();
246 function push($item) {
247 $this->items[$this->size] = $item;
253 if ($this->size == 0) {
254 return false; // stack is empty
257 return $this->items[$this->size];
266 return $this->items[$this->size - 1];
272 // end class definition
275 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
276 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
277 $formargs['method'] = 'get';
278 $formargs['class'] = $class;
283 while (list($key, $val) = each($args)) {
284 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
286 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
289 $a['size'] = $m[1] ? $m[1] : 30;
294 $formargs['enctype'] = 'multipart/form-data';
295 $contents .= Element('input',
296 array('name' => 'MAX_FILE_SIZE',
297 'value' => MAX_UPLOAD_SIZE,
298 'type' => 'hidden'));
299 $formargs['method'] = 'post';
303 $contents .= Element('input', $a);
306 $row = Element('td', $contents);
308 if (!empty($button_text)) {
309 $row .= Element('td',
310 Element('input', array('type' => 'submit',
312 'value' => $button_text)));
315 return Element('form', $formargs,
316 Element('table', array('cellspacing' => 0,
319 Element('tr', $row)));
322 function SplitQueryArgs ($query_args = '')
324 $split_args = split('&', $query_args);
326 while (list($key, $val) = each($split_args))
327 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
328 $args[$m[1]] = $m[2];
332 function LinkPhpwikiURL($url, $text = '') {
335 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
336 return Element('strong',
337 QElement('u', array('class' => 'baduri'),
338 'BAD phpwiki: URL'));
340 $pagename = urldecode($m[1]);
343 if (empty($pagename) &&
344 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m))
346 // Convert old style links (to not break diff links in
348 $pagename = urldecode($m[2]);
349 $args = array("action" => $m[1]);
352 $args = SplitQueryArgs($qargs);
355 if (empty($pagename))
356 $pagename = $GLOBALS['pagename'];
358 if (isset($args['action']) && $args['action'] == 'browse')
359 unset($args['action']);
361 if (empty($args['action']))
363 else if (is_safe_action($args['action']))
364 $class = 'wikiaction';
366 if (empty($args['action']) || is_safe_action($args['action']))
367 $class = 'wikiaction';
369 // Don't allow administrative links on unlocked pages.
370 // FIXME: Ugh: don't like this...
372 $page = $dbi->getPage($GLOBALS['pagename']);
373 if (!$page->get('locked'))
374 return QElement('u', array('class' => 'wikiunsafe'),
375 _("Lock page to enable link"));
377 $class = 'wikiadmin';
380 // FIXME: ug, don't like this
381 if (preg_match('/=\d*\(/', $qargs))
382 return MakeWikiForm($pagename, $args, $class, $text);
384 $text = htmlspecialchars($text);
386 $text = QElement('span', array('class' => 'rawurl'), $url);
388 return Element('a', array('href' => WikiURL($pagename, $args),
393 function ParseAndLink($bracketlink) {
394 global $dbi, $AllowedProtocols, $InlineImages;
395 global $InterWikiLinkRegexp;
397 // $bracketlink will start and end with brackets; in between will
398 // be either a page name, a URL or both separated by a pipe.
400 // strip brackets and leading space
401 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
402 // match the contents
403 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
405 if (isset($matches[3])) {
406 // named link of the form "[some link name | http://blippy.com/]"
407 $URL = trim($matches[3]);
408 $linkname = trim($matches[1]);
411 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
412 $URL = trim($matches[1]);
414 $linktype = 'simple';
417 if ($dbi->isWikiPage($URL)) {
418 $link['type'] = "wiki-$linktype";
419 $link['link'] = LinkExistingWikiWord($URL, $linkname);
420 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
421 // if it's an image, embed it; otherwise, it's a regular link
422 if (preg_match("/($InlineImages)$/i", $URL)) {
423 $link['type'] = "image-$linktype";
424 $link['link'] = LinkImage($URL, $linkname);
426 $link['type'] = "url-$linktype";
427 $link['link'] = LinkURL($URL, $linkname);
429 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
430 $link['type'] = "url-wiki-$linktype";
431 $link['link'] = LinkPhpwikiURL($URL, $linkname);
432 } elseif (preg_match("#^\d+$#", $URL)) {
433 $link['type'] = "footnote-$linktype";
434 $link['link'] = $URL;
435 } elseif (function_exists('LinkInterWikiLink') &&
436 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
437 $link['type'] = "interwiki-$linktype";
438 $link['link'] = LinkInterWikiLink($URL, $linkname);
440 $link['type'] = "wiki-unknown-$linktype";
441 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
448 function ExtractWikiPageLinks($content) {
449 global $WikiNameRegexp;
451 if (is_string($content))
452 $content = explode("\n", $content);
454 $wikilinks = array();
455 foreach ($content as $line) {
456 // remove plugin code
457 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
458 // remove escaped '['
459 $line = str_replace('[[', ' ', $line);
461 // bracket links (only type wiki-* is of interest)
462 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
464 for ($i = 0; $i < $numBracketLinks; $i++) {
465 $link = ParseAndLink($brktlinks[0][$i]);
466 if (preg_match("#^wiki#", $link['type']))
467 $wikilinks[$brktlinks[2][$i]] = 1;
469 $brktlink = preg_quote($brktlinks[0][$i]);
470 $line = preg_replace("|$brktlink|", '', $line);
473 // BumpyText old-style wiki links
474 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
475 for ($i = 0; isset($link[0][$i]); $i++) {
476 if($link[0][$i][0] <> '!')
477 $wikilinks[$link[0][$i]] = 1;
481 return array_keys($wikilinks);
484 function LinkRelatedPages($dbi, $pagename)
486 // currently not supported everywhere
487 if(!function_exists('GetWikiPageLinks'))
490 //FIXME: fix or toss?
491 $links = GetWikiPageLinks($dbi, $pagename);
493 $txt = QElement('strong',
494 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
495 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
496 if(isset($links['in'][$i])) {
497 list($name, $score) = $links['in'][$i];
498 $txt .= LinkExistingWikiWord($name) . " ($score), ";
502 $txt .= "\n" . Element('br');
503 $txt .= Element('strong',
504 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
505 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
506 if(isset($links['out'][$i])) {
507 list($name, $score) = $links['out'][$i];
508 if($dbi->isWikiPage($name))
509 $txt .= LinkExistingWikiWord($name) . " ($score), ";
513 $txt .= "\n" . Element('br');
514 $txt .= Element('strong',
515 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
516 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
517 if(isset($links['popular'][$i])) {
518 list($name, $score) = $links['popular'][$i];
519 $txt .= LinkExistingWikiWord($name) . " ($score), ";
528 * Split WikiWords in page names.
530 * It has been deemed useful to split WikiWords (into "Wiki Words") in
531 * places like page titles. This is rumored to help search engines
534 * @param $page string The page name.
536 * @return string The split name.
538 function split_pagename ($page) {
540 if (preg_match("/\s/", $page))
541 return $page; // Already split --- don't split any more.
543 // FIXME: this algorithm is Anglo-centric.
546 // This mess splits between a lower-case letter followed by
547 // either an upper-case or a numeral; except that it wont
548 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
549 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
550 // This the single-letter words 'I' and 'A' from any following
551 // capitalized words.
552 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
553 // Split numerals from following letters.
554 $RE[] = '/(\d)([[:alpha:]])/';
556 foreach ($RE as $key => $val)
557 $RE[$key] = pcre_fix_posix_classes($val);
560 foreach ($RE as $regexp)
561 $page = preg_replace($regexp, '\\1 \\2', $page);
565 function NoSuchRevision ($page, $version) {
566 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
567 $html .= QElement('p',
568 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
569 $version, $page->getName())) . "\n";
571 include_once('lib/Template.php');
572 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
578 * Get time offset for local time zone.
580 * @param $time time_t Get offset for this time. Default: now.
581 * @param $no_colon boolean Don't put colon between hours and minutes.
582 * @return string Offset as a string in the format +HH:MM.
584 function TimezoneOffset ($time = false, $no_colon = false) {
587 $secs = date('Z', $time);
595 $colon = $no_colon ? '' : ':';
596 $mins = intval(($secs + 30) / 60);
597 return sprintf("%s%02d%s%02d",
598 $sign, $mins / 60, $colon, $mins % 60);
602 * Format time in ISO-8601 format.
604 * @param $time time_t Time. Default: now.
605 * @return string Date and time in ISO-8601 format.
607 function Iso8601DateTime ($time = false) {
610 $tzoff = TimezoneOffset($time);
611 $date = date('Y-m-d', $time);
612 $time = date('H:i:s', $time);
613 return $date . 'T' . $time . $tzoff;
617 * Format time in RFC-2822 format.
619 * @param $time time_t Time. Default: now.
620 * @return string Date and time in RFC-2822 format.
622 function Rfc2822DateTime ($time = false) {
625 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
629 * Format time to standard 'ctime' format.
631 * @param $time time_t Time. Default: now.
632 * @return string Date and time in RFC-2822 format.
634 function CTime ($time = false)
638 return date("D M j H:i:s Y", $time);
644 * Internationalized printf.
646 * This is essentially the same as PHP's built-in printf
647 * with the following exceptions:
649 * <li> It passes the format string through gettext().
650 * <li> It supports the argument reordering extensions.
657 * __printf("Differences between versions %s and %s of %s",
658 * $new_link, $old_link, $page_link);
661 * Then in locale/po/de.po, one can reorder the printf arguments:
664 * msgid "Differences between %s and %s of %s."
665 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
668 * (Note that while PHP tries to expand $vars within double-quotes,
669 * the values in msgstr undergo no such expansion, so the '$'s
672 * One shouldn't use reordered arguments in the default format string.
673 * Backslashes in the default string would be necessary to escape the
674 * '$'s, and they'll cause all kinds of trouble....
676 function __printf ($fmt) {
677 $args = func_get_args();
679 echo __vsprintf($fmt, $args);
683 * Internationalized sprintf.
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 __sprintf ($fmt) {
696 $args = func_get_args();
698 return __vsprintf($fmt, $args);
702 * Internationalized vsprintf.
704 * This is essentially the same as PHP's built-in printf with the
705 * following exceptions:
708 * <li> It passes the format string through gettext().
709 * <li> It supports the argument reordering extensions.
714 function __vsprintf ($fmt, $args) {
715 $fmt = gettext($fmt);
716 // PHP's sprintf doesn't support variable with specifiers,
717 // like sprintf("%*s", 10, "x"); --- so we won't either.
719 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
720 // Format string has '%2$s' style argument reordering.
721 // PHP doesn't support this.
722 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
723 // literal variable name substitution only to keep locale
724 // strings uncluttered
725 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
726 '%1\$s','%s'), E_USER_WARNING);
728 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
731 // Reorder arguments appropriately.
732 foreach($m[1] as $argnum) {
733 if ($argnum < 1 || $argnum > count($args))
734 trigger_error(sprintf(_("%s: argument index out of range"),
735 $argnum), E_USER_WARNING);
736 $newargs[] = $args[$argnum - 1];
741 // Not all PHP's have vsprintf, so...
742 array_unshift($args, $fmt);
743 return call_user_func_array('sprintf', $args);
747 // (c-file-style: "gnu")
752 // c-hanging-comment-ender-p: nil
753 // indent-tabs-mode: nil