1 <?php rcs_id('$Id: stdlib.php,v 1.93 2002-01-28 15:52:40 carstenklapp 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)
28 better_srand($seed = '')
30 function: LinkInterWikiLink($link, $linktext)
31 moved to: lib/interwiki.php
32 function: linkExistingWikiWord($wikiword, $linktext, $version)
33 moved to: lib/Theme.php
34 function: LinkUnknownWikiWord($wikiword, $linktext)
35 moved to: lib/Theme.php
36 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
37 gone see: lib/plugin/RecentChanges.php
41 function WikiURL($pagename, $args = '', $get_abs_url = false) {
42 if (is_object($pagename)) {
43 if (isa($pagename, 'WikiDB_Page')) {
44 $pagename = $pagename->getName();
46 elseif (isa($pagename, 'WikiDB_PageRevision')) {
47 $page = $pagename->getPage();
48 $args['version'] = $pagename->getVersion();
49 $pagename = $page->getName();
53 if (is_array($args)) {
55 foreach ($args as $key => $val) {
56 $enc_args[] = urlencode($key) . '=' . urlencode($val);
58 $args = join('&', $enc_args);
62 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
63 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
68 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
69 $url .= "?pagename=" . rawurlencode($pagename);
76 function IconForLink($protocol_or_url) {
79 list ($proto) = explode(':', $protocol_or_url, 2);
80 $src = $Theme->getLinkIconURL($proto);
82 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon'));
87 function LinkURL($url, $linktext = '') {
88 // FIXME: Is this needed (or sufficient?)
89 if(ereg("[<>\"]", $url)) {
90 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
91 _("BAD URL -- remove all of <, >, \"")));
94 $link = HTML::a(array('href' => $url),
96 $linktext ? $linktext : $url);
98 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
102 function LinkWikiWord($wikiword, $linktext = '', $version = false) {
103 global $request, $Theme;
104 $dbi = $request->getDbh();
105 if ($dbi->isWikiPage($wikiword))
106 $link = $Theme->linkExistingWikiWord($wikiword, $linktext, $version);
108 $link = $Theme->linkUnknownWikiWord($wikiword, $linktext);
112 function LinkImage($url, $alt = '[External Image]') {
113 // FIXME: Is this needed (or sufficient?)
114 if(ereg("[<>\"]", $url)) {
115 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
116 _("BAD URL -- remove all of <, >, \"")));
119 $link = HTML::img(array('src' => $url, 'alt' => $alt));
121 $link->setAttr('class', 'inlineimage');
128 var $items = array();
131 function push($item) {
132 $this->items[$this->size] = $item;
138 if ($this->size == 0) {
139 return false; // stack is empty
142 return $this->items[$this->size];
151 return $this->items[$this->size - 1];
157 // end class definition
160 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
161 $form = HTML::form(array('action' => USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME,
164 'accept-charset' => CHARSET));
167 while (list($key, $val) = each($args)) {
168 $i = HTML::input(array('name' => $key, 'value' => $val, 'type' => 'hidden'));
170 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
171 $i->setAttr('size', $m[1] ? $m[1] : 30);
172 $i->setAttr('value', $m[2]);
174 $i->setAttr('type', 'text');
177 $i->setAttr('type', 'file');
178 $form->setAttr('enctype', 'multipart/form-data');
179 $form->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
180 'value' => MAX_UPLOAD_SIZE,
181 'type' => 'hidden')));
182 $form->setAttr('method', 'post');
184 $td->pushContent($i);
187 $form->pushContent($i);
192 if (!empty($button_text))
193 $tr->pushContent(HTML::td(HTML::input(array('type' => 'submit',
195 'value' => $button_text))));
196 $form->pushContent(HTML::table(array('cellspacing' => 0,
203 function SplitQueryArgs ($query_args = '')
205 $split_args = split('&', $query_args);
207 while (list($key, $val) = each($split_args))
208 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
209 $args[$m[1]] = $m[2];
213 function LinkPhpwikiURL($url, $text = '') {
216 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
217 return HTML::strong(array('class' => 'rawurl'),
218 HTML::u(array('class' => 'baduri'),
219 _("BAD phpwiki: URL")));
223 $pagename = urldecode($m[1]);
226 if (empty($pagename) &&
227 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
228 // Convert old style links (to not break diff links in
230 $pagename = urldecode($m[2]);
231 $args = array("action" => $m[1]);
234 $args = SplitQueryArgs($qargs);
237 if (empty($pagename))
238 $pagename = $GLOBALS['request']->getArg('pagename');
240 if (isset($args['action']) && $args['action'] == 'browse')
241 unset($args['action']);
244 if (empty($args['action']))
246 else if (is_safe_action($args['action']))
247 $class = 'wikiaction';
249 if (empty($args['action']) || is_safe_action($args['action']))
250 $class = 'wikiaction';
252 // Don't allow administrative links on unlocked pages.
253 $page = $GLOBALS['request']->getPage();
254 if (!$page->get('locked'))
255 return HTML::span(array('class' => 'wikiunsafe'),
256 HTML::u(_("Lock page to enable link")));
257 $class = 'wikiadmin';
260 // FIXME: ug, don't like this
261 if (preg_match('/=\d*\(/', $qargs))
262 return MakeWikiForm($pagename, $args, $class, $text);
264 $text = HTML::span(array('class' => 'rawurl'), $url);
266 return HTML::a(array('href' => WikiURL($pagename, $args),
271 function LinkBracketLink($bracketlink) {
272 global $request, $AllowedProtocols, $InlineImages;
273 global $InterWikiLinkRegexp, $Theme;
276 // $bracketlink will start and end with brackets; in between will
277 // be either a page name, a URL or both separated by a pipe.
279 // strip brackets and leading space
280 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
281 // match the contents
282 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
284 if (isset($matches[3])) {
285 // named link of the form "[some link name | http://blippy.com/]"
286 $URL = trim($matches[3]);
287 $linkname = trim($matches[1]);
289 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
290 $URL = trim($matches[1]);
294 $dbi = $request->getDbh();
295 if ($dbi->isWikiPage($URL))
296 return $Theme->linkExistingWikiWord($URL, $linkname);
297 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
298 // if it's an image, embed it; otherwise, it's a regular link
299 if (preg_match("/($InlineImages)$/i", $URL))
300 return LinkImage($URL, $linkname);
302 return LinkURL($URL, $linkname);
304 elseif (preg_match("/^phpwiki:/", $URL))
305 return LinkPhpwikiURL($URL, $linkname);
306 elseif (function_exists('LinkInterWikiLink')
307 && preg_match("/^$InterWikiLinkRegexp:/", $URL))
308 return LinkInterWikiLink($URL, $linkname);
310 return $Theme->linkUnknownWikiWord($URL, $linkname);
315 /* FIXME: this should be done by the transform code */
316 function ExtractWikiPageLinks($content) {
317 global $WikiNameRegexp;
319 if (is_string($content))
320 $content = explode("\n", $content);
322 $wikilinks = array();
323 foreach ($content as $line) {
324 // remove plugin code
325 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
326 // remove escaped '['
327 $line = str_replace('[[', ' ', $line);
329 $line = preg_replace('/[\d+]/', ' ', $line);
331 // bracket links (only type wiki-* is of interest)
332 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
334 for ($i = 0; $i < $numBracketLinks; $i++) {
335 $link = LinkBracketLink($brktlinks[0][$i]);
336 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
337 $wikilinks[$brktlinks[2][$i]] = 1;
339 $brktlink = preg_quote($brktlinks[0][$i]);
340 $line = preg_replace("|$brktlink|", '', $line);
343 // BumpyText old-style wiki links
344 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
345 for ($i = 0; isset($link[0][$i]); $i++) {
346 if($link[0][$i][0] <> '!')
347 $wikilinks[$link[0][$i]] = 1;
351 return array_keys($wikilinks);
355 * Split WikiWords in page names.
357 * It has been deemed useful to split WikiWords (into "Wiki Words") in
358 * places like page titles. This is rumored to help search engines
361 * @param $page string The page name.
363 * @return string The split name.
365 function split_pagename ($page) {
367 if (preg_match("/\s/", $page))
368 return $page; // Already split --- don't split any more.
370 // FIXME: this algorithm is Anglo-centric.
373 // This mess splits between a lower-case letter followed by
374 // either an upper-case or a numeral; except that it wont
375 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
376 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
377 // This the single-letter words 'I' and 'A' from any following
378 // capitalized words.
379 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
380 // Split numerals from following letters.
381 $RE[] = '/(\d)([[:alpha:]])/';
383 foreach ($RE as $key => $val)
384 $RE[$key] = pcre_fix_posix_classes($val);
387 foreach ($RE as $regexp)
388 $page = preg_replace($regexp, '\\1 \\2', $page);
392 function NoSuchRevision (&$request, $page, $version) {
393 $html[] = HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
394 $version, LinkWikiWord($page->getName())));
395 include_once('lib/Template.php');
396 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
402 * Get time offset for local time zone.
404 * @param $time time_t Get offset for this time. Default: now.
405 * @param $no_colon boolean Don't put colon between hours and minutes.
406 * @return string Offset as a string in the format +HH:MM.
408 function TimezoneOffset ($time = false, $no_colon = false) {
411 $secs = date('Z', $time);
419 $colon = $no_colon ? '' : ':';
420 $mins = intval(($secs + 30) / 60);
421 return sprintf("%s%02d%s%02d",
422 $sign, $mins / 60, $colon, $mins % 60);
426 * Format time in ISO-8601 format.
428 * @param $time time_t Time. Default: now.
429 * @return string Date and time in ISO-8601 format.
431 function Iso8601DateTime ($time = false) {
434 $tzoff = TimezoneOffset($time);
435 $date = date('Y-m-d', $time);
436 $time = date('H:i:s', $time);
437 return $date . 'T' . $time . $tzoff;
441 * Format time in RFC-2822 format.
443 * @param $time time_t Time. Default: now.
444 * @return string Date and time in RFC-2822 format.
446 function Rfc2822DateTime ($time = false) {
449 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
453 * Format time to standard 'ctime' format.
455 * @param $time time_t Time. Default: now.
456 * @return string Date and time in RFC-2822 format.
458 function CTime ($time = false)
462 return date("D M j H:i:s Y", $time);
468 * Internationalized printf.
470 * This is essentially the same as PHP's built-in printf
471 * with the following exceptions:
473 * <li> It passes the format string through gettext().
474 * <li> It supports the argument reordering extensions.
481 * __printf("Differences between versions %s and %s of %s",
482 * $new_link, $old_link, $page_link);
485 * Then in locale/po/de.po, one can reorder the printf arguments:
488 * msgid "Differences between %s and %s of %s."
489 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
492 * (Note that while PHP tries to expand $vars within double-quotes,
493 * the values in msgstr undergo no such expansion, so the '$'s
496 * One shouldn't use reordered arguments in the default format string.
497 * Backslashes in the default string would be necessary to escape the
498 * '$'s, and they'll cause all kinds of trouble....
500 function __printf ($fmt) {
501 $args = func_get_args();
503 echo __vsprintf($fmt, $args);
507 * Internationalized sprintf.
509 * This is essentially the same as PHP's built-in printf with the
510 * following exceptions:
513 * <li> It passes the format string through gettext().
514 * <li> It supports the argument reordering extensions.
519 function __sprintf ($fmt) {
520 $args = func_get_args();
522 return __vsprintf($fmt, $args);
526 * Internationalized vsprintf.
528 * This is essentially the same as PHP's built-in printf with the
529 * following exceptions:
532 * <li> It passes the format string through gettext().
533 * <li> It supports the argument reordering extensions.
538 function __vsprintf ($fmt, $args) {
539 $fmt = gettext($fmt);
540 // PHP's sprintf doesn't support variable with specifiers,
541 // like sprintf("%*s", 10, "x"); --- so we won't either.
543 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
544 // Format string has '%2$s' style argument reordering.
545 // PHP doesn't support this.
546 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
547 // literal variable name substitution only to keep locale
548 // strings uncluttered
549 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
550 '%1\$s','%s'), E_USER_WARNING); //php+locale error
552 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
555 // Reorder arguments appropriately.
556 foreach($m[1] as $argnum) {
557 if ($argnum < 1 || $argnum > count($args))
558 trigger_error(sprintf(_("%s: argument index out of range"),
559 $argnum), E_USER_WARNING);
560 $newargs[] = $args[$argnum - 1];
565 // Not all PHP's have vsprintf, so...
566 array_unshift($args, $fmt);
567 return call_user_func_array('sprintf', $args);
573 * Build an array in $this->_fileList of files from $dirname.
574 * Subdirectories are not traversed.
576 * (This was a function LoadDir in lib/loadsave.php)
577 * See also http://www.php.net/manual/en/function.readdir.php
579 function getFiles() {
580 return $this->_fileList;
583 function _filenameSelector($filename) {
584 // Default selects all filenames, override as needed.
588 function fileSet($directory) {
589 $this->_fileList = array();
591 if (empty($directory)) {
592 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
594 return; // early return
597 @ $dir_handle = opendir($dir=$directory);
598 if (empty($dir_handle)) {
599 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
600 $dir), E_USER_NOTICE);
601 return; // early return
604 while ($filename = readdir($dir_handle)) {
605 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
607 if ($this->_filenameSelector($filename)) {
608 array_push($this->_fileList, "$filename");
609 //trigger_error(sprintf(_("found file %s"), $filename),
610 // E_USER_NOTICE); //debugging
613 closedir($dir_handle);
618 // Class introspections
620 /** Determine whether object is of a specified type.
622 * @param $object object An object.
623 * @param $class string Class name.
624 * @return bool True iff $object is a $class
625 * or a sub-type of $class.
627 function isa ($object, $class)
629 $lclass = strtolower($class);
631 return is_object($object)
632 && ( get_class($object) == strtolower($lclass)
633 || is_subclass_of($object, $lclass) );
636 /** Determine whether (possible) object has method.
638 * @param $object mixed Object
639 * @param $method string Method name
640 * @return bool True iff $object is an object with has method $method.
642 function can ($object, $method)
644 return is_object($object) && method_exists($object, strtolower($method));
648 * Seed the random number generator.
650 * better_srand() ensures the randomizer is seeded only once.
652 * How random do you want it? See:
653 * http://www.php.net/manual/en/function.srand.php
654 * http://www.php.net/manual/en/function.mt-srand.php
656 function better_srand($seed = '') {
657 static $wascalled = FALSE;
659 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
662 //trigger_error("new random seed", E_USER_NOTICE); //debugging
666 // (c-file-style: "gnu")
671 // c-hanging-comment-ender-p: nil
672 // indent-tabs-mode: nil