1 <?php rcs_id('$Id: stdlib.php,v 1.110 2002-02-23 01:45:17 carstenklapp 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 = false) {
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 <, >, \"")));
123 $link = HTML::img(array('src' => $url, 'alt' => $alt));
125 $link->setAttr('class', 'inlineimage');
132 var $items = array();
135 function push($item) {
136 $this->items[$this->size] = $item;
142 if ($this->size == 0) {
143 return false; // stack is empty
146 return $this->items[$this->size];
155 return $this->items[$this->size - 1];
161 // end class definition
164 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
165 // HACK: so as to not completely break old PhpWikiAdministration pages.
166 trigger_error("MagicPhpWikiURL forms are no longer supported. "
167 . "Use the WikiFormPlugin instead.", E_USER_NOTICE);
170 $loader = new WikiPluginLoader;
171 @$action = (string)$args['action'];
172 return $loader->expandPI("<?plugin WikiForm action=$action ?>", $request);
175 function SplitQueryArgs ($query_args = '')
177 $split_args = split('&', $query_args);
179 while (list($key, $val) = each($split_args))
180 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
181 $args[$m[1]] = $m[2];
185 function LinkPhpwikiURL($url, $text = '') {
188 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
189 return HTML::strong(array('class' => 'rawurl'),
190 HTML::u(array('class' => 'baduri'),
191 _("BAD phpwiki: URL")));
195 $pagename = urldecode($m[1]);
198 if (empty($pagename) &&
199 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
200 // Convert old style links (to not break diff links in
202 $pagename = urldecode($m[2]);
203 $args = array("action" => $m[1]);
206 $args = SplitQueryArgs($qargs);
209 if (empty($pagename))
210 $pagename = $GLOBALS['request']->getArg('pagename');
212 if (isset($args['action']) && $args['action'] == 'browse')
213 unset($args['action']);
216 if (empty($args['action']))
218 else if (is_safe_action($args['action']))
219 $class = 'wikiaction';
221 if (empty($args['action']) || is_safe_action($args['action']))
222 $class = 'wikiaction';
224 // Don't allow administrative links on unlocked pages.
225 $page = $GLOBALS['request']->getPage();
226 if (!$page->get('locked'))
227 return HTML::span(array('class' => 'wikiunsafe'),
228 HTML::u(_("Lock page to enable link")));
229 $class = 'wikiadmin';
232 // FIXME: ug, don't like this
233 if (preg_match('/=\d*\(/', $qargs))
234 return MakeWikiForm($pagename, $args, $class, $text);
236 $text = HTML::span(array('class' => 'rawurl'), $url);
238 return HTML::a(array('href' => WikiURL($pagename, $args),
243 function LinkBracketLink($bracketlink) {
244 global $request, $AllowedProtocols, $InlineImages;
246 include_once("lib/interwiki.php");
247 $intermap = InterWikiMap::GetMap($request);
249 // $bracketlink will start and end with brackets; in between will
250 // be either a page name, a URL or both separated by a pipe.
252 // strip brackets and leading space
253 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
254 // match the contents
255 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
257 if (isset($matches[3])) {
258 // named link of the form "[some link name | http://blippy.com/]"
259 $URL = trim($matches[3]);
260 $linkname = trim($matches[1]);
262 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
263 $URL = trim($matches[1]);
267 $dbi = $request->getDbh();
268 if ($dbi->isWikiPage($URL))
269 return WikiLink($URL, 'known', $linkname);
270 elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
271 // if it's an image, embed it; otherwise, it's a regular link
272 if (preg_match("/($InlineImages)$/i", $URL))
273 return LinkImage($URL, $linkname);
275 return LinkURL($URL, $linkname);
277 elseif (preg_match("/^phpwiki:/", $URL))
278 return LinkPhpwikiURL($URL, $linkname);
279 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $URL))
280 return $intermap->link($URL, $linkname);
282 return WikiLink($URL, 'unknown', $linkname);
287 /* FIXME: this should be done by the transform code */
288 function ExtractWikiPageLinks($content) {
289 global $WikiNameRegexp;
291 if (is_string($content))
292 $content = explode("\n", $content);
294 $wikilinks = array();
295 foreach ($content as $line) {
296 // remove plugin code
297 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
298 // remove escaped '['
299 $line = str_replace('[[', ' ', $line);
301 $line = preg_replace('/[\d+]/', ' ', $line);
303 // bracket links (only type wiki-* is of interest)
304 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
306 for ($i = 0; $i < $numBracketLinks; $i++) {
307 $link = LinkBracketLink($brktlinks[0][$i]);
308 if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
309 $wikilinks[$brktlinks[2][$i]] = 1;
311 $brktlink = preg_quote($brktlinks[0][$i]);
312 $line = preg_replace("|$brktlink|", '', $line);
315 // BumpyText old-style wiki links
316 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
317 for ($i = 0; isset($link[0][$i]); $i++) {
318 if($link[0][$i][0] <> '!')
319 $wikilinks[$link[0][$i]] = 1;
323 return array_keys($wikilinks);
327 * Convert old page markup to new-style markup.
329 * @param $text string Old-style wiki markup.
331 * @param $just_links bool Only convert old-style links.
332 * (Really this only converts escaped old-style links.)
334 * @return string New-style wiki markup.
336 * @bugs FIXME: footnotes and old-style tables are known to be broken.
338 function ConvertOldMarkup ($text, $just_links = false) {
340 static $orig, $repl, $link_orig, $link_repl;
343 /*****************************************************************
344 * Conversions for inline markup:
351 // escape escaped brackets
355 // change ! escapes to ~'s.
356 global $AllowedProtocols, $WikiNameRegexp, $request;
357 include_once('lib/interwiki.php');
358 $map = InterWikiMap::GetMap($request);
359 $bang_esc[] = "(?:$AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
360 $bang_esc[] = $map->getRegexp() . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
361 $bang_esc[] = $WikiNameRegexp;
362 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
369 /*****************************************************************
370 * Conversions for block markup
372 // convert indented blocks to <pre></pre>.
373 $orig[] = '/^[ \t]+\S.*\n(?:(?:\s*\n)?^[ \t]+\S.*\n)*/m';
374 $repl[] = "<pre>\n\\0</pre>\n";
377 $orig[] = '/^([#*;]*)([*#]|;.*?:) */me';
378 $repl[] = "_ConvertOldListMarkup('\\1', '\\2')";
383 return preg_replace($link_orig, $link_repl, $text);
385 return preg_replace($orig, $repl, $text);
388 function _ConvertOldListMarkup ($indent, $bullet) {
389 $indent = str_repeat(' ', strlen($indent));
390 if ($bullet[0] == ';') {
391 $term = ltrim(substr($bullet, 1));
392 return $indent . $term . "\n" . $indent . ' ';
395 return $indent . $bullet . ' ';
401 * Split WikiWords in page names.
403 * It has been deemed useful to split WikiWords (into "Wiki Words") in
404 * places like page titles. This is rumored to help search engines
407 * @param $page string The page name.
409 * @return string The split name.
411 function split_pagename ($page) {
413 if (preg_match("/\s/", $page))
414 return $page; // Already split --- don't split any more.
416 // FIXME: this algorithm is Anglo-centric.
419 // This mess splits between a lower-case letter followed by
420 // either an upper-case or a numeral; except that it wont
421 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
422 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
423 // This the single-letter words 'I' and 'A' from any following
424 // capitalized words.
425 $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
426 // Split numerals from following letters.
427 $RE[] = '/(\d)([[:alpha:]])/';
429 foreach ($RE as $key => $val)
430 $RE[$key] = pcre_fix_posix_classes($val);
433 foreach ($RE as $regexp)
434 $page = preg_replace($regexp, '\\1 \\2', $page);
438 function NoSuchRevision (&$request, $page, $version) {
439 $html = HTML(HTML::h2(_("Revision Not Found")),
440 HTML::p(fmt("I'm sorry. Version %d of %s is not in my database.",
441 $version, WikiLink($page, 'auto'))));
442 include_once('lib/Template.php');
443 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
449 * Get time offset for local time zone.
451 * @param $time time_t Get offset for this time. Default: now.
452 * @param $no_colon boolean Don't put colon between hours and minutes.
453 * @return string Offset as a string in the format +HH:MM.
455 function TimezoneOffset ($time = false, $no_colon = false) {
458 $secs = date('Z', $time);
467 $colon = $no_colon ? '' : ':';
468 $mins = intval(($secs + 30) / 60);
469 return sprintf("%s%02d%s%02d",
470 $sign, $mins / 60, $colon, $mins % 60);
475 * Format time in ISO-8601 format.
477 * @param $time time_t Time. Default: now.
478 * @return string Date and time in ISO-8601 format.
480 function Iso8601DateTime ($time = false) {
483 $tzoff = TimezoneOffset($time);
484 $date = date('Y-m-d', $time);
485 $time = date('H:i:s', $time);
486 return $date . 'T' . $time . $tzoff;
490 * Format time in RFC-2822 format.
492 * @param $time time_t Time. Default: now.
493 * @return string Date and time in RFC-2822 format.
495 function Rfc2822DateTime ($time = false) {
498 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
502 * Format time to standard 'ctime' format.
504 * @param $time time_t Time. Default: now.
505 * @return string Date and time.
507 function CTime ($time = false)
511 return date("D M j H:i:s Y", $time);
517 * Internationalized printf.
519 * This is essentially the same as PHP's built-in printf
520 * with the following exceptions:
522 * <li> It passes the format string through gettext().
523 * <li> It supports the argument reordering extensions.
530 * __printf("Differences between versions %s and %s of %s",
531 * $new_link, $old_link, $page_link);
534 * Then in locale/po/de.po, one can reorder the printf arguments:
537 * msgid "Differences between %s and %s of %s."
538 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
541 * (Note that while PHP tries to expand $vars within double-quotes,
542 * the values in msgstr undergo no such expansion, so the '$'s
545 * One shouldn't use reordered arguments in the default format string.
546 * Backslashes in the default string would be necessary to escape the
547 * '$'s, and they'll cause all kinds of trouble....
549 function __printf ($fmt) {
550 $args = func_get_args();
552 echo __vsprintf($fmt, $args);
556 * Internationalized sprintf.
558 * This is essentially the same as PHP's built-in printf with the
559 * following exceptions:
562 * <li> It passes the format string through gettext().
563 * <li> It supports the argument reordering extensions.
568 function __sprintf ($fmt) {
569 $args = func_get_args();
571 return __vsprintf($fmt, $args);
575 * Internationalized vsprintf.
577 * This is essentially the same as PHP's built-in printf with the
578 * following exceptions:
581 * <li> It passes the format string through gettext().
582 * <li> It supports the argument reordering extensions.
587 function __vsprintf ($fmt, $args) {
588 $fmt = gettext($fmt);
589 // PHP's sprintf doesn't support variable with specifiers,
590 // like sprintf("%*s", 10, "x"); --- so we won't either.
592 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
593 // Format string has '%2$s' style argument reordering.
594 // PHP doesn't support this.
595 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
596 // literal variable name substitution only to keep locale
597 // strings uncluttered
598 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
599 '%1\$s','%s'), E_USER_WARNING); //php+locale error
601 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
604 // Reorder arguments appropriately.
605 foreach($m[1] as $argnum) {
606 if ($argnum < 1 || $argnum > count($args))
607 trigger_error(sprintf(_("%s: argument index out of range"),
608 $argnum), E_USER_WARNING);
609 $newargs[] = $args[$argnum - 1];
614 // Not all PHP's have vsprintf, so...
615 array_unshift($args, $fmt);
616 return call_user_func_array('sprintf', $args);
622 * Build an array in $this->_fileList of files from $dirname.
623 * Subdirectories are not traversed.
625 * (This was a function LoadDir in lib/loadsave.php)
626 * See also http://www.php.net/manual/en/function.readdir.php
628 function getFiles() {
629 return $this->_fileList;
632 function _filenameSelector($filename) {
633 // Default selects all filenames, override as needed.
637 function fileSet($directory) {
638 $this->_fileList = array();
640 if (empty($directory)) {
641 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
643 return; // early return
646 @ $dir_handle = opendir($dir=$directory);
647 if (empty($dir_handle)) {
648 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
649 $dir), E_USER_NOTICE);
650 return; // early return
653 while ($filename = readdir($dir_handle)) {
654 if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
656 if ($this->_filenameSelector($filename)) {
657 array_push($this->_fileList, "$filename");
658 //trigger_error(sprintf(_("found file %s"), $filename),
659 // E_USER_NOTICE); //debugging
662 closedir($dir_handle);
667 // Class introspections
669 /** Determine whether object is of a specified type.
671 * @param $object object An object.
672 * @param $class string Class name.
673 * @return bool True iff $object is a $class
674 * or a sub-type of $class.
676 function isa ($object, $class)
678 $lclass = strtolower($class);
680 return is_object($object)
681 && ( get_class($object) == strtolower($lclass)
682 || is_subclass_of($object, $lclass) );
685 /** Determine whether (possible) object has method.
687 * @param $object mixed Object
688 * @param $method string Method name
689 * @return bool True iff $object is an object with has method $method.
691 function can ($object, $method)
693 return is_object($object) && method_exists($object, strtolower($method));
697 * Seed the random number generator.
699 * better_srand() ensures the randomizer is seeded only once.
701 * How random do you want it? See:
702 * http://www.php.net/manual/en/function.srand.php
703 * http://www.php.net/manual/en/function.mt-srand.php
705 function better_srand($seed = '') {
706 static $wascalled = FALSE;
708 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
711 //trigger_error("new random seed", E_USER_NOTICE); //debugging
716 * Recursively count all non-empty elements
717 * in array of any dimension or mixed - i.e.
718 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
719 * See http://www.php.net/manual/en/function.count.php
721 function count_all($arg)
723 // skip if argument is empty
725 //print_r($arg); //debugging
727 // not an array, return 1 (base case)
730 // else call recursively for all elements $arg
731 foreach($arg as $key => $val)
732 $count += count_all($val);
738 // (c-file-style: "gnu")
743 // c-hanging-comment-ender-p: nil
744 // indent-tabs-mode: nil