1 <?php rcs_id('$Id: stdlib.php,v 1.66 2002-01-05 15:14:11 carstenklapp Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $abs)
6 CSS_URL($CSS_URLS, $CSS_DEFAULT)
7 LinkWikiWord($wikiword, $linktext)
8 LinkExistingWikiWord($wikiword, $linktext)
9 LinkUnknownWikiWord($wikiword, $linktext)
10 LinkURL($url, $linktext)
12 LinkInterWikiLink($link, $linktext)
13 CookSpaces($pagearray)
14 class Stack (push(), pop(), cnt(), top())
15 UpdateRecentChanges($dbi, $pagename, $isnewpage)
16 ParseAndLink($bracketlink)
17 ExtractWikiPageLinks($content)
18 LinkRelatedPages($dbi, $pagename)
22 function DataURL($url) {
23 if (preg_match('@^(\w+:|/)@', $url))
25 return SERVER_URL . DATA_PATH . "/$url";
29 return SERVER_URL . "/";
32 function WikiURL($pagename, $args = '', $get_abs_url = false) {
33 if (is_array($args)) {
35 foreach ($args as $key => $val) {
36 $enc_args[] = urlencode($key) . '=' . urlencode($val);
38 $args = join('&', $enc_args);
42 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : VIRTUAL_PATH . "/";
43 $url .= rawurlencode($pagename);
48 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
49 $url .= "?pagename=" . rawurlencode($pagename);
57 function CSS_URL($CSS_URLS, $CSS_DEFAULT) {
58 // FIXME: This is a kludge to allow xgettext to localize the title
59 // of the printer stylesheet. Think up a more elegant way which
60 // will also work with n stylesheets...
61 $PrinterStylesheetTitle = _("Printer");
64 foreach ($CSS_URLS as $key => $val) {
65 $html .= QElement('link',
66 array('rel' => (($CSS_DEFAULT == $key) ?
67 'stylesheet' : 'alternate stylesheet'),
68 'title' => _(htmlspecialchars($key)),
69 'href' => DataURL(htmlspecialchars($val)),
70 'type' => 'text/css'))."\n";
75 define('NO_END_TAG_PAT',
76 '/^' . join('|', array('area', 'base', 'basefont',
79 'isindex', 'link', 'meta',
82 function StartTag($tag, $args = '')
87 while (list($key, $val) = each($args))
89 if (is_string($val) || is_numeric($val))
90 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
92 $s .= " $key=\"$key\"";
99 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';
163 $attr['class'] = 'namedurl';
166 return Element('a', $attr,
167 IconForLink($url) . htmlspecialchars($linktext));
170 function LinkWikiWord($wikiword, $linktext='') {
172 if ($dbi->isWikiPage($wikiword))
173 return LinkExistingWikiWord($wikiword, $linktext);
175 return LinkUnknownWikiWord($wikiword, $linktext);
179 function LinkExistingWikiWord($wikiword, $linktext='') {
180 if (empty($linktext)) {
181 $linktext = $wikiword;
182 if (defined("autosplit_wikiwords"))
183 $linktext=split_pagename($linktext);
187 $class = 'named-wiki';
189 return QElement('a', array('href' => WikiURL($wikiword),
194 function LinkUnknownWikiWord($wikiword, $linktext='') {
195 if (empty($linktext)) {
196 $linktext = $wikiword;
197 if (defined("autosplit_wikiwords"))
198 $linktext=split_pagename($linktext);
199 $class = 'wikiunknown';
202 $class = 'named-wikiunknown';
205 return Element('span', array('class' => $class),
207 array('href' => WikiURL($wikiword, array('action' => 'edit'))),
209 . Element('u', $linktext));
212 function LinkImage($url, $alt='[External Image]') {
213 // FIXME: Is this needed (or sufficient?)
214 // As long as the src in htmlspecialchars()ed I think it's safe.
215 if(ereg("[<>\"]", $url)) {
216 return Element('strong',
217 QElement('u', array('class' => 'baduri'),
218 _("BAD URL -- remove all of <, >, \"")));
220 return Element('img', array('src' => $url, 'alt' => $alt));
223 // converts spaces to tabs
224 function CookSpaces($pagearray) {
225 return preg_replace("/ {3,8}/", "\t", $pagearray);
230 var $items = array();
233 function push($item) {
234 $this->items[$this->size] = $item;
240 if ($this->size == 0) {
241 return false; // stack is empty
244 return $this->items[$this->size];
253 return $this->items[$this->size - 1];
259 // end class definition
262 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
264 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
265 $formargs['method'] = 'get';
266 $formargs['class'] = $class;
271 while (list($key, $val) = each($args))
273 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
275 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
279 $a['size'] = $m[1] ? $m[1] : 30;
284 $formargs['enctype'] = 'multipart/form-data';
285 $contents .= Element('input',
286 array('name' => 'MAX_FILE_SIZE',
287 'value' => MAX_UPLOAD_SIZE,
288 'type' => 'hidden'));
289 $formargs['method'] = 'post';
293 $contents .= Element('input', $a);
296 $row = Element('td', $contents);
298 if (!empty($button_text)) {
299 $row .= Element('td', Element('input', array('type' => 'submit',
301 'value' => $button_text)));
304 return Element('form', $formargs,
305 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
306 Element('tr', $row)));
309 function SplitQueryArgs ($query_args = '')
311 $split_args = split('&', $query_args);
313 while (list($key, $val) = each($split_args))
314 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
315 $args[$m[1]] = $m[2];
319 function LinkPhpwikiURL($url, $text = '') {
322 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
323 return Element('strong',
324 QElement('u', array('class' => 'baduri'),
325 'BAD phpwiki: URL'));
327 $pagename = urldecode($m[1]);
330 if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
331 // Convert old style links (to not break diff links in RecentChanges).
332 $pagename = urldecode($m[2]);
333 $args = array("action" => $m[1]);
336 $args = SplitQueryArgs($qargs);
339 if (empty($pagename))
340 $pagename = $GLOBALS['pagename'];
342 if (isset($args['action']) && $args['action'] == 'browse')
343 unset($args['action']);
345 if (empty($args['action']))
347 else if (is_safe_action($args['action']))
348 $class = 'wikiaction';
350 if (empty($args['action']) || is_safe_action($args['action']))
351 $class = 'wikiaction';
353 // Don't allow administrative links on unlocked pages.
354 // FIXME: Ugh: don't like this...
356 $page = $dbi->getPage($GLOBALS['pagename']);
357 if (!$page->get('locked'))
358 return QElement('u', array('class' => 'wikiunsafe'),
359 _("Lock page to enable link"));
361 $class = 'wikiadmin';
364 // FIXME: ug, don't like this
365 if (preg_match('/=\d*\(/', $qargs))
366 return MakeWikiForm($pagename, $args, $class, $text);
368 $text = htmlspecialchars($text);
370 $text = QElement('span', array('class' => 'rawurl'), $url);
372 return Element('a', array('href' => WikiURL($pagename, $args),
377 function ParseAndLink($bracketlink) {
378 global $dbi, $AllowedProtocols, $InlineImages;
379 global $InterWikiLinkRegexp;
381 // $bracketlink will start and end with brackets; in between
382 // will be either a page name, a URL or both separated by a pipe.
384 // strip brackets and leading space
385 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
386 // match the contents
387 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
389 if (isset($matches[3])) {
390 // named link of the form "[some link name | http://blippy.com/]"
391 $URL = trim($matches[3]);
392 $linkname = trim($matches[1]);
395 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
396 $URL = trim($matches[1]);
398 $linktype = 'simple';
401 if ($dbi->isWikiPage($URL)) {
402 $link['type'] = "wiki-$linktype";
403 $link['link'] = LinkExistingWikiWord($URL, $linkname);
404 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
405 // if it's an image, embed it; otherwise, it's a regular link
406 if (preg_match("/($InlineImages)$/i", $URL)) {
407 $link['type'] = "image-$linktype";
408 $link['link'] = LinkImage($URL, $linkname);
410 $link['type'] = "url-$linktype";
411 $link['link'] = LinkURL($URL, $linkname);
413 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
414 $link['type'] = "url-wiki-$linktype";
415 $link['link'] = LinkPhpwikiURL($URL, $linkname);
416 } elseif (preg_match("#^\d+$#", $URL)) {
417 $link['type'] = "footnote-$linktype";
418 $link['link'] = $URL;
419 } elseif (function_exists('LinkInterWikiLink') &&
420 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
421 $link['type'] = "interwiki-$linktype";
422 $link['link'] = LinkInterWikiLink($URL, $linkname);
424 $link['type'] = "wiki-unknown-$linktype";
425 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
432 function ExtractWikiPageLinks($content)
434 global $WikiNameRegexp;
436 if (is_string($content))
437 $content = explode("\n", $content);
439 $wikilinks = array();
440 foreach ($content as $line) {
441 // remove plugin code
442 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
443 // remove escaped '['
444 $line = str_replace('[[', ' ', $line);
446 // bracket links (only type wiki-* is of interest)
447 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/", $line, $brktlinks);
448 for ($i = 0; $i < $numBracketLinks; $i++) {
449 $link = ParseAndLink($brktlinks[0][$i]);
450 if (preg_match("#^wiki#", $link['type']))
451 $wikilinks[$brktlinks[2][$i]] = 1;
453 $brktlink = preg_quote($brktlinks[0][$i]);
454 $line = preg_replace("|$brktlink|", '', $line);
457 // BumpyText old-style wiki links
458 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
459 for ($i = 0; isset($link[0][$i]); $i++) {
460 if($link[0][$i][0] <> '!')
461 $wikilinks[$link[0][$i]] = 1;
465 return array_keys($wikilinks);
468 function LinkRelatedPages($dbi, $pagename)
470 // currently not supported everywhere
471 if(!function_exists('GetWikiPageLinks'))
474 //FIXME: fix or toss?
475 $links = GetWikiPageLinks($dbi, $pagename);
477 $txt = QElement('strong',
478 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
479 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
480 if(isset($links['in'][$i])) {
481 list($name, $score) = $links['in'][$i];
482 $txt .= LinkExistingWikiWord($name) . " ($score), ";
486 $txt .= "\n" . Element('br');
487 $txt .= Element('strong',
488 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
489 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
490 if(isset($links['out'][$i])) {
491 list($name, $score) = $links['out'][$i];
492 if($dbi->isWikiPage($name))
493 $txt .= LinkExistingWikiWord($name) . " ($score), ";
497 $txt .= "\n" . Element('br');
498 $txt .= Element('strong',
499 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
500 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
501 if(isset($links['popular'][$i])) {
502 list($name, $score) = $links['popular'][$i];
503 $txt .= LinkExistingWikiWord($name) . " ($score), ";
512 * Split WikiWords in page names.
514 * It has been deemed useful to split WikiWords (into "Wiki Words")
515 * in places like page titles. This is rumored to help search engines
518 * @param $page string The page name.
520 * @return string The split name.
522 function split_pagename ($page) {
524 if (preg_match("/\s/", $page))
525 return $page; // Already split --- don't split any more.
527 // FIXME: this algorithm is Anglo-centric.
530 // This mess splits between a lower-case letter followed by either an upper-case
531 // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
533 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
534 // This the single-letter words 'I' and 'A' from any following capitalized words.
535 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
536 // Split numerals from following letters.
537 $RE[] = '/(\d)([[:alpha:]])/';
539 foreach ($RE as $key => $val)
540 $RE[$key] = pcre_fix_posix_classes($val);
543 foreach ($RE as $regexp)
544 $page = preg_replace($regexp, '\\1 \\2', $page);
548 function NoSuchRevision ($page, $version) {
549 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
550 $html .= QElement('p',
551 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
552 $version, $page->getName())) . "\n";
554 include_once('lib/Template.php');
555 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
561 * Get time offset for local time zone.
563 * @param $time time_t Get offset for this time. Default: now.
564 * @param $no_colon boolean Don't put colon between hours and minutes.
565 * @return string Offset as a string in the format +HH:MM.
567 function TimezoneOffset ($time = false, $no_colon = false) {
570 $secs = date('Z', $time);
578 $colon = $no_colon ? '' : ':';
579 $mins = intval(($secs + 30) / 60);
580 return sprintf("%s%02d%s%02d",
581 $sign, $mins / 60, $colon, $mins % 60);
585 * Format time in ISO-8601 format.
587 * @param $time time_t Time. Default: now.
588 * @return string Date and time in ISO-8601 format.
590 function Iso8601DateTime ($time = false) {
593 $tzoff = TimezoneOffset($time);
594 $date = date('Y-m-d', $time);
595 $time=date('H:i:s', $time);
596 return $date . 'T' . $time . $tzoff;
600 * Format time in RFC-2822 format.
602 * @param $time time_t Time. Default: now.
603 * @return string Date and time in RFC-2822 format.
605 function Rfc2822DateTime ($time = false) {
608 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
612 * Format time to standard 'ctime' format.
614 * @param $time time_t Time. Default: now.
615 * @return string Date and time in RFC-2822 format.
617 function CTime ($time = false)
621 return date("D M j H:i:s Y", $time);
627 * Internationalized printf.
629 * This is essentially the same as PHP's built-in printf
630 * with the following exceptions:
632 * <li> It passes the format string through gettext().
633 * <li> It supports the argument reordering extensions.
640 * __printf("Differences between versions %s and %s of %s",
641 * $new_link, $old_link, $page_link);
644 * Then in locale/po/de.po, one can reorder the printf arguments:
647 * msgid "Differences between %s and %s of %s."
648 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
651 * (Note that while PHP tries to expand $vars within double-quotes,
652 * the values in msgstr undergo no such expansion, so the '$'s okay...)
654 * One shouldn't use reordered arguments in the default format string.
655 * Backslashes in the default string would be necessary to escape the '$'s,
656 * and they'll cause all kinds of trouble....
658 function __printf ($fmt) {
659 $args = func_get_args();
661 echo __vsprintf($fmt, $args);
665 * Internationalized sprintf.
667 * This is essentially the same as PHP's built-in printf
668 * with the 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
686 * with the following exceptions:
688 * <li> It passes the format string through gettext().
689 * <li> It supports the argument reordering extensions.
694 function __vsprintf ($fmt, $args) {
695 $fmt = gettext($fmt);
696 // PHP's sprintf doesn't support variable with specifiers,
697 // like sprintf("%*s", 10, "x"); --- so we won't either.
699 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
700 // Format string has '%2$s' style argument reordering.
701 // PHP doesn't support this.
702 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
703 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),'%1\$s','%s'), E_USER_WARNING);
705 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
708 // Reorder arguments appropriately.
709 foreach($m[1] as $argnum) {
710 if ($argnum < 1 || $argnum > count($args))
711 trigger_error(sprintf(_("%s: argument index out of range"),$argnum), E_USER_WARNING);
712 $newargs[] = $args[$argnum - 1];
717 // Not all PHP's have vsprintf, so...
718 array_unshift($args, $fmt);
719 return call_user_func_array('sprintf', $args);
723 // (c-file-style: "gnu")
728 // c-hanging-comment-ender-p: nil
729 // indent-tabs-mode: nil