1 <?php rcs_id('$Id: stdlib.php,v 1.95 2002-01-30 23:41:54 dairiki Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
6 IconForLink($protocol_or_url)
7 LinkURL($url, $linktext)
10 MakeWikiForm ($pagename, $args, $class, $button_text)
11 SplitQueryArgs ($query_args)
12 LinkPhpwikiURL($url, $text)
13 LinkBracketLink($bracketlink)
14 ExtractWikiPageLinks($content)
16 class Stack { push($item), pop(), cnt(), top() }
18 split_pagename ($page)
19 NoSuchRevision ($request, $page, $version)
20 TimezoneOffset ($time, $no_colon)
21 Iso8601DateTime ($time)
22 Rfc2822DateTime ($time)
26 __vsprintf ($fmt, $args)
27 better_srand($seed = '')
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');
102 function LinkImage($url, $alt = '[External Image]') {
103 // FIXME: Is this needed (or sufficient?)
104 if(ereg("[<>\"]", $url)) {
105 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
106 _("BAD URL -- remove all of <, >, \"")));
109 $link = HTML::img(array('src' => $url, 'alt' => $alt));
111 $link->setAttr('class', 'inlineimage');
118 var $items = array();
121 function push($item) {
122 $this->items[$this->size] = $item;
128 if ($this->size == 0) {
129 return false; // stack is empty
132 return $this->items[$this->size];
141 return $this->items[$this->size - 1];
147 // end class definition
150 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
151 $form = HTML::form(array('action' => USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME,
154 'accept-charset' => CHARSET));
157 while (list($key, $val) = each($args)) {
158 $i = HTML::input(array('name' => $key, 'value' => $val, 'type' => 'hidden'));
160 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
161 $i->setAttr('size', $m[1] ? $m[1] : 30);
162 $i->setAttr('value', $m[2]);
164 $i->setAttr('type', 'text');
167 $i->setAttr('type', 'file');
168 $form->setAttr('enctype', 'multipart/form-data');
169 $form->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
170 'value' => MAX_UPLOAD_SIZE,
171 'type' => 'hidden')));
172 $form->setAttr('method', 'post');
174 $td->pushContent($i);
177 $form->pushContent($i);
182 if (!empty($button_text))
183 $tr->pushContent(HTML::td(HTML::input(array('type' => 'submit',
185 'value' => $button_text))));
186 $form->pushContent(HTML::table(array('cellspacing' => 0,
193 function SplitQueryArgs ($query_args = '')
195 $split_args = split('&', $query_args);
197 while (list($key, $val) = each($split_args))
198 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
199 $args[$m[1]] = $m[2];
203 function LinkPhpwikiURL($url, $text = '') {
206 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
207 return HTML::strong(array('class' => 'rawurl'),
208 HTML::u(array('class' => 'baduri'),
209 _("BAD phpwiki: URL")));
213 $pagename = urldecode($m[1]);
216 if (empty($pagename) &&
217 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
218 // Convert old style links (to not break diff links in
220 $pagename = urldecode($m[2]);
221 $args = array("action" => $m[1]);
224 $args = SplitQueryArgs($qargs);
227 if (empty($pagename))
228 $pagename = $GLOBALS['request']->getArg('pagename');
230 if (isset($args['action']) && $args['action'] == 'browse')
231 unset($args['action']);
234 if (empty($args['action']))
236 else if (is_safe_action($args['action']))
237 $class = 'wikiaction';
239 if (empty($args['action']) || is_safe_action($args['action']))
240 $class = 'wikiaction';
242 // Don't allow administrative links on unlocked pages.
243 $page = $GLOBALS['request']->getPage();
244 if (!$page->get('locked'))
245 return HTML::span(array('class' => 'wikiunsafe'),
246 HTML::u(_("Lock page to enable link")));
247 $class = 'wikiadmin';
250 // FIXME: ug, don't like this
251 if (preg_match('/=\d*\(/', $qargs))
252 return MakeWikiForm($pagename, $args, $class, $text);
254 $text = HTML::span(array('class' => 'rawurl'), $url);
256 return HTML::a(array('href' => WikiURL($pagename, $args),
261 function LinkBracketLink($bracketlink) {
262 global $request, $AllowedProtocols, $InlineImages;
263 global $InterWikiLinkRegexp;
266 // $bracketlink will start and end with brackets; in between will
267 // be either a page name, a URL or both separated by a pipe.
269 // strip brackets and leading space
270 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
271 // match the contents
272 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
274 if (isset($matches[3])) {
275 // named link of the form "[some link name | http://blippy.com/]"
276 $URL = trim($matches[3]);
277 $linkname = trim($matches[1]);
279 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
280 $URL = trim($matches[1]);
284 $dbi = $request->getDbh();
285 if ($dbi->isWikiPage($URL))
286 return WikiLink($URL, 'known', $linkname);
287 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
288 // if it's an image, embed it; otherwise, it's a regular link
289 if (preg_match("/($InlineImages)$/i", $URL))
290 return LinkImage($URL, $linkname);
292 return LinkURL($URL, $linkname);
294 elseif (preg_match("/^phpwiki:/", $URL))
295 return LinkPhpwikiURL($URL, $linkname);
296 elseif (function_exists('LinkInterWikiLink')
297 && preg_match("/^$InterWikiLinkRegexp:/", $URL))
298 return LinkInterWikiLink($URL, $linkname);
300 return WikiLink($URL, 'unknown', $linkname);
305 /* FIXME: this should be done by the transform code */
306 function ExtractWikiPageLinks($content) {
307 global $WikiNameRegexp;
309 if (is_string($content))
310 $content = explode("\n", $content);
312 $wikilinks = array();
313 foreach ($content as $line) {
314 // remove plugin code
315 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
316 // remove escaped '['
317 $line = str_replace('[[', ' ', $line);
319 $line = preg_replace('/[\d+]/', ' ', $line);
321 // bracket links (only type wiki-* is of interest)
322 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
324 for ($i = 0; $i < $numBracketLinks; $i++) {
325 $link = LinkBracketLink($brktlinks[0][$i]);
326 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
327 $wikilinks[$brktlinks[2][$i]] = 1;
329 $brktlink = preg_quote($brktlinks[0][$i]);
330 $line = preg_replace("|$brktlink|", '', $line);
333 // BumpyText old-style wiki links
334 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
335 for ($i = 0; isset($link[0][$i]); $i++) {
336 if($link[0][$i][0] <> '!')
337 $wikilinks[$link[0][$i]] = 1;
341 return array_keys($wikilinks);
345 * Split WikiWords in page names.
347 * It has been deemed useful to split WikiWords (into "Wiki Words") in
348 * places like page titles. This is rumored to help search engines
351 * @param $page string The page name.
353 * @return string The split name.
355 function split_pagename ($page) {
357 if (preg_match("/\s/", $page))
358 return $page; // Already split --- don't split any more.
360 // FIXME: this algorithm is Anglo-centric.
363 // This mess splits between a lower-case letter followed by
364 // either an upper-case or a numeral; except that it wont
365 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
366 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
367 // This the single-letter words 'I' and 'A' from any following
368 // capitalized words.
369 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
370 // Split numerals from following letters.
371 $RE[] = '/(\d)([[:alpha:]])/';
373 foreach ($RE as $key => $val)
374 $RE[$key] = pcre_fix_posix_classes($val);
377 foreach ($RE as $regexp)
378 $page = preg_replace($regexp, '\\1 \\2', $page);
382 function NoSuchRevision (&$request, $page, $version) {
383 $html = HTML(HTML::h2(_("Revision Not Found")),
384 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
385 $version, WikiLink($page, 'auto'))));
386 include_once('lib/Template.php');
387 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
393 * Get time offset for local time zone.
395 * @param $time time_t Get offset for this time. Default: now.
396 * @param $no_colon boolean Don't put colon between hours and minutes.
397 * @return string Offset as a string in the format +HH:MM.
399 function TimezoneOffset ($time = false, $no_colon = false) {
402 $secs = date('Z', $time);
410 $colon = $no_colon ? '' : ':';
411 $mins = intval(($secs + 30) / 60);
412 return sprintf("%s%02d%s%02d",
413 $sign, $mins / 60, $colon, $mins % 60);
417 * Format time in ISO-8601 format.
419 * @param $time time_t Time. Default: now.
420 * @return string Date and time in ISO-8601 format.
422 function Iso8601DateTime ($time = false) {
425 $tzoff = TimezoneOffset($time);
426 $date = date('Y-m-d', $time);
427 $time = date('H:i:s', $time);
428 return $date . 'T' . $time . $tzoff;
432 * Format time in RFC-2822 format.
434 * @param $time time_t Time. Default: now.
435 * @return string Date and time in RFC-2822 format.
437 function Rfc2822DateTime ($time = false) {
440 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
444 * Format time to standard 'ctime' format.
446 * @param $time time_t Time. Default: now.
447 * @return string Date and time in RFC-2822 format.
449 function CTime ($time = false)
453 return date("D M j H:i:s Y", $time);
459 * Internationalized printf.
461 * This is essentially the same as PHP's built-in printf
462 * with the following exceptions:
464 * <li> It passes the format string through gettext().
465 * <li> It supports the argument reordering extensions.
472 * __printf("Differences between versions %s and %s of %s",
473 * $new_link, $old_link, $page_link);
476 * Then in locale/po/de.po, one can reorder the printf arguments:
479 * msgid "Differences between %s and %s of %s."
480 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
483 * (Note that while PHP tries to expand $vars within double-quotes,
484 * the values in msgstr undergo no such expansion, so the '$'s
487 * One shouldn't use reordered arguments in the default format string.
488 * Backslashes in the default string would be necessary to escape the
489 * '$'s, and they'll cause all kinds of trouble....
491 function __printf ($fmt) {
492 $args = func_get_args();
494 echo __vsprintf($fmt, $args);
498 * Internationalized sprintf.
500 * This is essentially the same as PHP's built-in printf with the
501 * following exceptions:
504 * <li> It passes the format string through gettext().
505 * <li> It supports the argument reordering extensions.
510 function __sprintf ($fmt) {
511 $args = func_get_args();
513 return __vsprintf($fmt, $args);
517 * Internationalized vsprintf.
519 * This is essentially the same as PHP's built-in printf with the
520 * following exceptions:
523 * <li> It passes the format string through gettext().
524 * <li> It supports the argument reordering extensions.
529 function __vsprintf ($fmt, $args) {
530 $fmt = gettext($fmt);
531 // PHP's sprintf doesn't support variable with specifiers,
532 // like sprintf("%*s", 10, "x"); --- so we won't either.
534 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
535 // Format string has '%2$s' style argument reordering.
536 // PHP doesn't support this.
537 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
538 // literal variable name substitution only to keep locale
539 // strings uncluttered
540 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
541 '%1\$s','%s'), E_USER_WARNING); //php+locale error
543 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
546 // Reorder arguments appropriately.
547 foreach($m[1] as $argnum) {
548 if ($argnum < 1 || $argnum > count($args))
549 trigger_error(sprintf(_("%s: argument index out of range"),
550 $argnum), E_USER_WARNING);
551 $newargs[] = $args[$argnum - 1];
556 // Not all PHP's have vsprintf, so...
557 array_unshift($args, $fmt);
558 return call_user_func_array('sprintf', $args);
564 * Build an array in $this->_fileList of files from $dirname.
565 * Subdirectories are not traversed.
567 * (This was a function LoadDir in lib/loadsave.php)
568 * See also http://www.php.net/manual/en/function.readdir.php
570 function getFiles() {
571 return $this->_fileList;
574 function _filenameSelector($filename) {
575 // Default selects all filenames, override as needed.
579 function fileSet($directory) {
580 $this->_fileList = array();
582 if (empty($directory)) {
583 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
585 return; // early return
588 @ $dir_handle = opendir($dir=$directory);
589 if (empty($dir_handle)) {
590 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
591 $dir), E_USER_NOTICE);
592 return; // early return
595 while ($filename = readdir($dir_handle)) {
596 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
598 if ($this->_filenameSelector($filename)) {
599 array_push($this->_fileList, "$filename");
600 //trigger_error(sprintf(_("found file %s"), $filename),
601 // E_USER_NOTICE); //debugging
604 closedir($dir_handle);
609 // Class introspections
611 /** Determine whether object is of a specified type.
613 * @param $object object An object.
614 * @param $class string Class name.
615 * @return bool True iff $object is a $class
616 * or a sub-type of $class.
618 function isa ($object, $class)
620 $lclass = strtolower($class);
622 return is_object($object)
623 && ( get_class($object) == strtolower($lclass)
624 || is_subclass_of($object, $lclass) );
627 /** Determine whether (possible) object has method.
629 * @param $object mixed Object
630 * @param $method string Method name
631 * @return bool True iff $object is an object with has method $method.
633 function can ($object, $method)
635 return is_object($object) && method_exists($object, strtolower($method));
639 * Seed the random number generator.
641 * better_srand() ensures the randomizer is seeded only once.
643 * How random do you want it? See:
644 * http://www.php.net/manual/en/function.srand.php
645 * http://www.php.net/manual/en/function.mt-srand.php
647 function better_srand($seed = '') {
648 static $wascalled = FALSE;
650 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
653 //trigger_error("new random seed", E_USER_NOTICE); //debugging
657 // (c-file-style: "gnu")
662 // c-hanging-comment-ender-p: nil
663 // indent-tabs-mode: nil