1 <?php rcs_id('$Id: stdlib.php,v 1.92 2002-01-27 04:38:38 dairiki Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
6 IconForLink($protocol_or_url)
7 LinkURL($url, $linktext)
8 LinkWikiWord($wikiword, $linktext)
11 MakeWikiForm ($pagename, $args, $class, $button_text)
12 SplitQueryArgs ($query_args)
13 LinkPhpwikiURL($url, $text)
14 LinkBracketLink($bracketlink)
15 ExtractWikiPageLinks($content)
17 class Stack { push($item), pop(), cnt(), top() }
19 split_pagename ($page)
20 NoSuchRevision ($request, $page, $version)
21 TimezoneOffset ($time, $no_colon)
22 Iso8601DateTime ($time)
23 Rfc2822DateTime ($time)
27 __vsprintf ($fmt, $args)
29 function: LinkInterWikiLink($link, $linktext)
30 moved to: lib/interwiki.php
31 function: linkExistingWikiWord($wikiword, $linktext, $version)
32 moved to: lib/Theme.php
33 function: LinkUnknownWikiWord($wikiword, $linktext)
34 moved to: lib/Theme.php
35 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
36 gone see: lib/plugin/RecentChanges.php
40 function WikiURL($pagename, $args = '', $get_abs_url = false) {
41 if (is_object($pagename)) {
42 if (isa($pagename, 'WikiDB_Page')) {
43 $pagename = $pagename->getName();
45 elseif (isa($pagename, 'WikiDB_PageRevision')) {
46 $page = $pagename->getPage();
47 $args['version'] = $pagename->getVersion();
48 $pagename = $page->getName();
52 if (is_array($args)) {
54 foreach ($args as $key => $val) {
55 $enc_args[] = urlencode($key) . '=' . urlencode($val);
57 $args = join('&', $enc_args);
61 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
62 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
67 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
68 $url .= "?pagename=" . rawurlencode($pagename);
75 function IconForLink($protocol_or_url) {
78 list ($proto) = explode(':', $protocol_or_url, 2);
79 $src = $Theme->getLinkIconURL($proto);
81 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon'));
86 function LinkURL($url, $linktext = '') {
87 // FIXME: Is this needed (or sufficient?)
88 if(ereg("[<>\"]", $url)) {
89 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
90 _("BAD URL -- remove all of <, >, \"")));
93 $link = HTML::a(array('href' => $url),
95 $linktext ? $linktext : $url);
97 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
101 function LinkWikiWord($wikiword, $linktext = '', $version = false) {
102 global $request, $Theme;
103 $dbi = $request->getDbh();
104 if ($dbi->isWikiPage($wikiword))
105 $link = $Theme->linkExistingWikiWord($wikiword, $linktext, $version);
107 $link = $Theme->linkUnknownWikiWord($wikiword, $linktext);
111 function LinkImage($url, $alt = '[External Image]') {
112 // FIXME: Is this needed (or sufficient?)
113 if(ereg("[<>\"]", $url)) {
114 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
115 _("BAD URL -- remove all of <, >, \"")));
118 $link = HTML::img(array('src' => $url, 'alt' => $alt));
120 $link->setAttr('class', 'inlineimage');
127 var $items = array();
130 function push($item) {
131 $this->items[$this->size] = $item;
137 if ($this->size == 0) {
138 return false; // stack is empty
141 return $this->items[$this->size];
150 return $this->items[$this->size - 1];
156 // end class definition
159 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
160 $form = HTML::form(array('action' => USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME,
163 'accept-charset' => CHARSET));
166 while (list($key, $val) = each($args)) {
167 $i = HTML::input(array('name' => $key, 'value' => $val, 'type' => 'hidden'));
169 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
170 $i->setAttr('size', $m[1] ? $m[1] : 30);
171 $i->setAttr('value', $m[2]);
173 $i->setAttr('type', 'text');
176 $i->setAttr('type', 'file');
177 $form->setAttr('enctype', 'multipart/form-data');
178 $form->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
179 'value' => MAX_UPLOAD_SIZE,
180 'type' => 'hidden')));
181 $form->setAttr('method', 'post');
183 $td->pushContent($i);
186 $form->pushContent($i);
191 if (!empty($button_text))
192 $tr->pushContent(HTML::td(HTML::input(array('type' => 'submit',
194 'value' => $button_text))));
195 $form->pushContent(HTML::table(array('cellspacing' => 0,
202 function SplitQueryArgs ($query_args = '')
204 $split_args = split('&', $query_args);
206 while (list($key, $val) = each($split_args))
207 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
208 $args[$m[1]] = $m[2];
212 function LinkPhpwikiURL($url, $text = '') {
215 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
216 return HTML::strong(array('class' => 'rawurl'),
217 HTML::u(array('class' => 'baduri'),
218 _("BAD phpwiki: URL")));
222 $pagename = urldecode($m[1]);
225 if (empty($pagename) &&
226 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
227 // Convert old style links (to not break diff links in
229 $pagename = urldecode($m[2]);
230 $args = array("action" => $m[1]);
233 $args = SplitQueryArgs($qargs);
236 if (empty($pagename))
237 $pagename = $GLOBALS['request']->getArg('pagename');
239 if (isset($args['action']) && $args['action'] == 'browse')
240 unset($args['action']);
243 if (empty($args['action']))
245 else if (is_safe_action($args['action']))
246 $class = 'wikiaction';
248 if (empty($args['action']) || is_safe_action($args['action']))
249 $class = 'wikiaction';
251 // Don't allow administrative links on unlocked pages.
252 $page = $GLOBALS['request']->getPage();
253 if (!$page->get('locked'))
254 return HTML::span(array('class' => 'wikiunsafe'),
255 HTML::u(_("Lock page to enable link")));
256 $class = 'wikiadmin';
259 // FIXME: ug, don't like this
260 if (preg_match('/=\d*\(/', $qargs))
261 return MakeWikiForm($pagename, $args, $class, $text);
263 $text = HTML::span(array('class' => 'rawurl'), $url);
265 return HTML::a(array('href' => WikiURL($pagename, $args),
270 function LinkBracketLink($bracketlink) {
271 global $request, $AllowedProtocols, $InlineImages;
272 global $InterWikiLinkRegexp, $Theme;
275 // $bracketlink will start and end with brackets; in between will
276 // be either a page name, a URL or both separated by a pipe.
278 // strip brackets and leading space
279 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
280 // match the contents
281 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
283 if (isset($matches[3])) {
284 // named link of the form "[some link name | http://blippy.com/]"
285 $URL = trim($matches[3]);
286 $linkname = trim($matches[1]);
288 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
289 $URL = trim($matches[1]);
293 $dbi = $request->getDbh();
294 if ($dbi->isWikiPage($URL))
295 return $Theme->linkExistingWikiWord($URL, $linkname);
296 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
297 // if it's an image, embed it; otherwise, it's a regular link
298 if (preg_match("/($InlineImages)$/i", $URL))
299 return LinkImage($URL, $linkname);
301 return LinkURL($URL, $linkname);
303 elseif (preg_match("/^phpwiki:/", $URL))
304 return LinkPhpwikiURL($URL, $linkname);
305 elseif (function_exists('LinkInterWikiLink')
306 && preg_match("/^$InterWikiLinkRegexp:/", $URL))
307 return LinkInterWikiLink($URL, $linkname);
309 return $Theme->linkUnknownWikiWord($URL, $linkname);
314 /* FIXME: this should be done by the transform code */
315 function ExtractWikiPageLinks($content) {
316 global $WikiNameRegexp;
318 if (is_string($content))
319 $content = explode("\n", $content);
321 $wikilinks = array();
322 foreach ($content as $line) {
323 // remove plugin code
324 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
325 // remove escaped '['
326 $line = str_replace('[[', ' ', $line);
328 $line = preg_replace('/[\d+]/', ' ', $line);
330 // bracket links (only type wiki-* is of interest)
331 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
333 for ($i = 0; $i < $numBracketLinks; $i++) {
334 $link = LinkBracketLink($brktlinks[0][$i]);
335 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
336 $wikilinks[$brktlinks[2][$i]] = 1;
338 $brktlink = preg_quote($brktlinks[0][$i]);
339 $line = preg_replace("|$brktlink|", '', $line);
342 // BumpyText old-style wiki links
343 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
344 for ($i = 0; isset($link[0][$i]); $i++) {
345 if($link[0][$i][0] <> '!')
346 $wikilinks[$link[0][$i]] = 1;
350 return array_keys($wikilinks);
354 * Split WikiWords in page names.
356 * It has been deemed useful to split WikiWords (into "Wiki Words") in
357 * places like page titles. This is rumored to help search engines
360 * @param $page string The page name.
362 * @return string The split name.
364 function split_pagename ($page) {
366 if (preg_match("/\s/", $page))
367 return $page; // Already split --- don't split any more.
369 // FIXME: this algorithm is Anglo-centric.
372 // This mess splits between a lower-case letter followed by
373 // either an upper-case or a numeral; except that it wont
374 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
375 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
376 // This the single-letter words 'I' and 'A' from any following
377 // capitalized words.
378 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
379 // Split numerals from following letters.
380 $RE[] = '/(\d)([[:alpha:]])/';
382 foreach ($RE as $key => $val)
383 $RE[$key] = pcre_fix_posix_classes($val);
386 foreach ($RE as $regexp)
387 $page = preg_replace($regexp, '\\1 \\2', $page);
391 function NoSuchRevision (&$request, $page, $version) {
392 $html[] = HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
393 $version, LinkWikiWord($page->getName())));
394 include_once('lib/Template.php');
395 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
401 * Get time offset for local time zone.
403 * @param $time time_t Get offset for this time. Default: now.
404 * @param $no_colon boolean Don't put colon between hours and minutes.
405 * @return string Offset as a string in the format +HH:MM.
407 function TimezoneOffset ($time = false, $no_colon = false) {
410 $secs = date('Z', $time);
418 $colon = $no_colon ? '' : ':';
419 $mins = intval(($secs + 30) / 60);
420 return sprintf("%s%02d%s%02d",
421 $sign, $mins / 60, $colon, $mins % 60);
425 * Format time in ISO-8601 format.
427 * @param $time time_t Time. Default: now.
428 * @return string Date and time in ISO-8601 format.
430 function Iso8601DateTime ($time = false) {
433 $tzoff = TimezoneOffset($time);
434 $date = date('Y-m-d', $time);
435 $time = date('H:i:s', $time);
436 return $date . 'T' . $time . $tzoff;
440 * Format time in RFC-2822 format.
442 * @param $time time_t Time. Default: now.
443 * @return string Date and time in RFC-2822 format.
445 function Rfc2822DateTime ($time = false) {
448 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
452 * Format time to standard 'ctime' format.
454 * @param $time time_t Time. Default: now.
455 * @return string Date and time in RFC-2822 format.
457 function CTime ($time = false)
461 return date("D M j H:i:s Y", $time);
467 * Internationalized printf.
469 * This is essentially the same as PHP's built-in printf
470 * with the following exceptions:
472 * <li> It passes the format string through gettext().
473 * <li> It supports the argument reordering extensions.
480 * __printf("Differences between versions %s and %s of %s",
481 * $new_link, $old_link, $page_link);
484 * Then in locale/po/de.po, one can reorder the printf arguments:
487 * msgid "Differences between %s and %s of %s."
488 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
491 * (Note that while PHP tries to expand $vars within double-quotes,
492 * the values in msgstr undergo no such expansion, so the '$'s
495 * One shouldn't use reordered arguments in the default format string.
496 * Backslashes in the default string would be necessary to escape the
497 * '$'s, and they'll cause all kinds of trouble....
499 function __printf ($fmt) {
500 $args = func_get_args();
502 echo __vsprintf($fmt, $args);
506 * Internationalized sprintf.
508 * This is essentially the same as PHP's built-in printf with the
509 * following exceptions:
512 * <li> It passes the format string through gettext().
513 * <li> It supports the argument reordering extensions.
518 function __sprintf ($fmt) {
519 $args = func_get_args();
521 return __vsprintf($fmt, $args);
525 * Internationalized vsprintf.
527 * This is essentially the same as PHP's built-in printf with the
528 * following exceptions:
531 * <li> It passes the format string through gettext().
532 * <li> It supports the argument reordering extensions.
537 function __vsprintf ($fmt, $args) {
538 $fmt = gettext($fmt);
539 // PHP's sprintf doesn't support variable with specifiers,
540 // like sprintf("%*s", 10, "x"); --- so we won't either.
542 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
543 // Format string has '%2$s' style argument reordering.
544 // PHP doesn't support this.
545 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
546 // literal variable name substitution only to keep locale
547 // strings uncluttered
548 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
549 '%1\$s','%s'), E_USER_WARNING); //php+locale error
551 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
554 // Reorder arguments appropriately.
555 foreach($m[1] as $argnum) {
556 if ($argnum < 1 || $argnum > count($args))
557 trigger_error(sprintf(_("%s: argument index out of range"),
558 $argnum), E_USER_WARNING);
559 $newargs[] = $args[$argnum - 1];
564 // Not all PHP's have vsprintf, so...
565 array_unshift($args, $fmt);
566 return call_user_func_array('sprintf', $args);
572 * Build an array in $this->_fileList of files from $dirname.
573 * Subdirectories are not traversed.
575 * (This was a function LoadDir in lib/loadsave.php)
576 * See also http://www.php.net/manual/en/function.readdir.php
578 function getFiles() {
579 return $this->_fileList;
582 function _filenameSelector($filename) {
583 // Default selects all filenames, override as needed.
587 function fileSet($directory) {
588 $this->_fileList = array();
590 if (empty($directory)) {
591 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
593 return; // early return
596 @ $dir_handle = opendir($dir=$directory);
597 if (empty($dir_handle)) {
598 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
599 $dir), E_USER_NOTICE);
600 return; // early return
603 while ($filename = readdir($dir_handle)) {
604 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
606 if ($this->_filenameSelector($filename)) {
607 array_push($this->_fileList, "$filename");
608 //trigger_error(sprintf(_("found file %s"), $filename),
609 // E_USER_NOTICE); //debugging
612 closedir($dir_handle);
617 // Class introspections
619 /** Determine whether object is of a specified type.
621 * @param $object object An object.
622 * @param $class string Class name.
623 * @return bool True iff $object is a $class
624 * or a sub-type of $class.
626 function isa ($object, $class)
628 $lclass = strtolower($class);
630 return is_object($object)
631 && ( get_class($object) == strtolower($lclass)
632 || is_subclass_of($object, $lclass) );
635 /** Determine whether (possible) object has method.
637 * @param $object mixed Object
638 * @param $method string Method name
639 * @return bool True iff $object is an object with has method $method.
641 function can ($object, $method)
643 return is_object($object) && method_exists($object, strtolower($method));
646 // (c-file-style: "gnu")
651 // c-hanging-comment-ender-p: nil
652 // indent-tabs-mode: nil