1 <?php rcs_id('$Id: stdlib.php,v 1.108 2002-02-08 22:03:00 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)
15 ConvertOldMarkup($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) {
78 if ($filename_suffix = false) {
79 // display apache style icon for file type instead of protocol icon
80 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
81 // - document: html, htm, text, txt, rtf, pdf, doc
82 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
83 // - audio: mp3,mp2,aiff,aif,au
84 // - multimedia: mpeg,mpg,mov,qt
86 list ($proto) = explode(':', $protocol_or_url, 2);
87 $src = $Theme->getLinkIconURL($proto);
89 return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon', 'border' => 0));
95 function LinkURL($url, $linktext = '') {
96 // FIXME: Is this needed (or sufficient?)
97 if(ereg("[<>\"]", $url)) {
98 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
99 _("BAD URL -- remove all of <, >, \"")));
103 $linktext = preg_replace("/mailto:/A", "", $url);
105 $link = HTML::a(array('href' => $url),
106 IconForLink($url), $linktext);
109 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
114 function LinkImage($url, $alt = '[External Image]') {
115 // FIXME: Is this needed (or sufficient?)
116 if(ereg("[<>\"]", $url)) {
117 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
118 _("BAD URL -- remove all of <, >, \"")));
121 $link = HTML::img(array('src' => $url, 'alt' => $alt));
123 $link->setAttr('class', 'inlineimage');
130 var $items = array();
133 function push($item) {
134 $this->items[$this->size] = $item;
140 if ($this->size == 0) {
141 return false; // stack is empty
144 return $this->items[$this->size];
153 return $this->items[$this->size - 1];
159 // end class definition
162 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
163 // HACK: so as to not completely break old PhpWikiAdministration pages.
164 trigger_error("MagicPhpWikiURL forms are no longer supported. "
165 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
168 $loader = new WikiPluginLoader;
169 @$action = (string)$args['action'];
170 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
173 function SplitQueryArgs ($query_args = '')
175 $split_args = split('&', $query_args);
177 while (list($key, $val) = each($split_args))
178 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
179 $args[$m[1]] = $m[2];
183 function LinkPhpwikiURL($url, $text = '') {
186 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
187 return HTML::strong(array('class' => 'rawurl'),
188 HTML::u(array('class' => 'baduri'),
189 _("BAD phpwiki: URL")));
193 $pagename = urldecode($m[1]);
196 if (empty($pagename) &&
197 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
198 // Convert old style links (to not break diff links in
200 $pagename = urldecode($m[2]);
201 $args = array("action" => $m[1]);
204 $args = SplitQueryArgs($qargs);
207 if (empty($pagename))
208 $pagename = $GLOBALS['request']->getArg('pagename');
210 if (isset($args['action']) && $args['action'] == 'browse')
211 unset($args['action']);
214 if (empty($args['action']))
216 else if (is_safe_action($args['action']))
217 $class = 'wikiaction';
219 if (empty($args['action']) || is_safe_action($args['action']))
220 $class = 'wikiaction';
222 // Don't allow administrative links on unlocked pages.
223 $page = $GLOBALS['request']->getPage();
224 if (!$page->get('locked'))
225 return HTML::span(array('class' => 'wikiunsafe'),
226 HTML::u(_("Lock page to enable link")));
227 $class = 'wikiadmin';
230 // FIXME: ug, don't like this
231 if (preg_match('/=\d*\(/', $qargs))
232 return MakeWikiForm($pagename, $args, $class, $text);
234 $text = HTML::span(array('class' => 'rawurl'), $url);
236 return HTML::a(array('href' => WikiURL($pagename, $args),
241 function LinkBracketLink($bracketlink) {
242 global $request, $AllowedProtocols, $InlineImages;
244 include_once("lib/interwiki.php");
245 $intermap = InterWikiMap::GetMap($request);
247 // $bracketlink will start and end with brackets; in between will
248 // be either a page name, a URL or both separated by a pipe.
250 // strip brackets and leading space
251 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
252 // match the contents
253 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
255 if (isset($matches[3])) {
256 // named link of the form "[some link name | http://blippy.com/]"
257 $URL = trim($matches[3]);
258 $linkname = trim($matches[1]);
260 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
261 $URL = trim($matches[1]);
265 $dbi = $request->getDbh();
266 if ($dbi->isWikiPage($URL))
267 return WikiLink($URL, 'known', $linkname);
268 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
269 // if it's an image, embed it; otherwise, it's a regular link
270 if (preg_match("/($InlineImages)$/i", $URL))
271 return LinkImage($URL, $linkname);
273 return LinkURL($URL, $linkname);
275 elseif (preg_match("/^phpwiki:/", $URL))
276 return LinkPhpwikiURL($URL, $linkname);
277 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
278 return $intermap->link($URL, $linkname);
280 return WikiLink($URL, 'unknown', $linkname);
285 /* FIXME: this should be done by the transform code */
286 function ExtractWikiPageLinks($content) {
287 global $WikiNameRegexp;
289 if (is_string($content))
290 $content = explode("\n", $content);
292 $wikilinks = array();
293 foreach ($content as $line) {
294 // remove plugin code
295 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
296 // remove escaped '['
297 $line = str_replace('[[', ' ', $line);
299 $line = preg_replace('/[\d+]/', ' ', $line);
301 // bracket links (only type wiki-* is of interest)
302 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
304 for ($i = 0; $i < $numBracketLinks; $i++) {
305 $link = LinkBracketLink($brktlinks[0][$i]);
306 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
307 $wikilinks[$brktlinks[2][$i]] = 1;
309 $brktlink = preg_quote($brktlinks[0][$i]);
310 $line = preg_replace("|$brktlink|", '', $line);
313 // BumpyText old-style wiki links
314 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
315 for ($i = 0; isset($link[0][$i]); $i++) {
316 if($link[0][$i][0] <> '!')
317 $wikilinks[$link[0][$i]] = 1;
321 return array_keys($wikilinks);
325 * Convert old page markup to new-style markup.
327 * @param $text string Old-style wiki markup.
329 * @param $just_links bool Only convert old-style links.
330 * (Really this only converts escaped old-style links.)
332 * @return string New-style wiki markup.
334 * @bugs FIXME: footnotes and old-style tables are known to be broken.
336 function ConvertOldMarkup ($text, $just_links = false) {
338 static $orig, $repl, $link_orig, $link_repl;
341 /*****************************************************************
342 * Conversions for inline markup:
349 // escape escaped brackets
353 // change ! escapes to ~'s.
354 global $AllowedProtocols, $WikiNameRegexp, $request;
355 include_once('lib/interwiki.php');
356 $map = InterWikiMap::GetMap($request);
357 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
358 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
359 $bang_esc[] = $WikiNameRegexp;
360 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
367 /*****************************************************************
368 * Conversions for block markup
370 // convert indented blocks to <pre></pre>.
371 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
372 $repl[] = "<pre>\n\\0</pre>\n";
375 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
376 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
381 return preg_replace($link_orig, $link_repl, $text);
383 return preg_replace($orig, $repl, $text);
386 function _ConvertOldListMarkup ($indent, $bullet) {
387 $indent = str_repeat(' ', strlen($indent));
388 if ($bullet[0] == ';') {
389 $term = ltrim(substr($bullet, 1));
390 return $indent . $term . "\n" . $indent . ' ';
393 return $indent . $bullet . ' ';
399 * Split WikiWords in page names.
401 * It has been deemed useful to split WikiWords (into "Wiki Words") in
402 * places like page titles. This is rumored to help search engines
405 * @param $page string The page name.
407 * @return string The split name.
409 function split_pagename ($page) {
411 if (preg_match("/\s/", $page))
412 return $page; // Already split --- don't split any more.
414 // FIXME: this algorithm is Anglo-centric.
417 // This mess splits between a lower-case letter followed by
418 // either an upper-case or a numeral; except that it wont
419 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
420 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
421 // This the single-letter words 'I' and 'A' from any following
422 // capitalized words.
423 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
424 // Split numerals from following letters.
425 $RE[] = '/(\d)([[:alpha:]])/';
427 foreach ($RE as $key => $val)
428 $RE[$key] = pcre_fix_posix_classes($val);
431 foreach ($RE as $regexp)
432 $page = preg_replace($regexp, '\\1 \\2', $page);
436 function NoSuchRevision (&$request, $page, $version) {
437 $html = HTML(HTML::h2(_("Revision Not Found")),
438 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
439 $version, WikiLink($page, 'auto'))));
440 include_once('lib/Template.php');
441 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
447 * Get time offset for local time zone.
449 * @param $time time_t Get offset for this time. Default: now.
450 * @param $no_colon boolean Don't put colon between hours and minutes.
451 * @return string Offset as a string in the format +HH:MM.
453 function TimezoneOffset ($time = false, $no_colon = false) {
456 $secs = date('Z', $time);
465 $colon = $no_colon ? '' : ':';
466 $mins = intval(($secs + 30) / 60);
467 return sprintf("%s%02d%s%02d",
468 $sign, $mins / 60, $colon, $mins % 60);
473 * Format time in ISO-8601 format.
475 * @param $time time_t Time. Default: now.
476 * @return string Date and time in ISO-8601 format.
478 function Iso8601DateTime ($time = false) {
481 $tzoff = TimezoneOffset($time);
482 $date = date('Y-m-d', $time);
483 $time = date('H:i:s', $time);
484 return $date . 'T' . $time . $tzoff;
488 * Format time in RFC-2822 format.
490 * @param $time time_t Time. Default: now.
491 * @return string Date and time in RFC-2822 format.
493 function Rfc2822DateTime ($time = false) {
496 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
500 * Format time to standard 'ctime' format.
502 * @param $time time_t Time. Default: now.
503 * @return string Date and time.
505 function CTime ($time = false)
509 return date("D M j H:i:s Y", $time);
515 * Internationalized printf.
517 * This is essentially the same as PHP's built-in printf
518 * with the following exceptions:
520 * <li> It passes the format string through gettext().
521 * <li> It supports the argument reordering extensions.
528 * __printf("Differences between versions %s and %s of %s",
529 * $new_link, $old_link, $page_link);
532 * Then in locale/po/de.po, one can reorder the printf arguments:
535 * msgid "Differences between %s and %s of %s."
536 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
539 * (Note that while PHP tries to expand $vars within double-quotes,
540 * the values in msgstr undergo no such expansion, so the '$'s
543 * One shouldn't use reordered arguments in the default format string.
544 * Backslashes in the default string would be necessary to escape the
545 * '$'s, and they'll cause all kinds of trouble....
547 function __printf ($fmt) {
548 $args = func_get_args();
550 echo __vsprintf($fmt, $args);
554 * Internationalized sprintf.
556 * This is essentially the same as PHP's built-in printf with the
557 * following exceptions:
560 * <li> It passes the format string through gettext().
561 * <li> It supports the argument reordering extensions.
566 function __sprintf ($fmt) {
567 $args = func_get_args();
569 return __vsprintf($fmt, $args);
573 * Internationalized vsprintf.
575 * This is essentially the same as PHP's built-in printf with the
576 * following exceptions:
579 * <li> It passes the format string through gettext().
580 * <li> It supports the argument reordering extensions.
585 function __vsprintf ($fmt, $args) {
586 $fmt = gettext($fmt);
587 // PHP's sprintf doesn't support variable with specifiers,
588 // like sprintf("%*s", 10, "x"); --- so we won't either.
590 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
591 // Format string has '%2$s' style argument reordering.
592 // PHP doesn't support this.
593 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
594 // literal variable name substitution only to keep locale
595 // strings uncluttered
596 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
597 '%1\$s','%s'), E_USER_WARNING); //php+locale error
599 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
602 // Reorder arguments appropriately.
603 foreach($m[1] as $argnum) {
604 if ($argnum < 1 || $argnum > count($args))
605 trigger_error(sprintf(_("%s: argument index out of range"),
606 $argnum), E_USER_WARNING);
607 $newargs[] = $args[$argnum - 1];
612 // Not all PHP's have vsprintf, so...
613 array_unshift($args, $fmt);
614 return call_user_func_array('sprintf', $args);
620 * Build an array in $this->_fileList of files from $dirname.
621 * Subdirectories are not traversed.
623 * (This was a function LoadDir in lib/loadsave.php)
624 * See also http://www.php.net/manual/en/function.readdir.php
626 function getFiles() {
627 return $this->_fileList;
630 function _filenameSelector($filename) {
631 // Default selects all filenames, override as needed.
635 function fileSet($directory) {
636 $this->_fileList = array();
638 if (empty($directory)) {
639 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
641 return; // early return
644 @ $dir_handle = opendir($dir=$directory);
645 if (empty($dir_handle)) {
646 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
647 $dir), E_USER_NOTICE);
648 return; // early return
651 while ($filename = readdir($dir_handle)) {
652 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
654 if ($this->_filenameSelector($filename)) {
655 array_push($this->_fileList, "$filename");
656 //trigger_error(sprintf(_("found file %s"), $filename),
657 // E_USER_NOTICE); //debugging
660 closedir($dir_handle);
665 // Class introspections
667 /** Determine whether object is of a specified type.
669 * @param $object object An object.
670 * @param $class string Class name.
671 * @return bool True iff $object is a $class
672 * or a sub-type of $class.
674 function isa ($object, $class)
676 $lclass = strtolower($class);
678 return is_object($object)
679 && ( get_class($object) == strtolower($lclass)
680 || is_subclass_of($object, $lclass) );
683 /** Determine whether (possible) object has method.
685 * @param $object mixed Object
686 * @param $method string Method name
687 * @return bool True iff $object is an object with has method $method.
689 function can ($object, $method)
691 return is_object($object) && method_exists($object, strtolower($method));
695 * Seed the random number generator.
697 * better_srand() ensures the randomizer is seeded only once.
699 * How random do you want it? See:
700 * http://www.php.net/manual/en/function.srand.php
701 * http://www.php.net/manual/en/function.mt-srand.php
703 function better_srand($seed = '') {
704 static $wascalled = FALSE;
706 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
709 //trigger_error("new random seed", E_USER_NOTICE); //debugging
713 // (c-file-style: "gnu")
718 // c-hanging-comment-ender-p: nil
719 // indent-tabs-mode: nil