1 <?php rcs_id('$Id: stdlib.php,v 1.64 2002-01-03 00:09:18 carstenklapp Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $abs)
6 LinkWikiWord($wikiword, $linktext)
7 LinkExistingWikiWord($wikiword, $linktext)
8 LinkUnknownWikiWord($wikiword, $linktext)
9 LinkURL($url, $linktext)
11 LinkInterWikiLink($link, $linktext)
12 CookSpaces($pagearray)
13 class Stack (push(), pop(), cnt(), top())
14 UpdateRecentChanges($dbi, $pagename, $isnewpage)
15 ParseAndLink($bracketlink)
16 ExtractWikiPageLinks($content)
17 LinkRelatedPages($dbi, $pagename)
21 function DataURL($url) {
22 if (preg_match('@^(\w+:|/)@', $url))
24 return SERVER_URL . DATA_PATH . "/$url";
28 return SERVER_URL . VIRTUAL_PATH . "/";
31 function WikiURL($pagename, $args = '', $get_abs_url = false) {
32 if (is_array($args)) {
34 foreach ($args as $key => $val) {
35 $enc_args[] = urlencode($key) . '=' . urlencode($val);
37 $args = join('&', $enc_args);
41 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : '';
42 $url .= rawurlencode($pagename);
47 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
48 $url .= "?pagename=" . rawurlencode($pagename);
56 function CSS_URL($CSS_URLS, $CSS_DEFAULT) {
58 foreach ($CSS_URLS as $key => $val) {
59 if ($CSS_DEFAULT == $key) {
60 $html .= "<link rel=\"stylesheet\" title=\"".htmlspecialchars($key)."\" href=\"". DataURL(htmlspecialchars($val))."\" type=\"text/css\" />\n";
62 $html .= "<link rel=\"alternate stylesheet\" title=\"".htmlspecialchars($key)."\" href=\"". DataURL(htmlspecialchars($val))."\" type=\"text/css\" />\n";
68 define('NO_END_TAG_PAT',
69 '/^' . join('|', array('area', 'base', 'basefont',
72 'isindex', 'link', 'meta',
75 function StartTag($tag, $args = '')
80 while (list($key, $val) = each($args))
82 if (is_string($val) || is_numeric($val))
83 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
85 $s .= " $key=\"$key\"";
92 function Element($tag, $args = '', $content = '')
95 if (!is_array($args)) {
99 $html = StartTag($tag, $args);
100 if (preg_match(NO_END_TAG_PAT, $tag)) {
102 return preg_replace('/>$/', " />", $html);
105 $html .= "</$tag>";//FIXME: newline might not always be desired.
110 function QElement($tag, $args = '', $content = '')
113 return Element($tag, $args, htmlspecialchars($content));
116 return Element($tag, htmlspecialchars($content));
120 function IconForLink($protocol_or_url) {
121 global $URL_LINK_ICONS;
123 list ($proto) = explode(':', $protocol_or_url, 2);
125 if (isset($URL_LINK_ICONS[$proto])) {
126 $linkimg = $URL_LINK_ICONS[$proto];
128 elseif (isset($URL_LINK_ICONS['*'])) {
129 $linkimg = $URL_LINK_ICONS['*'];
135 return Element('img', array('src' => DataURL($linkimg),
137 'class' => 'linkicon'));
141 function LinkURL($url, $linktext = '') {
142 // FIXME: Is this needed (or sufficient?)
143 if(ereg("[<>\"]", $url)) {
144 return Element('strong',
145 QElement('u', array('class' => 'baduri'),
146 _("BAD URL -- remove all of <, >, \"")));
149 $attr['href'] = $url;
151 if (empty($linktext)) {
153 $attr['class'] = 'rawurl';
156 $attr['class'] = 'namedurl';
159 return Element('a', $attr,
160 IconForLink($url) . htmlspecialchars($linktext));
163 function LinkWikiWord($wikiword, $linktext='') {
165 if ($dbi->isWikiPage($wikiword))
166 return LinkExistingWikiWord($wikiword, $linktext);
168 return LinkUnknownWikiWord($wikiword, $linktext);
172 function LinkExistingWikiWord($wikiword, $linktext='') {
173 if (empty($linktext)) {
174 $linktext = $wikiword;
175 if (defined("autosplit_wikiwords"))
176 $linktext=split_pagename($linktext);
180 $class = 'named-wiki';
182 return QElement('a', array('href' => WikiURL($wikiword),
187 function LinkUnknownWikiWord($wikiword, $linktext='') {
188 if (empty($linktext)) {
189 $linktext = $wikiword;
190 if (defined("autosplit_wikiwords"))
191 $linktext=split_pagename($linktext);
192 $class = 'wikiunknown';
195 $class = 'named-wikiunknown';
198 return Element('span', array('class' => $class),
200 array('href' => WikiURL($wikiword, array('action' => 'edit'))),
202 . Element('u', $linktext));
205 function LinkImage($url, $alt='[External Image]') {
206 // FIXME: Is this needed (or sufficient?)
207 // As long as the src in htmlspecialchars()ed I think it's safe.
208 if(ereg("[<>\"]", $url)) {
209 return Element('strong',
210 QElement('u', array('class' => 'baduri'),
211 _("BAD URL -- remove all of <, >, \"")));
213 return Element('img', array('src' => $url, 'alt' => $alt));
216 // converts spaces to tabs
217 function CookSpaces($pagearray) {
218 return preg_replace("/ {3,8}/", "\t", $pagearray);
223 var $items = array();
226 function push($item) {
227 $this->items[$this->size] = $item;
233 if ($this->size == 0) {
234 return false; // stack is empty
237 return $this->items[$this->size];
246 return $this->items[$this->size - 1];
252 // end class definition
255 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))
266 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
268 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
272 $a['size'] = $m[1] ? $m[1] : 30;
277 $formargs['enctype'] = 'multipart/form-data';
278 $contents .= Element('input',
279 array('name' => 'MAX_FILE_SIZE',
280 'value' => MAX_UPLOAD_SIZE,
281 'type' => 'hidden'));
282 $formargs['method'] = 'post';
286 $contents .= Element('input', $a);
289 $row = Element('td', $contents);
291 if (!empty($button_text)) {
292 $row .= Element('td', Element('input', array('type' => 'submit',
294 'value' => $button_text)));
297 return Element('form', $formargs,
298 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
299 Element('tr', $row)));
302 function SplitQueryArgs ($query_args = '')
304 $split_args = split('&', $query_args);
306 while (list($key, $val) = each($split_args))
307 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
308 $args[$m[1]] = $m[2];
312 function LinkPhpwikiURL($url, $text = '') {
315 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
316 return Element('strong',
317 QElement('u', array('class' => 'baduri'),
318 'BAD phpwiki: URL'));
320 $pagename = urldecode($m[1]);
323 if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
324 // Convert old style links (to not break diff links in RecentChanges).
325 $pagename = urldecode($m[2]);
326 $args = array("action" => $m[1]);
329 $args = SplitQueryArgs($qargs);
332 if (empty($pagename))
333 $pagename = $GLOBALS['pagename'];
335 if (isset($args['action']) && $args['action'] == 'browse')
336 unset($args['action']);
338 if (empty($args['action']))
340 else if (is_safe_action($args['action']))
341 $class = 'wikiaction';
343 if (empty($args['action']) || is_safe_action($args['action']))
344 $class = 'wikiaction';
346 // Don't allow administrative links on unlocked pages.
347 // FIXME: Ugh: don't like this...
349 $page = $dbi->getPage($GLOBALS['pagename']);
350 if (!$page->get('locked'))
351 return QElement('u', array('class' => 'wikiunsafe'),
352 _("Lock page to enable link"));
354 $class = 'wikiadmin';
357 // FIXME: ug, don't like this
358 if (preg_match('/=\d*\(/', $qargs))
359 return MakeWikiForm($pagename, $args, $class, $text);
361 $text = htmlspecialchars($text);
363 $text = QElement('span', array('class' => 'rawurl'), $url);
365 return Element('a', array('href' => WikiURL($pagename, $args),
370 function ParseAndLink($bracketlink) {
371 global $dbi, $AllowedProtocols, $InlineImages;
372 global $InterWikiLinkRegexp;
374 // $bracketlink will start and end with brackets; in between
375 // will be either a page name, a URL or both separated by a pipe.
377 // strip brackets and leading space
378 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
379 // match the contents
380 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
382 if (isset($matches[3])) {
383 // named link of the form "[some link name | http://blippy.com/]"
384 $URL = trim($matches[3]);
385 $linkname = trim($matches[1]);
388 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
389 $URL = trim($matches[1]);
391 $linktype = 'simple';
394 if ($dbi->isWikiPage($URL)) {
395 $link['type'] = "wiki-$linktype";
396 $link['link'] = LinkExistingWikiWord($URL, $linkname);
397 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
398 // if it's an image, embed it; otherwise, it's a regular link
399 if (preg_match("/($InlineImages)$/i", $URL)) {
400 $link['type'] = "image-$linktype";
401 $link['link'] = LinkImage($URL, $linkname);
403 $link['type'] = "url-$linktype";
404 $link['link'] = LinkURL($URL, $linkname);
406 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
407 $link['type'] = "url-wiki-$linktype";
408 $link['link'] = LinkPhpwikiURL($URL, $linkname);
409 } elseif (preg_match("#^\d+$#", $URL)) {
410 $link['type'] = "footnote-$linktype";
411 $link['link'] = $URL;
412 } elseif (function_exists('LinkInterWikiLink') &&
413 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
414 $link['type'] = "interwiki-$linktype";
415 $link['link'] = LinkInterWikiLink($URL, $linkname);
417 $link['type'] = "wiki-unknown-$linktype";
418 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
425 function ExtractWikiPageLinks($content)
427 global $WikiNameRegexp;
429 if (is_string($content))
430 $content = explode("\n", $content);
432 $wikilinks = array();
433 foreach ($content as $line) {
434 // remove plugin code
435 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
436 // remove escaped '['
437 $line = str_replace('[[', ' ', $line);
439 // bracket links (only type wiki-* is of interest)
440 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/", $line, $brktlinks);
441 for ($i = 0; $i < $numBracketLinks; $i++) {
442 $link = ParseAndLink($brktlinks[0][$i]);
443 if (preg_match("#^wiki#", $link['type']))
444 $wikilinks[$brktlinks[2][$i]] = 1;
446 $brktlink = preg_quote($brktlinks[0][$i]);
447 $line = preg_replace("|$brktlink|", '', $line);
450 // BumpyText old-style wiki links
451 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
452 for ($i = 0; isset($link[0][$i]); $i++) {
453 if($link[0][$i][0] <> '!')
454 $wikilinks[$link[0][$i]] = 1;
458 return array_keys($wikilinks);
461 function LinkRelatedPages($dbi, $pagename)
463 // currently not supported everywhere
464 if(!function_exists('GetWikiPageLinks'))
467 //FIXME: fix or toss?
468 $links = GetWikiPageLinks($dbi, $pagename);
470 $txt = QElement('strong',
471 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
472 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
473 if(isset($links['in'][$i])) {
474 list($name, $score) = $links['in'][$i];
475 $txt .= LinkExistingWikiWord($name) . " ($score), ";
479 $txt .= "\n" . Element('br');
480 $txt .= Element('strong',
481 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
482 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
483 if(isset($links['out'][$i])) {
484 list($name, $score) = $links['out'][$i];
485 if($dbi->isWikiPage($name))
486 $txt .= LinkExistingWikiWord($name) . " ($score), ";
490 $txt .= "\n" . Element('br');
491 $txt .= Element('strong',
492 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
493 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
494 if(isset($links['popular'][$i])) {
495 list($name, $score) = $links['popular'][$i];
496 $txt .= LinkExistingWikiWord($name) . " ($score), ";
505 * Split WikiWords in page names.
507 * It has been deemed useful to split WikiWords (into "Wiki Words")
508 * in places like page titles. This is rumored to help search engines
511 * @param $page string The page name.
513 * @return string The split name.
515 function split_pagename ($page) {
517 if (preg_match("/\s/", $page))
518 return $page; // Already split --- don't split any more.
520 // FIXME: this algorithm is Anglo-centric.
523 // This mess splits between a lower-case letter followed by either an upper-case
524 // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
526 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
527 // This the single-letter words 'I' and 'A' from any following capitalized words.
528 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
529 // Split numerals from following letters.
530 $RE[] = '/(\d)([[:alpha:]])/';
532 foreach ($RE as $key => $val)
533 $RE[$key] = pcre_fix_posix_classes($val);
536 foreach ($RE as $regexp)
537 $page = preg_replace($regexp, '\\1 \\2', $page);
541 function NoSuchRevision ($page, $version) {
542 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
543 $html .= QElement('p',
544 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
545 $version, $page->getName())) . "\n";
547 include_once('lib/Template.php');
548 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
554 * Get time offset for local time zone.
556 * @param $time time_t Get offset for this time. Default: now.
557 * @param $no_colon boolean Don't put colon between hours and minutes.
558 * @return string Offset as a string in the format +HH:MM.
560 function TimezoneOffset ($time = false, $no_colon = false) {
563 $secs = date('Z', $time);
571 $colon = $no_colon ? '' : ':';
572 $mins = intval(($secs + 30) / 60);
573 return sprintf("%s%02d%s%02d",
574 $sign, $mins / 60, $colon, $mins % 60);
578 * Format time in ISO-8601 format.
580 * @param $time time_t Time. Default: now.
581 * @return string Date and time in ISO-8601 format.
583 function Iso8601DateTime ($time = false) {
586 $tzoff = TimezoneOffset($time);
587 $date = date('Y-m-d', $time);
588 $time=date('H:i:s', $time);
589 return $date . 'T' . $time . $tzoff;
593 * Format time in RFC-2822 format.
595 * @param $time time_t Time. Default: now.
596 * @return string Date and time in RFC-2822 format.
598 function Rfc2822DateTime ($time = false) {
601 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
605 * Format time to standard 'ctime' format.
607 * @param $time time_t Time. Default: now.
608 * @return string Date and time in RFC-2822 format.
610 function CTime ($time = false)
614 return date("D M j H:i:s Y", $time);
620 * Internationalized printf.
622 * This is essentially the same as PHP's built-in printf
623 * with the following exceptions:
625 * <li> It passes the format string through gettext().
626 * <li> It supports the argument reordering extensions.
633 * __printf("Differences between versions %s and %s of %s",
634 * $new_link, $old_link, $page_link);
637 * Then in locale/po/de.po, one can reorder the printf arguments:
640 * msgid "Differences between %s and %s of %s."
641 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
644 * (Note that while PHP tries to expand $vars within double-quotes,
645 * the values in msgstr undergo no such expansion, so the '$'s okay...)
647 * One shouldn't use reordered arguments in the default format string.
648 * Backslashes in the default string would be necessary to escape the '$'s,
649 * and they'll cause all kinds of trouble....
651 function __printf ($fmt) {
652 $args = func_get_args();
654 echo __vsprintf($fmt, $args);
658 * Internationalized sprintf.
660 * This is essentially the same as PHP's built-in printf
661 * with the following exceptions:
663 * <li> It passes the format string through gettext().
664 * <li> It supports the argument reordering extensions.
669 function __sprintf ($fmt) {
670 $args = func_get_args();
672 return __vsprintf($fmt, $args);
676 * Internationalized vsprintf.
678 * This is essentially the same as PHP's built-in printf
679 * with the following exceptions:
681 * <li> It passes the format string through gettext().
682 * <li> It supports the argument reordering extensions.
687 function __vsprintf ($fmt, $args) {
688 $fmt = gettext($fmt);
689 // PHP's sprintf doesn't support variable with specifiers,
690 // like sprintf("%*s", 10, "x"); --- so we won't either.
692 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
693 // Format string has '%2$s' style argument reordering.
694 // PHP doesn't support this.
695 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
696 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),'%1\$s','%s'), E_USER_WARNING);
698 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
701 // Reorder arguments appropriately.
702 foreach($m[1] as $argnum) {
703 if ($argnum < 1 || $argnum > count($args))
704 trigger_error(sprintf(_("%s: argument index out of range"),$argnum), E_USER_WARNING);
705 $newargs[] = $args[$argnum - 1];
710 // Not all PHP's have vsprintf, so...
711 array_unshift($args, $fmt);
712 return call_user_func_array('sprintf', $args);
716 // (c-file-style: "gnu")
721 // c-hanging-comment-ender-p: nil
722 // indent-tabs-mode: nil