1 <?php rcs_id('$Id: stdlib.php,v 1.79 2002-01-17 23:14:22 dairiki Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
7 Element($tag, $args, $content)
8 QElement($tag, $args, $content)
9 IconForLink($protocol_or_url)
10 LinkURL($url, $linktext)
11 LinkWikiWord($wikiword, $linktext)
12 LinkExistingWikiWord($wikiword, $linktext)
13 LinkUnknownWikiWord($wikiword, $linktext)
15 class Stack { push($item), pop(), cnt(), top() }
16 CookSpaces($pagearray)
17 MakeWikiForm ($pagename, $args, $class, $button_text)
18 SplitQueryArgs ($query_args)
19 LinkPhpwikiURL($url, $text)
20 ParseAndLink($bracketlink)
21 ExtractWikiPageLinks($content)
22 LinkRelatedPages($dbi, $pagename)
23 split_pagename ($page)
24 NoSuchRevision ($page, $version)
25 TimezoneOffset ($time, $no_colon)
26 Iso8601DateTime ($time)
27 Rfc2822DateTime ($time)
31 __vsprintf ($fmt, $args)
33 function moved => LinkInterWikiLink($link, $linktext)
34 (see /lib/interwiki.php)
35 function gone => UpdateRecentChanges($dbi, $pagename, $isnewpage)
36 (see /lib/plugin/RecentChanges.php)
41 function WikiURL($pagename, $args = '', $get_abs_url = false) {
42 if (is_array($args)) {
44 foreach ($args as $key => $val) {
45 $enc_args[] = urlencode($key) . '=' . urlencode($val);
47 $args = join('&', $enc_args);
51 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
52 $url .= rawurlencode($pagename);
57 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
58 $url .= "?pagename=" . rawurlencode($pagename);
65 define('NO_END_TAG_PAT',
66 '/^' . join('|', array('area', 'base', 'basefont',
69 'isindex', 'link', 'meta',
72 function StartTag($tag, $args = '') {
74 if (is_array($args)) {
75 while (list($key, $val) = each($args))
77 if (is_string($val) || is_numeric($val))
78 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
80 $s .= " $key=\"$key\"";
87 function Element($tag, $args = '', $content = '') {
89 if (!is_array($args)) {
93 $html = StartTag($tag, $args);
94 if (preg_match(NO_END_TAG_PAT, $tag)) {
96 return preg_replace('/>$/', " />", $html);
99 $html .= "</$tag>";//FIXME: newline might not always be desired.
104 function QElement($tag, $args = '', $content = '')
107 return Element($tag, $args, htmlspecialchars($content));
110 return Element($tag, htmlspecialchars($content));
114 function IconForLink($protocol_or_url) {
117 list ($proto) = explode(':', $protocol_or_url, 2);
118 $src = $Theme->getLinkIconURL($proto);
122 return Element('img', array('src' => $src,
124 'class' => 'linkicon'));
128 function LinkURL($url, $linktext = '') {
129 // FIXME: Is this needed (or sufficient?)
130 if(ereg("[<>\"]", $url)) {
131 return Element('strong',
132 QElement('u', array('class' => 'baduri'),
133 _("BAD URL -- remove all of <, >, \"")));
136 $attr['href'] = $url;
138 if (empty($linktext)) {
140 $attr['class'] = 'rawurl';
142 $attr['class'] = 'namedurl';
144 return Element('a', $attr,
145 IconForLink($url) . htmlspecialchars($linktext));
148 function LinkWikiWord($wikiword, $linktext = '', $version = false) {
150 if ($dbi->isWikiPage($wikiword))
151 return LinkExistingWikiWord($wikiword, $linktext);
153 return LinkUnknownWikiWord($wikiword, $linktext);
156 function LinkExistingWikiWord($wikiword, $linktext = '', $version = false) {
157 if (empty($linktext)) {
158 $linktext = $wikiword;
159 if (defined("autosplit_wikiwords"))
160 $linktext = split_pagename($linktext);
164 $class = 'named-wiki';
167 if ($version !== false)
168 $attr['version'] = $version;
170 return QElement('a', array('href' => WikiURL($wikiword, $attr),
175 function LinkUnknownWikiWord($wikiword, $linktext = '', $version = false) {
176 if (empty($linktext)) {
177 $linktext = $wikiword;
178 if (defined("autosplit_wikiwords"))
179 $linktext=split_pagename($linktext);
180 $class = 'wikiunknown';
182 $class = 'named-wikiunknown';
184 $attr = array('action' => 'edit');
185 if ($version !== false)
186 $attr['version'] = $version;
188 $qmark = QElement('a', array('href' => WikiURL($wikiword, $attr)),
190 $text = QElement('u', $linktext);
192 if (defined('WIKIMARK_AFTER') && WIKIMARK_AFTER)
195 $text = $qmark . $text;
197 return Element('span', array('class' => $class), $text);
200 function LinkImage($url, $alt = '[External Image]') {
201 // FIXME: Is this needed (or sufficient?)
202 // As long as the src in htmlspecialchars()ed I think it's safe.
203 if(ereg("[<>\"]", $url)) {
204 return Element('strong',
205 QElement('u', array('class' => 'baduri'),
206 _("BAD URL -- remove all of <, >, \"")));
208 return Element('img', array('src' => $url, 'alt' => $alt));
211 // converts spaces to tabs
212 function CookSpaces($pagearray) {
213 return preg_replace("/ {3,8}/", "\t", $pagearray);
218 var $items = array();
221 function push($item) {
222 $this->items[$this->size] = $item;
228 if ($this->size == 0) {
229 return false; // stack is empty
232 return $this->items[$this->size];
241 return $this->items[$this->size - 1];
247 // end class definition
250 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
251 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
252 $formargs['method'] = 'get';
253 $formargs['class'] = $class;
258 while (list($key, $val) = each($args)) {
259 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
261 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
264 $a['size'] = $m[1] ? $m[1] : 30;
269 $formargs['enctype'] = 'multipart/form-data';
270 $contents .= Element('input',
271 array('name' => 'MAX_FILE_SIZE',
272 'value' => MAX_UPLOAD_SIZE,
273 'type' => 'hidden'));
274 $formargs['method'] = 'post';
278 $contents .= Element('input', $a);
281 $row = Element('td', $contents);
283 if (!empty($button_text)) {
284 $row .= Element('td',
285 Element('input', array('type' => 'submit',
287 'value' => $button_text)));
290 return Element('form', $formargs,
291 Element('table', array('cellspacing' => 0,
294 Element('tr', $row)));
297 function SplitQueryArgs ($query_args = '')
299 $split_args = split('&', $query_args);
301 while (list($key, $val) = each($split_args))
302 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
303 $args[$m[1]] = $m[2];
307 function LinkPhpwikiURL($url, $text = '') {
310 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
311 return Element('strong',
312 QElement('u', array('class' => 'baduri'),
313 'BAD phpwiki: URL'));
315 $pagename = urldecode($m[1]);
318 if (empty($pagename) &&
319 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m))
321 // Convert old style links (to not break diff links in
323 $pagename = urldecode($m[2]);
324 $args = array("action" => $m[1]);
327 $args = SplitQueryArgs($qargs);
330 if (empty($pagename))
331 $pagename = $GLOBALS['pagename'];
333 if (isset($args['action']) && $args['action'] == 'browse')
334 unset($args['action']);
336 if (empty($args['action']))
338 else if (is_safe_action($args['action']))
339 $class = 'wikiaction';
341 if (empty($args['action']) || is_safe_action($args['action']))
342 $class = 'wikiaction';
344 // Don't allow administrative links on unlocked pages.
345 // FIXME: Ugh: don't like this...
347 $page = $dbi->getPage($GLOBALS['pagename']);
348 if (!$page->get('locked'))
349 return QElement('u', array('class' => 'wikiunsafe'),
350 _("Lock page to enable link"));
352 $class = 'wikiadmin';
355 // FIXME: ug, don't like this
356 if (preg_match('/=\d*\(/', $qargs))
357 return MakeWikiForm($pagename, $args, $class, $text);
359 $text = htmlspecialchars($text);
361 $text = QElement('span', array('class' => 'rawurl'), $url);
363 return Element('a', array('href' => WikiURL($pagename, $args),
368 function ParseAndLink($bracketlink) {
369 global $dbi, $AllowedProtocols, $InlineImages;
370 global $InterWikiLinkRegexp;
372 // $bracketlink will start and end with brackets; in between will
373 // be either a page name, a URL or both separated by a pipe.
375 // strip brackets and leading space
376 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
377 // match the contents
378 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
380 if (isset($matches[3])) {
381 // named link of the form "[some link name | http://blippy.com/]"
382 $URL = trim($matches[3]);
383 $linkname = trim($matches[1]);
386 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
387 $URL = trim($matches[1]);
389 $linktype = 'simple';
392 if ($dbi->isWikiPage($URL)) {
393 $link['type'] = "wiki-$linktype";
394 $link['link'] = LinkExistingWikiWord($URL, $linkname);
395 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
396 // if it's an image, embed it; otherwise, it's a regular link
397 if (preg_match("/($InlineImages)$/i", $URL)) {
398 $link['type'] = "image-$linktype";
399 $link['link'] = LinkImage($URL, $linkname);
401 $link['type'] = "url-$linktype";
402 $link['link'] = LinkURL($URL, $linkname);
404 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
405 $link['type'] = "url-wiki-$linktype";
406 $link['link'] = LinkPhpwikiURL($URL, $linkname);
407 } elseif (preg_match("#^\d+$#", $URL)) {
408 $link['type'] = "footnote-$linktype";
409 $link['link'] = $URL;
410 } elseif (function_exists('LinkInterWikiLink') &&
411 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
412 $link['type'] = "interwiki-$linktype";
413 $link['link'] = LinkInterWikiLink($URL, $linkname);
415 $link['type'] = "wiki-unknown-$linktype";
416 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
423 function ExtractWikiPageLinks($content) {
424 global $WikiNameRegexp;
426 if (is_string($content))
427 $content = explode("\n", $content);
429 $wikilinks = array();
430 foreach ($content as $line) {
431 // remove plugin code
432 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
433 // remove escaped '['
434 $line = str_replace('[[', ' ', $line);
436 // bracket links (only type wiki-* is of interest)
437 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
439 for ($i = 0; $i < $numBracketLinks; $i++) {
440 $link = ParseAndLink($brktlinks[0][$i]);
441 if (preg_match("#^wiki#", $link['type']))
442 $wikilinks[$brktlinks[2][$i]] = 1;
444 $brktlink = preg_quote($brktlinks[0][$i]);
445 $line = preg_replace("|$brktlink|", '', $line);
448 // BumpyText old-style wiki links
449 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
450 for ($i = 0; isset($link[0][$i]); $i++) {
451 if($link[0][$i][0] <> '!')
452 $wikilinks[$link[0][$i]] = 1;
456 return array_keys($wikilinks);
459 function LinkRelatedPages($dbi, $pagename)
461 // currently not supported everywhere
462 if(!function_exists('GetWikiPageLinks'))
465 //FIXME: fix or toss?
466 $links = GetWikiPageLinks($dbi, $pagename);
468 $txt = QElement('strong',
469 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
470 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
471 if(isset($links['in'][$i])) {
472 list($name, $score) = $links['in'][$i];
473 $txt .= LinkExistingWikiWord($name) . " ($score), ";
477 $txt .= "\n" . Element('br');
478 $txt .= Element('strong',
479 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
480 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
481 if(isset($links['out'][$i])) {
482 list($name, $score) = $links['out'][$i];
483 if($dbi->isWikiPage($name))
484 $txt .= LinkExistingWikiWord($name) . " ($score), ";
488 $txt .= "\n" . Element('br');
489 $txt .= Element('strong',
490 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
491 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
492 if(isset($links['popular'][$i])) {
493 list($name, $score) = $links['popular'][$i];
494 $txt .= LinkExistingWikiWord($name) . " ($score), ";
503 * Split WikiWords in page names.
505 * It has been deemed useful to split WikiWords (into "Wiki Words") in
506 * places like page titles. This is rumored to help search engines
509 * @param $page string The page name.
511 * @return string The split name.
513 function split_pagename ($page) {
515 if (preg_match("/\s/", $page))
516 return $page; // Already split --- don't split any more.
518 // FIXME: this algorithm is Anglo-centric.
521 // This mess splits between a lower-case letter followed by
522 // either an upper-case or a numeral; except that it wont
523 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
524 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
525 // This the single-letter words 'I' and 'A' from any following
526 // capitalized words.
527 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
528 // Split numerals from following letters.
529 $RE[] = '/(\d)([[:alpha:]])/';
531 foreach ($RE as $key => $val)
532 $RE[$key] = pcre_fix_posix_classes($val);
535 foreach ($RE as $regexp)
536 $page = preg_replace($regexp, '\\1 \\2', $page);
540 function NoSuchRevision ($page, $version) {
541 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
542 $html .= QElement('p',
543 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
544 $version, $page->getName())) . "\n";
546 include_once('lib/Template.php');
547 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
553 * Get time offset for local time zone.
555 * @param $time time_t Get offset for this time. Default: now.
556 * @param $no_colon boolean Don't put colon between hours and minutes.
557 * @return string Offset as a string in the format +HH:MM.
559 function TimezoneOffset ($time = false, $no_colon = false) {
562 $secs = date('Z', $time);
570 $colon = $no_colon ? '' : ':';
571 $mins = intval(($secs + 30) / 60);
572 return sprintf("%s%02d%s%02d",
573 $sign, $mins / 60, $colon, $mins % 60);
577 * Format time in ISO-8601 format.
579 * @param $time time_t Time. Default: now.
580 * @return string Date and time in ISO-8601 format.
582 function Iso8601DateTime ($time = false) {
585 $tzoff = TimezoneOffset($time);
586 $date = date('Y-m-d', $time);
587 $time = date('H:i:s', $time);
588 return $date . 'T' . $time . $tzoff;
592 * Format time in RFC-2822 format.
594 * @param $time time_t Time. Default: now.
595 * @return string Date and time in RFC-2822 format.
597 function Rfc2822DateTime ($time = false) {
600 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
604 * Format time to standard 'ctime' format.
606 * @param $time time_t Time. Default: now.
607 * @return string Date and time in RFC-2822 format.
609 function CTime ($time = false)
613 return date("D M j H:i:s Y", $time);
619 * Internationalized printf.
621 * This is essentially the same as PHP's built-in printf
622 * with the following exceptions:
624 * <li> It passes the format string through gettext().
625 * <li> It supports the argument reordering extensions.
632 * __printf("Differences between versions %s and %s of %s",
633 * $new_link, $old_link, $page_link);
636 * Then in locale/po/de.po, one can reorder the printf arguments:
639 * msgid "Differences between %s and %s of %s."
640 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
643 * (Note that while PHP tries to expand $vars within double-quotes,
644 * the values in msgstr undergo no such expansion, so the '$'s
647 * One shouldn't use reordered arguments in the default format string.
648 * Backslashes in the default string would be necessary to escape the
649 * '$'s, 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 with the
661 * following exceptions:
664 * <li> It passes the format string through gettext().
665 * <li> It supports the argument reordering extensions.
670 function __sprintf ($fmt) {
671 $args = func_get_args();
673 return __vsprintf($fmt, $args);
677 * Internationalized vsprintf.
679 * This is essentially the same as PHP's built-in printf with the
680 * following exceptions:
683 * <li> It passes the format string through gettext().
684 * <li> It supports the argument reordering extensions.
689 function __vsprintf ($fmt, $args) {
690 $fmt = gettext($fmt);
691 // PHP's sprintf doesn't support variable with specifiers,
692 // like sprintf("%*s", 10, "x"); --- so we won't either.
694 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
695 // Format string has '%2$s' style argument reordering.
696 // PHP doesn't support this.
697 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
698 // literal variable name substitution only to keep locale
699 // strings uncluttered
700 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
701 '%1\$s','%s'), E_USER_WARNING);
703 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
706 // Reorder arguments appropriately.
707 foreach($m[1] as $argnum) {
708 if ($argnum < 1 || $argnum > count($args))
709 trigger_error(sprintf(_("%s: argument index out of range"),
710 $argnum), E_USER_WARNING);
711 $newargs[] = $args[$argnum - 1];
716 // Not all PHP's have vsprintf, so...
717 array_unshift($args, $fmt);
718 return call_user_func_array('sprintf', $args);
722 // Class introspections
724 /** Determine whether object is of a specified type.
726 * @param $object object An object.
727 * @param $class string Class name.
728 * @return bool True iff $object is a $class
729 * or a sub-type of $class.
731 function isa ($object, $class)
733 $lclass = strtolower($class);
735 return get_class($object) == strtolower($lclass)
736 || is_subclass_of($object, $lclass);
739 // (c-file-style: "gnu")
744 // c-hanging-comment-ender-p: nil
745 // indent-tabs-mode: nil