1 <?php rcs_id('$Id: stdlib.php,v 1.85 2002-01-21 06:55:47 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)
14 class Stack { push($item), pop(), cnt(), top() }
15 CookSpaces($pagearray)
16 MakeWikiForm ($pagename, $args, $class, $button_text)
17 SplitQueryArgs ($query_args)
18 LinkPhpwikiURL($url, $text)
19 ParseAndLink($bracketlink)
20 ExtractWikiPageLinks($content)
21 LinkRelatedPages($dbi, $pagename)
22 split_pagename ($page)
23 NoSuchRevision ($page, $version)
24 TimezoneOffset ($time, $no_colon)
25 Iso8601DateTime ($time)
26 Rfc2822DateTime ($time)
30 __vsprintf ($fmt, $args)
32 function moved => LinkInterWikiLink($link, $linktext)
33 (see /lib/interwiki.php)
34 function moved => LinkUnknownWikiWord($wikiword, $linktext)
36 function gone => UpdateRecentChanges($dbi, $pagename, $isnewpage)
37 (see /lib/plugin/RecentChanges.php)
42 function WikiURL($pagename, $args = '', $get_abs_url = false) {
43 if (is_array($args)) {
45 foreach ($args as $key => $val) {
46 $enc_args[] = urlencode($key) . '=' . urlencode($val);
48 $args = join('&', $enc_args);
52 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
53 $url .= rawurlencode($pagename);
58 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
59 $url .= "?pagename=" . rawurlencode($pagename);
66 define('NO_END_TAG_PAT',
67 '/^' . join('|', array('area', 'base', 'basefont',
70 'isindex', 'link', 'meta',
73 function StartTag($tag, $args = '') {
75 if (is_array($args)) {
76 while (list($key, $val) = each($args))
78 if (is_string($val) || is_numeric($val))
79 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
81 $s .= " $key=\"$key\"";
88 function Element($tag, $args = '', $content = '') {
90 if (!is_array($args)) {
94 $html = StartTag($tag, $args);
95 if (preg_match(NO_END_TAG_PAT, $tag)) {
97 return preg_replace('/>$/', " />", $html);
100 $html .= "</$tag>";//FIXME: newline might not always be desired.
105 function QElement($tag, $args = '', $content = '')
108 return Element($tag, $args, htmlspecialchars($content));
111 return Element($tag, htmlspecialchars($content));
115 function IconForLink($protocol_or_url) {
118 list ($proto) = explode(':', $protocol_or_url, 2);
119 $src = $Theme->getLinkIconURL($proto);
123 return Element('img', array('src' => $src,
125 'class' => 'linkicon'));
129 function LinkURL($url, $linktext = '') {
130 // FIXME: Is this needed (or sufficient?)
131 if(ereg("[<>\"]", $url)) {
132 return Element('strong',
133 QElement('u', array('class' => 'baduri'),
134 _("BAD URL -- remove all of <, >, \"")));
137 $attr['href'] = $url;
139 if (empty($linktext)) {
141 $attr['class'] = 'rawurl';
143 $attr['class'] = 'namedurl';
145 return Element('a', $attr,
146 IconForLink($url) . htmlspecialchars($linktext));
149 function LinkWikiWord($wikiword, $linktext = '', $version = false) {
150 $link = _LinkWikiWord($wikiword, $linktext, $version);
151 return $link->asXML();
154 // This function will be renamed LinkWikiWord once changeover
155 // to object based HTML generation is complete.
156 function _LinkWikiWord($wikiword, $linktext = '', $version = false) {
158 if ($dbi->isWikiPage($wikiword))
159 $link = $Theme->linkExistingWikiWord($wikiword, $linktext, $version);
161 $link = $Theme->linkUnknownWikiWord($wikiword, $linktext);
165 //This function will be deleted once all references to it are updated.
166 function LinkExistingWikiWord($wikiword, $linktext = '', $version = false) {
168 $link = $Theme->linkExistingWikiWord($wikiword, $linktext, $version);
169 return $link->asXML();
173 function LinkImage($url, $alt = '[External Image]') {
174 // FIXME: Is this needed (or sufficient?)
175 // As long as the src in htmlspecialchars()ed I think it's safe.
176 if(ereg("[<>\"]", $url)) {
177 return Element('strong',
178 QElement('u', array('class' => 'baduri'),
179 _("BAD URL -- remove all of <, >, \"")));
181 return Element('img', array('src' => $url, 'alt' => $alt));
184 // converts spaces to tabs
185 function CookSpaces($pagearray) {
186 return preg_replace("/ {3,8}/", "\t", $pagearray);
191 var $items = array();
194 function push($item) {
195 $this->items[$this->size] = $item;
201 if ($this->size == 0) {
202 return false; // stack is empty
205 return $this->items[$this->size];
214 return $this->items[$this->size - 1];
220 // end class definition
223 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
224 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
225 $formargs['method'] = 'get';
226 $formargs['class'] = $class;
231 while (list($key, $val) = each($args)) {
232 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
234 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
237 $a['size'] = $m[1] ? $m[1] : 30;
242 $formargs['enctype'] = 'multipart/form-data';
243 $contents .= Element('input',
244 array('name' => 'MAX_FILE_SIZE',
245 'value' => MAX_UPLOAD_SIZE,
246 'type' => 'hidden'));
247 $formargs['method'] = 'post';
251 $contents .= Element('input', $a);
254 $row = Element('td', $contents);
256 if (!empty($button_text)) {
257 $row .= Element('td',
258 Element('input', array('type' => 'submit',
260 'value' => $button_text)));
263 return Element('form', $formargs,
264 Element('table', array('cellspacing' => 0,
267 Element('tr', $row)));
270 function SplitQueryArgs ($query_args = '')
272 $split_args = split('&', $query_args);
274 while (list($key, $val) = each($split_args))
275 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
276 $args[$m[1]] = $m[2];
280 function LinkPhpwikiURL($url, $text = '') {
283 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
284 return Element('strong',
285 QElement('u', array('class' => 'baduri'),
286 'BAD phpwiki: URL'));
288 $pagename = urldecode($m[1]);
291 if (empty($pagename) &&
292 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m))
294 // Convert old style links (to not break diff links in
296 $pagename = urldecode($m[2]);
297 $args = array("action" => $m[1]);
300 $args = SplitQueryArgs($qargs);
303 if (empty($pagename))
304 $pagename = $GLOBALS['pagename'];
306 if (isset($args['action']) && $args['action'] == 'browse')
307 unset($args['action']);
309 if (empty($args['action']))
311 else if (is_safe_action($args['action']))
312 $class = 'wikiaction';
314 if (empty($args['action']) || is_safe_action($args['action']))
315 $class = 'wikiaction';
317 // Don't allow administrative links on unlocked pages.
318 // FIXME: Ugh: don't like this...
320 $page = $dbi->getPage($GLOBALS['pagename']);
321 if (!$page->get('locked'))
322 return QElement('u', array('class' => 'wikiunsafe'),
323 _("Lock page to enable link"));
325 $class = 'wikiadmin';
328 // FIXME: ug, don't like this
329 if (preg_match('/=\d*\(/', $qargs))
330 return MakeWikiForm($pagename, $args, $class, $text);
332 $text = htmlspecialchars($text);
334 $text = QElement('span', array('class' => 'rawurl'), $url);
336 return Element('a', array('href' => WikiURL($pagename, $args),
341 function ParseAndLink($bracketlink) {
342 global $dbi, $AllowedProtocols, $InlineImages;
343 global $InterWikiLinkRegexp;
345 // $bracketlink will start and end with brackets; in between will
346 // be either a page name, a URL or both separated by a pipe.
348 // strip brackets and leading space
349 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
350 // match the contents
351 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
353 if (isset($matches[3])) {
354 // named link of the form "[some link name | http://blippy.com/]"
355 $URL = trim($matches[3]);
356 $linkname = trim($matches[1]);
359 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
360 $URL = trim($matches[1]);
362 $linktype = 'simple';
365 if ($dbi->isWikiPage($URL)) {
366 $link['type'] = "wiki-$linktype";
367 $link['link'] = LinkExistingWikiWord($URL, $linkname);
368 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
369 // if it's an image, embed it; otherwise, it's a regular link
370 if (preg_match("/($InlineImages)$/i", $URL)) {
371 $link['type'] = "image-$linktype";
372 $link['link'] = LinkImage($URL, $linkname);
374 $link['type'] = "url-$linktype";
375 $link['link'] = LinkURL($URL, $linkname);
377 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
378 $link['type'] = "url-wiki-$linktype";
379 $link['link'] = LinkPhpwikiURL($URL, $linkname);
380 } elseif (preg_match("#^\d+$#", $URL)) {
381 $link['type'] = "footnote-$linktype";
382 $link['link'] = $URL;
383 } elseif (function_exists('LinkInterWikiLink') &&
384 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
385 $link['type'] = "interwiki-$linktype";
386 $link['link'] = LinkInterWikiLink($URL, $linkname);
388 $link['type'] = "wiki-unknown-$linktype";
390 $uww = $Theme->linkUnknownWikiWord($URL, $linkname);
391 $link['link'] = $uww->asXML();
398 function ExtractWikiPageLinks($content) {
399 global $WikiNameRegexp;
401 if (is_string($content))
402 $content = explode("\n", $content);
404 $wikilinks = array();
405 foreach ($content as $line) {
406 // remove plugin code
407 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
408 // remove escaped '['
409 $line = str_replace('[[', ' ', $line);
411 // bracket links (only type wiki-* is of interest)
412 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
414 for ($i = 0; $i < $numBracketLinks; $i++) {
415 $link = ParseAndLink($brktlinks[0][$i]);
416 if (preg_match("#^wiki#", $link['type']))
417 $wikilinks[$brktlinks[2][$i]] = 1;
419 $brktlink = preg_quote($brktlinks[0][$i]);
420 $line = preg_replace("|$brktlink|", '', $line);
423 // BumpyText old-style wiki links
424 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
425 for ($i = 0; isset($link[0][$i]); $i++) {
426 if($link[0][$i][0] <> '!')
427 $wikilinks[$link[0][$i]] = 1;
431 return array_keys($wikilinks);
434 function LinkRelatedPages($dbi, $pagename)
436 // currently not supported everywhere
437 if(!function_exists('GetWikiPageLinks'))
440 //FIXME: fix or toss?
441 $links = GetWikiPageLinks($dbi, $pagename);
443 $txt = QElement('strong',
444 sprintf (_("%d best incoming links:"), NUM_RELATED_PAGES));
445 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
446 if(isset($links['in'][$i])) {
447 list($name, $score) = $links['in'][$i];
448 $txt .= LinkExistingWikiWord($name) . " ($score), ";
452 $txt .= "\n" . Element('br');
453 $txt .= Element('strong',
454 sprintf (_("%d best outgoing links:"), NUM_RELATED_PAGES));
455 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
456 if(isset($links['out'][$i])) {
457 list($name, $score) = $links['out'][$i];
458 if($dbi->isWikiPage($name))
459 $txt .= LinkExistingWikiWord($name) . " ($score), ";
463 $txt .= "\n" . Element('br');
464 $txt .= Element('strong',
465 sprintf (_("%d most popular nearby:"), NUM_RELATED_PAGES));
466 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
467 if(isset($links['popular'][$i])) {
468 list($name, $score) = $links['popular'][$i];
469 $txt .= LinkExistingWikiWord($name) . " ($score), ";
478 * Split WikiWords in page names.
480 * It has been deemed useful to split WikiWords (into "Wiki Words") in
481 * places like page titles. This is rumored to help search engines
484 * @param $page string The page name.
486 * @return string The split name.
488 function split_pagename ($page) {
490 if (preg_match("/\s/", $page))
491 return $page; // Already split --- don't split any more.
493 // FIXME: this algorithm is Anglo-centric.
496 // This mess splits between a lower-case letter followed by
497 // either an upper-case or a numeral; except that it wont
498 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
499 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
500 // This the single-letter words 'I' and 'A' from any following
501 // capitalized words.
502 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
503 // Split numerals from following letters.
504 $RE[] = '/(\d)([[:alpha:]])/';
506 foreach ($RE as $key => $val)
507 $RE[$key] = pcre_fix_posix_classes($val);
510 foreach ($RE as $regexp)
511 $page = preg_replace($regexp, '\\1 \\2', $page);
515 function NoSuchRevision ($page, $version) {
516 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
517 $html .= QElement('p',
518 sprintf(_("I'm sorry. Version %d of %s is not in my database."),
519 $version, $page->getName())) . "\n";
521 include_once('lib/Template.php');
522 echo GeneratePage('MESSAGE', $html, _("Bad Version"));
528 * Get time offset for local time zone.
530 * @param $time time_t Get offset for this time. Default: now.
531 * @param $no_colon boolean Don't put colon between hours and minutes.
532 * @return string Offset as a string in the format +HH:MM.
534 function TimezoneOffset ($time = false, $no_colon = false) {
537 $secs = date('Z', $time);
545 $colon = $no_colon ? '' : ':';
546 $mins = intval(($secs + 30) / 60);
547 return sprintf("%s%02d%s%02d",
548 $sign, $mins / 60, $colon, $mins % 60);
552 * Format time in ISO-8601 format.
554 * @param $time time_t Time. Default: now.
555 * @return string Date and time in ISO-8601 format.
557 function Iso8601DateTime ($time = false) {
560 $tzoff = TimezoneOffset($time);
561 $date = date('Y-m-d', $time);
562 $time = date('H:i:s', $time);
563 return $date . 'T' . $time . $tzoff;
567 * Format time in RFC-2822 format.
569 * @param $time time_t Time. Default: now.
570 * @return string Date and time in RFC-2822 format.
572 function Rfc2822DateTime ($time = false) {
575 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
579 * Format time to standard 'ctime' format.
581 * @param $time time_t Time. Default: now.
582 * @return string Date and time in RFC-2822 format.
584 function CTime ($time = false)
588 return date("D M j H:i:s Y", $time);
594 * Internationalized printf.
596 * This is essentially the same as PHP's built-in printf
597 * with the following exceptions:
599 * <li> It passes the format string through gettext().
600 * <li> It supports the argument reordering extensions.
607 * __printf("Differences between versions %s and %s of %s",
608 * $new_link, $old_link, $page_link);
611 * Then in locale/po/de.po, one can reorder the printf arguments:
614 * msgid "Differences between %s and %s of %s."
615 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
618 * (Note that while PHP tries to expand $vars within double-quotes,
619 * the values in msgstr undergo no such expansion, so the '$'s
622 * One shouldn't use reordered arguments in the default format string.
623 * Backslashes in the default string would be necessary to escape the
624 * '$'s, and they'll cause all kinds of trouble....
626 function __printf ($fmt) {
627 $args = func_get_args();
629 echo __vsprintf($fmt, $args);
633 * Internationalized sprintf.
635 * This is essentially the same as PHP's built-in printf with the
636 * following exceptions:
639 * <li> It passes the format string through gettext().
640 * <li> It supports the argument reordering extensions.
645 function __sprintf ($fmt) {
646 $args = func_get_args();
648 return __vsprintf($fmt, $args);
652 * Internationalized vsprintf.
654 * This is essentially the same as PHP's built-in printf with the
655 * following exceptions:
658 * <li> It passes the format string through gettext().
659 * <li> It supports the argument reordering extensions.
664 function __vsprintf ($fmt, $args) {
665 $fmt = gettext($fmt);
666 // PHP's sprintf doesn't support variable with specifiers,
667 // like sprintf("%*s", 10, "x"); --- so we won't either.
669 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
670 // Format string has '%2$s' style argument reordering.
671 // PHP doesn't support this.
672 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
673 // literal variable name substitution only to keep locale
674 // strings uncluttered
675 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
676 '%1\$s','%s'), E_USER_WARNING);
678 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
681 // Reorder arguments appropriately.
682 foreach($m[1] as $argnum) {
683 if ($argnum < 1 || $argnum > count($args))
684 trigger_error(sprintf(_("%s: argument index out of range"),
685 $argnum), E_USER_WARNING);
686 $newargs[] = $args[$argnum - 1];
691 // Not all PHP's have vsprintf, so...
692 array_unshift($args, $fmt);
693 return call_user_func_array('sprintf', $args);
697 // Class introspections
699 /** Determine whether object is of a specified type.
701 * @param $object object An object.
702 * @param $class string Class name.
703 * @return bool True iff $object is a $class
704 * or a sub-type of $class.
706 function isa ($object, $class)
708 $lclass = strtolower($class);
710 return is_object($object)
711 && ( get_class($object) == strtolower($lclass)
712 || is_subclass_of($object, $lclass) );
715 /** Determine whether (possible) object has method.
717 * @param $object mixed Object
718 * @param $method string Method name
719 * @return bool True iff $object is an object with has method $method.
721 function can ($object, $method)
723 return is_object($object) && method_exists($object, strtolower($method));
726 // (c-file-style: "gnu")
731 // c-hanging-comment-ender-p: nil
732 // indent-tabs-mode: nil