1 <?php //rcs_id('$Id: stdlib.php,v 1.196 2004-07-01 08:51:22 rurban Exp $');
4 Standard functions for Wiki functionality
5 WikiURL($pagename, $args, $get_abs_url)
6 IconForLink($protocol_or_url)
7 LinkURL($url, $linktext)
10 SplitQueryArgs ($query_args)
11 LinkPhpwikiURL($url, $text)
12 ConvertOldMarkup($content)
14 class Stack { push($item), pop(), cnt(), top() }
17 NoSuchRevision ($request, $page, $version)
18 TimezoneOffset ($time, $no_colon)
19 Iso8601DateTime ($time)
20 Rfc2822DateTime ($time)
24 __vsprintf ($fmt, $args)
25 better_srand($seed = '')
28 subPageSlice($pagename, $pos)
29 explodePageList($input, $perm = false)
31 function: LinkInterWikiLink($link, $linktext)
32 moved to: lib/interwiki.php
33 function: linkExistingWikiWord($wikiword, $linktext, $version)
34 moved to: lib/Theme.php
35 function: LinkUnknownWikiWord($wikiword, $linktext)
36 moved to: lib/Theme.php
37 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
38 gone see: lib/plugin/RecentChanges.php
40 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
41 else define('_PHPWIKI_STDLIB_LOADED',true);
43 define('MAX_PAGENAME_LENGTH', 100);
47 * Convert string to a valid XML identifier.
49 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
51 * We would like to have, e.g. named anchors within wiki pages
52 * names like "Table of Contents" --- clearly not a valid XML
53 * fragment identifier.
55 * This function implements a one-to-one map from {any string}
56 * to {valid XML identifiers}.
59 * converting all bytes not in [A-Za-z0-9:_-],
60 * and any leading byte not in [A-Za-z] to 'xbb.',
61 * where 'bb' is the hexadecimal representation of the
64 * As a special case, the empty string is converted to 'empty.'
69 function MangleXmlIdentifier($str) {
73 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
74 "'x' . sprintf('%02x', ord('\\0')) . '.'",
78 function UnMangleXmlIdentifier($str) {
81 return preg_replace('/x(\w\w)\./e',
82 "sprintf('%c', hex('\\0'))",
87 * Generates a valid URL for a given Wiki pagename.
88 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
89 * If a WikiDB_Page object function will extract the name to link to.
90 * If a WikiDB_PageRevision object function will extract the name to link to.
92 * @param boolean $get_abs_url Default value is false.
93 * @return string The absolute URL to the page passed as $pagename.
95 function WikiURL($pagename, $args = '', $get_abs_url = false) {
98 if (is_object($pagename)) {
99 if (isa($pagename, 'WikiDB_Page')) {
100 $pagename = $pagename->getName();
102 elseif (isa($pagename, 'WikiDB_PageRevision')) {
103 $page = $pagename->getPage();
104 $args['version'] = $pagename->getVersion();
105 $pagename = $page->getName();
107 elseif (isa($pagename, 'WikiPageName')) {
108 $anchor = $pagename->anchor;
109 $pagename = $pagename->name;
111 $anchor = $pagename->anchor;
112 $pagename = $pagename->name;
116 if (is_array($args)) {
118 foreach ($args as $key => $val) {
119 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
120 $enc_args[] = urlencode($key) . '=' . urlencode($val);
122 $args = join('&', $enc_args);
126 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
127 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
132 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
133 $url .= "?pagename=" . rawurlencode($pagename);
138 $url .= "#" . MangleXmlIdentifier($anchor);
142 /** Convert relative URL to absolute URL.
144 * This converts a relative URL to one of PhpWiki's support files
145 * to an absolute one.
148 * @return string Absolute URL
150 function AbsoluteURL ($url) {
151 if (preg_match('/^https?:/', $url))
153 if ($url[0] != '/') {
154 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
155 while ($base != '/' and substr($url, 0, 3) == "../") {
156 $url = substr($url, 3);
157 $base = dirname($base);
163 return SERVER_URL . $url;
167 * Generates icon in front of links.
169 * @param string $protocol_or_url URL or protocol to determine which icon to use.
171 * @return HtmlElement HtmlElement object that contains data to create img link to
172 * icon for use with url or protocol passed to the function. False if no img to be
175 function IconForLink($protocol_or_url) {
177 if (0 and $filename_suffix == false) {
178 // display apache style icon for file type instead of protocol icon
179 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
180 // - document: html, htm, text, txt, rtf, pdf, doc
181 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
182 // - audio: mp3,mp2,aiff,aif,au
183 // - multimedia: mpeg,mpg,mov,qt
185 list ($proto) = explode(':', $protocol_or_url, 2);
186 $src = $WikiTheme->getLinkIconURL($proto);
188 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
195 * Glue icon in front of or after text.
196 * Pref: 'noLinkIcons' - ignore icon if set
197 * Theme: 'LinkIcons' - 'yes' at front
198 * - 'no' display no icon
199 * - 'front' display at left
200 * - 'after' display at right
202 * @param string $protocol_or_url Protocol or URL. Used to determine the
204 * @param string $text The text.
205 * @return XmlContent.
207 function PossiblyGlueIconToText($proto_or_url, $text) {
208 global $request, $WikiTheme;
209 if ($request->getPref('noLinkIcons'))
211 $icon = IconForLink($proto_or_url);
214 if ($where = $WikiTheme->getLinkIconAttr()) {
215 if ($where == 'no') return $text;
216 if ($where != 'after') $where = 'front';
220 if ($where == 'after') {
221 // span the icon only to the last word (tie them together),
222 // to let the previous words wrap on line breaks.
223 if (!is_object($text)) {
224 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
225 list (, $prefix, $last_word) = $m;
231 $text = HTML::span(array('style' => 'white-space: nowrap'),
232 $last_word, HTML::Raw(' '), $icon);
234 $text = HTML($prefix, $text);
237 // span the icon only to the first word (tie them together),
238 // to let the next words wrap on line breaks
239 if (!is_object($text)) {
240 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
241 list (, $first_word, $tail) = $m;
247 $text = HTML::span(array('style' => 'white-space: nowrap'),
250 $text = HTML($text, $tail);
255 * Determines if the url passed to function is safe, by detecting if the characters
256 * '<', '>', or '"' are present.
258 * @param string $url URL to check for unsafe characters.
259 * @return boolean True if same, false else.
261 function IsSafeURL($url) {
262 return !ereg('[<>"]', $url);
266 * Generates an HtmlElement object to store data for a link.
268 * @param string $url URL that the link will point to.
269 * @param string $linktext Text to be displayed as link.
270 * @return HtmlElement HtmlElement object that contains data to construct an html link.
272 function LinkURL($url, $linktext = '') {
273 // FIXME: Is this needed (or sufficient?)
274 if(! IsSafeURL($url)) {
275 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
276 _("BAD URL -- remove all of <, >, \"")));
280 $linktext = preg_replace("/mailto:/A", "", $url);
282 $link = HTML::a(array('href' => $url),
283 PossiblyGlueIconToText($url, $linktext));
286 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
291 * FIXME: disallow sizes which are too small.
292 * Spammers may use such (typically invisible) image attributes to higher their GoogleRank.
294 function LinkImage($url, $alt = false) {
295 // FIXME: Is this needed (or sufficient?)
296 if(! IsSafeURL($url)) {
297 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
298 _("BAD URL -- remove all of <, >, \"")));
300 // support new syntax: [image.jpg size=50% border=n]
301 $arr = split(' ',$url);
302 if (count($arr) > 1) {
305 if (empty($alt)) $alt = basename($url);
306 $link = HTML::img(array('src' => $url, 'alt' => $alt));
307 if (count($arr) > 1) {
309 foreach ($arr as $attr) {
310 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
311 $link->setAttr('width',$m[1]);
312 $link->setAttr('height',$m[1]);
314 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
315 $link->setAttr('width',$m[1]);
316 $link->setAttr('height',$m[2]);
318 if (preg_match('/^border=(\d+)$/',$attr,$m))
319 $link->setAttr('border',$m[1]);
320 if (preg_match('/^align=(\w+)$/',$attr,$m))
321 $link->setAttr('align',$m[1]);
322 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
323 $link->setAttr('hspace',$m[1]);
324 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
325 $link->setAttr('vspace',$m[1]);
328 // check width and height as spam countermeasure
329 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
330 $width = (integer) $width; // px or % or other suffix
331 $height = (integer) $height;
332 if (($width < 3 and $height < 10) or
333 ($height < 3 and $width < 20) or
334 ($height < 7 and $width < 7))
336 trigger_error(_("Invalid image size"), E_USER_NOTICE);
339 } elseif ($size = @getimagesize($url)) {
342 if (($width < 3 and $height < 10) or
343 ($height < 3 and $width < 20) or
344 ($height < 7 and $width < 7))
346 trigger_error(_("Invalid image size"), E_USER_NOTICE);
351 $link->setAttr('class', 'inlineimage');
358 var $items = array();
360 // var in php5.0.0.rc1 deprecated
362 function push($item) {
363 $this->items[$this->size] = $item;
369 if ($this->size == 0) {
370 return false; // stack is empty
373 return $this->items[$this->size];
382 return $this->items[$this->size - 1];
388 // end class definition
390 function SplitQueryArgs ($query_args = '')
392 $split_args = split('&', $query_args);
394 while (list($key, $val) = each($split_args))
395 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
396 $args[$m[1]] = $m[2];
400 function LinkPhpwikiURL($url, $text = '', $basepage) {
403 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
404 return HTML::strong(array('class' => 'rawurl'),
405 HTML::u(array('class' => 'baduri'),
406 _("BAD phpwiki: URL")));
410 $pagename = urldecode($m[1]);
413 if (empty($pagename) &&
414 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
415 // Convert old style links (to not break diff links in
417 $pagename = urldecode($m[2]);
418 $args = array("action" => $m[1]);
421 $args = SplitQueryArgs($qargs);
424 if (empty($pagename))
425 $pagename = $GLOBALS['request']->getArg('pagename');
427 if (isset($args['action']) && $args['action'] == 'browse')
428 unset($args['action']);
431 if (empty($args['action']))
433 else if (is_safe_action($args['action']))
434 $class = 'wikiaction';
436 if (empty($args['action']) || is_safe_action($args['action']))
437 $class = 'wikiaction';
439 // Don't allow administrative links on unlocked pages.
440 $dbi = $GLOBALS['request']->getDbh();
441 $page = $dbi->getPage($basepage);
442 if (!$page->get('locked'))
443 return HTML::span(array('class' => 'wikiunsafe'),
444 HTML::u(_("Lock page to enable link")));
445 $class = 'wikiadmin';
449 $text = HTML::span(array('class' => 'rawurl'), $url);
451 $wikipage = new WikiPageName($pagename);
452 if (!$wikipage->isValid()) {
454 return $WikiTheme->linkBadWikiWord($wikipage, $url);
457 return HTML::a(array('href' => WikiURL($pagename, $args),
463 * A class to assist in parsing wiki pagenames.
465 * Now with subpages and anchors, parsing and passing around
466 * pagenames is more complicated. This should help.
470 /** Short name for page.
472 * This is the value of $name passed to the constructor.
473 * (For use, e.g. as a default label for links to the page.)
477 /** The full page name.
479 * This is the full name of the page (without anchor).
485 * This is the referenced anchor within the page, or the empty string.
491 * @param mixed $name Page name.
492 * WikiDB_Page, WikiDB_PageRevision, or string.
493 * This can be a relative subpage name (like '/SubPage'),
494 * or can be the empty string to refer to the $basename.
496 * @param string $anchor For links to anchors in page.
498 * @param mixed $basename Page name from which to interpret
499 * relative or other non-fully-specified page names.
501 function WikiPageName($name, $basename=false, $anchor=false) {
502 if (is_string($name)) {
503 $this->shortName = $name;
505 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
507 $name = $this->_pagename($basename) . $name;
509 $name = $this->_normalize_bad_pagename($name);
513 $name = $this->_pagename($name);
514 $this->shortName = $name;
517 $this->name = $this->_check($name);
518 $this->anchor = (string)$anchor;
521 function getParent() {
523 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
525 return substr($name, 0, -strlen($tail));
528 function isValid($strict = false) {
530 return !isset($this->_errors);
531 return (is_string($this->name) and $this->name != '');
534 function getWarnings() {
536 if (isset($this->_warnings))
537 $warnings = array_merge($warnings, $this->_warnings);
538 if (isset($this->_errors))
539 $warnings = array_merge($warnings, $this->_errors);
543 return sprintf(_("'%s': Bad page name: %s"),
544 $this->shortName, join(', ', $warnings));
547 function _pagename($page) {
548 if (isa($page, 'WikiDB_Page'))
549 return $page->getName();
550 elseif (isa($page, 'WikiDB_PageRevision'))
551 return $page->getPageName();
552 elseif (isa($page, 'WikiPageName'))
554 if (!is_string($page)) {
555 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
556 $page, gettype($page), get_class($page)),
559 //assert(is_string($page));
563 function _normalize_bad_pagename($name) {
564 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
566 // Punt... You really shouldn't get here.
569 return $request->getArg('pagename');
571 assert($name[0] == SUBPAGE_SEPARATOR);
572 return substr($name, 1);
576 function _check($pagename) {
577 // Compress internal white-space to single space character.
578 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
579 if ($pagename != $orig)
580 $this->_warnings[] = _("White space converted to single space");
582 // Delete any control characters.
583 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
584 if ($pagename != $orig)
585 $this->_errors[] = _("Control characters not allowed");
587 // Strip leading and trailing white-space.
588 $pagename = trim($pagename);
591 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
592 $pagename = substr($pagename, 1);
593 if ($pagename != $orig)
594 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
596 if (preg_match('/[:;]/', $pagename))
597 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
599 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
600 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
601 $this->_errors[] = _("too long");
605 if ($pagename == '.' or $pagename == '..') {
606 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
615 * Convert old page markup to new-style markup.
617 * @param string $text Old-style wiki markup.
619 * @param string $markup_type
621 * <dt><code>"block"</code> <dd>Convert all markup.
622 * <dt><code>"inline"</code> <dd>Convert only inline markup.
623 * <dt><code>"links"</code> <dd>Convert only link markup.
626 * @return string New-style wiki markup.
628 * @bugs Footnotes don't work quite as before (esp if there are
629 * multiple references to the same footnote. But close enough,
630 * probably for now....
631 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
632 * AnciennesR%E8glesDeFormatage. ( at the 2nd attempt to do the anchored block regex )
633 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
634 * also known to crash, even with Apache1.
636 function ConvertOldMarkup ($text, $markup_type = "block") {
642 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
643 // AnciennesR%E8glesDeFormatage crashes.
644 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
645 // also known to crash, even with Apache1.
647 // I suspect this only to crash with Apache2 and IIS.
648 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
649 and preg_match("/plugin CreateToc/", $text))
651 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
652 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
653 ._("Skipped."), E_USER_WARNING);
655 //if (!DEBUG) return $text;
660 /*****************************************************************
661 * Conversions for inline markup:
668 // escape escaped brackets
672 // change ! escapes to ~'s.
673 global $WikiNameRegexp, $request;
674 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
675 $map = getInterwikiMap();
676 if ($map_regex = $map->getRegexp())
677 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
678 $bang_esc[] = $WikiNameRegexp;
679 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
682 $subs["links"] = array($orig, $repl);
685 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
688 // Convert footnote references.
689 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
690 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
692 // Convert old style emphases to HTML style emphasis.
693 $orig[] = '/__(.*?)__/';
694 $repl[] = '<strong>\\1</strong>';
695 $orig[] = "/''(.*?)''/";
696 $repl[] = '<em>\\1</em>';
698 // Escape nestled markup.
699 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
702 // in old markup headings only allowed at beginning of line
706 $subs["inline"] = array($orig, $repl);
708 /*****************************************************************
709 * Patterns which match block markup constructs which take
710 * special handling...
714 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
716 $blockpats[] = '\|(?:.*\n\|)*';
719 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
721 // Footnote definitions
722 $blockpats[] = '\[\s*(\d+)\s*\]';
726 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
730 $blockpats[] = '!{1,3}[^!]';
732 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
733 . join("|", $blockpats)
738 if ($markup_type != "block") {
739 list ($orig, $repl) = $subs[$markup_type];
740 return preg_replace($orig, $repl, $text);
743 list ($orig, $repl) = $subs['inline'];
746 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
747 // AnciennesR%E8glesDeFormatage and more
748 while (preg_match($block_re, $text, $m)) {
749 $text = substr($text, strlen($m[0]));
750 list (,$leading_text, $block) = $m;
753 if (strchr(" \t", $block[0])) {
756 $suffix = "\n</pre>\n";
758 elseif ($block[0] == '|') {
760 $prefix = "<?plugin OldStyleTable\n";
763 elseif (strchr("#*;", $block[0])) {
764 // Old-style list item
765 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
766 list (,$ind,$bullet) = $m;
767 $block = substr($block, strlen($m[0]));
769 $indent = str_repeat(' ', strlen($ind));
770 if ($bullet[0] == ';') {
771 //$term = ltrim(substr($bullet, 1));
772 //return $indent . $term . "\n" . $indent . ' ';
773 $prefix = $ind . $bullet;
776 $prefix = $indent . $bullet . ' ';
778 elseif ($block[0] == '[') {
779 // Footnote definition
780 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
782 $block = substr($block, strlen($m[0]));
783 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
785 elseif ($block[0] == '<') {
787 // HACK: no inline markup...
791 elseif ($block[0] == '!') {
793 preg_match('/^!{1,3}/', $block, $m);
795 $block = substr($block, strlen($m[0]));
801 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
802 if ($block) $block = preg_replace($orig, $repl, $block);
803 $out .= $leading_text;
808 return $out . preg_replace($orig, $repl, $text);
814 * Expand tabs in string.
816 * Converts all tabs to (the appropriate number of) spaces.
819 * @param integer $tab_width
822 function expand_tabs($str, $tab_width = 8) {
823 $split = split("\t", $str);
824 $tail = array_pop($split);
826 foreach ($split as $hunk) {
828 $pos = strlen(strrchr($expanded, "\n")) - 1;
829 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
831 return substr($expanded, 1) . $tail;
835 * Split WikiWords in page names.
837 * It has been deemed useful to split WikiWords (into "Wiki Words") in
838 * places like page titles. This is rumored to help search engines
841 * @param $page string The page name.
843 * @return string The split name.
845 function SplitPagename ($page) {
847 if (preg_match("/\s/", $page))
848 return $page; // Already split --- don't split any more.
850 // This algorithm is specialized for several languages.
851 // (Thanks to Pierrick MEIGNEN)
852 // Improvements for other languages welcome.
855 // This mess splits between a lower-case letter followed by
856 // either an upper-case or a numeral; except that it wont
857 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
858 switch ($GLOBALS['LANG']) {
863 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
866 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
869 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
870 // This the single-letter words 'I' and 'A' from any following
871 // capitalized words.
872 switch ($GLOBALS['LANG']) {
874 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
877 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
880 // Split numerals from following letters.
881 $RE[] = '/(\d)([[:alpha:]])/';
882 // Split at subpage seperators. TBD in Theme.php
883 $RE[] = "/([^${sep}]+)(${sep})/";
885 foreach ($RE as $key)
886 $RE[$key] = pcre_fix_posix_classes($key);
889 foreach ($RE as $regexp) {
890 $page = preg_replace($regexp, '\\1 \\2', $page);
895 function NoSuchRevision (&$request, $page, $version) {
896 $html = HTML(HTML::h2(_("Revision Not Found")),
897 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
898 $version, WikiLink($page, 'auto'))));
899 include_once('lib/Template.php');
900 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
906 * Get time offset for local time zone.
908 * @param $time time_t Get offset for this time. Default: now.
909 * @param $no_colon boolean Don't put colon between hours and minutes.
910 * @return string Offset as a string in the format +HH:MM.
912 function TimezoneOffset ($time = false, $no_colon = false) {
915 $secs = date('Z', $time);
924 $colon = $no_colon ? '' : ':';
925 $mins = intval(($secs + 30) / 60);
926 return sprintf("%s%02d%s%02d",
927 $sign, $mins / 60, $colon, $mins % 60);
932 * Format time in ISO-8601 format.
934 * @param $time time_t Time. Default: now.
935 * @return string Date and time in ISO-8601 format.
937 function Iso8601DateTime ($time = false) {
940 $tzoff = TimezoneOffset($time);
941 $date = date('Y-m-d', $time);
942 $time = date('H:i:s', $time);
943 return $date . 'T' . $time . $tzoff;
947 * Format time in RFC-2822 format.
949 * @param $time time_t Time. Default: now.
950 * @return string Date and time in RFC-2822 format.
952 function Rfc2822DateTime ($time = false) {
955 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
959 * Format time in RFC-1123 format.
961 * @param $time time_t Time. Default: now.
962 * @return string Date and time in RFC-1123 format.
964 function Rfc1123DateTime ($time = false) {
967 return gmdate('D, d M Y H:i:s \G\M\T', $time);
970 /** Parse date in RFC-1123 format.
972 * According to RFC 1123 we must accept dates in the following
975 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
976 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
977 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
979 * (Though we're only allowed to generate dates in the first format.)
981 function ParseRfc1123DateTime ($timestr) {
982 $timestr = trim($timestr);
983 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
984 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
986 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
988 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
989 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
991 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
992 if ($year < 70) $year += 2000;
993 elseif ($year < 100) $year += 1900;
995 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
996 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
998 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1005 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1007 return false; // failed
1012 * Format time to standard 'ctime' format.
1014 * @param $time time_t Time. Default: now.
1015 * @return string Date and time.
1017 function CTime ($time = false)
1019 if ($time === false)
1021 return date("D M j H:i:s Y", $time);
1026 * Format number as kilobytes or bytes.
1027 * Short format is used for PageList
1028 * Long format is used in PageInfo
1030 * @param $bytes int. Default: 0.
1031 * @param $longformat bool. Default: false.
1032 * @return class FormattedText (XmlElement.php).
1034 function ByteFormatter ($bytes = 0, $longformat = false) {
1037 if ($bytes < 1024) {
1039 $size = fmt("%s b", $bytes);
1041 $size = fmt("%s bytes", $bytes);
1044 $kb = round($bytes / 1024, 1);
1046 $size = fmt("%s k", $kb);
1048 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1054 * Internationalized printf.
1056 * This is essentially the same as PHP's built-in printf
1057 * with the following exceptions:
1059 * <li> It passes the format string through gettext().
1060 * <li> It supports the argument reordering extensions.
1067 * __printf("Differences between versions %s and %s of %s",
1068 * $new_link, $old_link, $page_link);
1071 * Then in locale/po/de.po, one can reorder the printf arguments:
1074 * msgid "Differences between %s and %s of %s."
1075 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1078 * (Note that while PHP tries to expand $vars within double-quotes,
1079 * the values in msgstr undergo no such expansion, so the '$'s
1082 * One shouldn't use reordered arguments in the default format string.
1083 * Backslashes in the default string would be necessary to escape the
1084 * '$'s, and they'll cause all kinds of trouble....
1086 function __printf ($fmt) {
1087 $args = func_get_args();
1089 echo __vsprintf($fmt, $args);
1093 * Internationalized sprintf.
1095 * This is essentially the same as PHP's built-in printf with the
1096 * following exceptions:
1099 * <li> It passes the format string through gettext().
1100 * <li> It supports the argument reordering extensions.
1105 function __sprintf ($fmt) {
1106 $args = func_get_args();
1108 return __vsprintf($fmt, $args);
1112 * Internationalized vsprintf.
1114 * This is essentially the same as PHP's built-in printf with the
1115 * following exceptions:
1118 * <li> It passes the format string through gettext().
1119 * <li> It supports the argument reordering extensions.
1124 function __vsprintf ($fmt, $args) {
1125 $fmt = gettext($fmt);
1126 // PHP's sprintf doesn't support variable with specifiers,
1127 // like sprintf("%*s", 10, "x"); --- so we won't either.
1129 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1130 // Format string has '%2$s' style argument reordering.
1131 // PHP doesn't support this.
1132 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1133 // literal variable name substitution only to keep locale
1134 // strings uncluttered
1135 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1136 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1138 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1141 // Reorder arguments appropriately.
1142 foreach($m[1] as $argnum) {
1143 if ($argnum < 1 || $argnum > count($args))
1144 trigger_error(sprintf(_("%s: argument index out of range"),
1145 $argnum), E_USER_WARNING);
1146 $newargs[] = $args[$argnum - 1];
1151 // Not all PHP's have vsprintf, so...
1152 array_unshift($args, $fmt);
1153 return call_user_func_array('sprintf', $args);
1156 function file_mtime ($filename) {
1157 if ($stat = @stat($filename))
1163 function sort_file_mtime ($a, $b) {
1164 $ma = file_mtime($a);
1165 $mb = file_mtime($b);
1166 if (!$ma or !$mb or $ma == $mb) return 0;
1167 return ($ma > $mb) ? -1 : 1;
1172 * Build an array in $this->_fileList of files from $dirname.
1173 * Subdirectories are not traversed.
1175 * (This was a function LoadDir in lib/loadsave.php)
1176 * See also http://www.php.net/manual/en/function.readdir.php
1178 function getFiles($exclude=false,$sortby=false,$limit=false) {
1179 $list = $this->_fileList;
1181 switch (Pagelist::sortby($sortby,'db')) {
1182 case 'pagename ASC': break;
1183 case 'pagename DESC':
1184 $list = array_reverse($list);
1187 usort($list,'sort_file_mtime');
1190 usort($list,'sort_file_mtime');
1191 $list = array_reverse($list);
1196 return array_splice($list,0,$limit);
1200 function _filenameSelector($filename) {
1201 if (! $this->_pattern)
1204 return glob_match ($this->_pattern, $filename, $this->_case);
1208 function fileSet($directory, $filepattern = false) {
1209 $this->_fileList = array();
1210 $this->_pattern = $filepattern;
1211 $this->_case = !isWindows();
1212 $this->_pathsep = '/';
1214 if (empty($directory)) {
1215 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1217 return; // early return
1220 @ $dir_handle = opendir($dir=$directory);
1221 if (empty($dir_handle)) {
1222 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1223 $dir), E_USER_NOTICE);
1224 return; // early return
1227 while ($filename = readdir($dir_handle)) {
1228 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1230 if ($this->_filenameSelector($filename)) {
1231 array_push($this->_fileList, "$filename");
1232 //trigger_error(sprintf(_("found file %s"), $filename),
1233 // E_USER_NOTICE); //debugging
1236 closedir($dir_handle);
1242 // expands a list containing regex's to its matching entries
1243 class ListRegexExpand {
1244 var $match, $list, $index, $case_sensitive;
1245 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1246 $this->match = str_replace('/','\/',$match);
1247 $this->list = &$list;
1248 $this->case_sensitive = $case_sensitive;
1249 //$this->index = false;
1251 function listMatchCallback ($item, $key) {
1252 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1253 unset($this->list[$this->index]);
1254 $this->list[] = $item;
1257 function expandRegex ($index, &$pages) {
1258 $this->index = $index;
1259 array_walk($pages, array($this, 'listMatchCallback'));
1264 // convert fileglob to regex style
1265 function glob_to_pcre ($glob) {
1266 $re = preg_replace('/\./', '\\.', $glob);
1267 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1268 if (!preg_match('/^[\?\*]/',$glob))
1270 if (!preg_match('/[\?\*]$/',$glob))
1275 function glob_match ($glob, $against, $case_sensitive = true) {
1276 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1279 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1280 $list = explode(',',$input);
1281 // expand wildcards from list of $allnames
1282 if (preg_match('/[\?\*]/',$input)) {
1283 // Optimizing loop invariants:
1284 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1285 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1287 if (preg_match('/[\?\*]/',$f)) {
1289 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1290 $expand->expandRegex($i, $allnames);
1297 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1298 function explodePageList($input, $perm=false, $sortby='pagename', $limit=false) {
1299 include_once("lib/PageList.php");
1300 return PageList::explodePageList($input,$perm,$sortby,$limit);
1303 // Class introspections
1306 * Determine whether object is of a specified type.
1307 * In PHP builtin since 4.2.0 as is_a()
1309 * @param $object object An object.
1310 * @param $class string Class name.
1311 * @return bool True iff $object is a $class
1312 * or a sub-type of $class.
1314 function isa ($object, $class) {
1315 $lclass = strtolower($class);
1317 return is_object($object)
1318 && ( strtolower(get_class($object)) == $lclass
1319 || is_subclass_of($object, $lclass) );
1322 /** Determine whether (possible) object has method.
1324 * @param $object mixed Object
1325 * @param $method string Method name
1326 * @return bool True iff $object is an object with has method $method.
1328 function can ($object, $method) {
1329 return is_object($object) && method_exists($object, strtolower($method));
1332 /** Determine whether a function is okay to use.
1334 * Some providers (e.g. Lycos) disable some of PHP functions for
1335 * "security reasons." This makes those functions, of course,
1336 * unusable, despite the fact the function_exists() says they
1339 * This function test to see if a function exists and is not
1340 * disallowed by PHP's disable_functions config setting.
1342 * @param string $function_name Function name
1343 * @return bool True iff function can be used.
1345 function function_usable($function_name) {
1347 if (!is_array($disabled)) {
1348 $disabled = array();
1349 // Use get_cfg_var since ini_get() is one of the disabled functions
1350 // (on Lycos, at least.)
1351 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1352 foreach ($split as $f)
1353 $disabled[strtolower($f)] = true;
1356 return ( function_exists($function_name)
1357 and ! isset($disabled[strtolower($function_name)])
1364 * This is used for generating ETags.
1366 function hash ($x) {
1367 if (is_scalar($x)) {
1370 elseif (is_array($x)) {
1372 return md5(serialize($x));
1374 elseif (is_object($x)) {
1377 trigger_error("Can't hash $x", E_USER_ERROR);
1382 * Seed the random number generator.
1384 * better_srand() ensures the randomizer is seeded only once.
1386 * How random do you want it? See:
1387 * http://www.php.net/manual/en/function.srand.php
1388 * http://www.php.net/manual/en/function.mt-srand.php
1390 function better_srand($seed = '') {
1391 static $wascalled = FALSE;
1393 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1396 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1401 * Recursively count all non-empty elements
1402 * in array of any dimension or mixed - i.e.
1403 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1404 * See http://www.php.net/manual/en/function.count.php
1406 function count_all($arg) {
1407 // skip if argument is empty
1409 //print_r($arg); //debugging
1411 // not an array, return 1 (base case)
1414 // else call recursively for all elements $arg
1415 foreach($arg as $key => $val)
1416 $count += count_all($val);
1421 function isSubPage($pagename) {
1422 return (strstr($pagename, SUBPAGE_SEPARATOR));
1425 function subPageSlice($pagename, $pos) {
1426 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1427 $pages = array_slice($pages,$pos,1);
1434 * Class for "popping up" and alert box. (Except that right now, it doesn't
1438 * This is a hackish and needs to be refactored. However it would be nice to
1439 * unify all the different methods we use for showing Alerts and Dialogs.
1440 * (E.g. "Page deleted", login form, ...)
1445 * @param object $request
1446 * @param mixed $head Header ("title") for alert box.
1447 * @param mixed $body The text in the alert box.
1448 * @param hash $buttons An array mapping button labels to URLs.
1449 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1451 function Alert($head, $body, $buttons=false) {
1452 if ($buttons === false)
1455 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1456 $this->_buttons = $buttons;
1460 * Show the alert box.
1462 function show(&$request) {
1465 $tokens = $this->_tokens;
1466 $tokens['BUTTONS'] = $this->_getButtons();
1468 $request->discardOutput();
1469 $tmpl = new Template('dialog', $request, $tokens);
1475 function _getButtons() {
1478 $buttons = $this->_buttons;
1480 $buttons = array(_("Okay") => $request->getURLtoSelf());
1483 foreach ($buttons as $label => $url)
1484 print "$label $url\n";
1485 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1486 return new XmlContent($out);
1491 // 1.3.9-p1 => 1030.091
1492 // 1.3.10pre => 1030.099
1493 function phpwiki_version() {
1494 static $PHPWIKI_VERSION;
1495 if (!isset($PHPWIKI_VERSION)) {
1496 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1497 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1498 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1499 if (substr(PHPWIKI_VERSION,-3,3) == 'pre')
1500 $PHPWIKI_VERSION -= 0.001;
1502 return $PHPWIKI_VERSION;
1505 function isWikiWord($word) {
1506 global $WikiNameRegexp;
1507 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1508 return preg_match("/^$WikiNameRegexp\$/",$word);
1511 // needed to store serialized objects-values only (perm, pref)
1512 function obj2hash ($obj, $exclude = false, $fields = false) {
1514 if (! $fields ) $fields = get_object_vars($obj);
1515 foreach ($fields as $key => $val) {
1516 if (is_array($exclude)) {
1517 if (in_array($key,$exclude)) continue;
1525 * isUtf8String($string) - cheap utf-8 detection
1527 * segfaults for strings longer than 10kb!
1528 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1529 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1531 function isUtf8String( $s ) {
1532 $ptrASCII = '[\x00-\x7F]';
1533 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1534 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1535 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1536 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1537 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1538 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1542 * Check for UTF-8 URLs; Internet Explorer produces these if you
1543 * type non-ASCII chars in the URL bar or follow unescaped links.
1544 * Requires urldecoded pagename.
1545 * Fixes sf.net bug #953949
1547 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1549 function fixTitleEncoding( $s ) {
1554 if (empty($s)) return $s;
1556 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1558 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1559 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1561 $isutf = ($ishigh ? isUtf8String($s) : true);
1562 $locharset = strtolower($charset);
1564 if( $locharset != "utf-8" and $ishigh and $isutf )
1565 // if charset == 'iso-8859-1' then simply use utf8_decode()
1566 if ($locharset == 'iso-8859-1')
1567 return utf8_decode( $s );
1569 // TODO: check for iconv support
1570 return iconv( "UTF-8", $charset, $s );
1572 if ($locharset == "utf-8" and $ishigh and !$isutf )
1573 return utf8_encode( $s );
1575 // Other languages can safely leave this function, or replace
1576 // it with one to detect and convert another legacy encoding.
1581 * MySQL fulltext index doesn't grok utf-8, so we
1582 * need to fold cases and convert to hex.
1583 * src: languages/Language.php:stripForSearch() from mediawiki
1586 function stripForSearch( $string ) {
1587 global $wikiLowerChars;
1588 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1589 return preg_replace(
1590 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1591 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1597 * Workaround for allow_url_fopen, to get the content of an external URI.
1598 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1599 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1601 function url_get_contents( $uri ) {
1602 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1603 return @file_get_contents($uri);
1605 require_once("lib/HttpClient.php");
1606 $bits = parse_url($uri);
1607 $host = $bits['host'];
1608 $port = isset($bits['port']) ? $bits['port'] : 80;
1609 $path = isset($bits['path']) ? $bits['path'] : '/';
1610 if (isset($bits['query'])) {
1611 $path .= '?'.$bits['query'];
1613 $client = new HttpClient($host, $port);
1614 $client->use_gzip = false;
1615 if (!$client->get($path)) {
1618 return $client->getContent();
1624 // $Log: not supported by cvs2svn $
1625 // Revision 1.195 2004/06/29 08:52:22 rurban
1626 // Use ...version() $need_content argument in WikiDB also:
1627 // To reduce the memory footprint for larger sets of pagelists,
1628 // we don't cache the content (only true or false) and
1629 // we purge the pagedata (_cached_html) also.
1630 // _cached_html is only cached for the current pagename.
1631 // => Vastly improved page existance check, ACL check, ...
1633 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1635 // Revision 1.194 2004/06/29 06:48:04 rurban
1636 // Improve LDAP auth and GROUP_LDAP membership:
1637 // no error message on false password,
1638 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
1639 // fixed two group queries (this -> user)
1640 // stdlib: ConvertOldMarkup still flawed
1642 // Revision 1.193 2004/06/28 13:27:03 rurban
1643 // CreateToc disabled for old markup and Apache2 only
1645 // Revision 1.192 2004/06/28 12:47:43 rurban
1646 // skip if non-DEBUG and old markup with CreateToc
1648 // Revision 1.191 2004/06/25 14:31:56 rurban
1649 // avoid debug_skip warning
1651 // Revision 1.190 2004/06/25 14:29:20 rurban
1652 // WikiGroup refactoring:
1653 // global group attached to user, code for not_current user.
1654 // improved helpers for special groups (avoid double invocations)
1655 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1656 // fixed a XHTML validation error on userprefs.tmpl
1658 // Revision 1.189 2004/06/20 09:45:35 rurban
1659 // php5 isa fix (wrong strtolower)
1661 // Revision 1.188 2004/06/16 10:38:58 rurban
1662 // Disallow refernces in calls if the declaration is a reference
1663 // ("allow_call_time_pass_reference clean").
1664 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1665 // but several external libraries may not.
1666 // In detail these libs look to be affected (not tested):
1670 // Revision 1.187 2004/06/14 11:31:37 rurban
1671 // renamed global $Theme to $WikiTheme (gforge nameclash)
1672 // inherit PageList default options from PageList
1673 // default sortby=pagename
1674 // use options in PageList_Selectable (limit, sortby, ...)
1675 // added action revert, with button at action=diff
1676 // added option regex to WikiAdminSearchReplace
1678 // Revision 1.186 2004/06/13 13:54:25 rurban
1679 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
1680 // FoafViewer: Check against external requirements, instead of fatal.
1681 // Change output for xhtmldumps: using file:// urls to the local fs.
1682 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
1683 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
1685 // Revision 1.185 2004/06/11 09:07:30 rurban
1686 // support theme-specific LinkIconAttr: front or after or none
1688 // Revision 1.184 2004/06/04 20:32:53 rurban
1689 // Several locale related improvements suggested by Pierrick Meignen
1690 // LDAP fix by John Cole
1691 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1693 // Revision 1.183 2004/06/01 10:22:56 rurban
1694 // added url_get_contents() used in XmlParser and elsewhere
1696 // Revision 1.182 2004/05/25 12:40:48 rurban
1697 // trim the pagename
1699 // Revision 1.181 2004/05/25 10:18:44 rurban
1700 // Check for UTF-8 URLs; Internet Explorer produces these if you
1701 // type non-ASCII chars in the URL bar or follow unescaped links.
1702 // Fixes sf.net bug #953949
1703 // src: languages/Language.php:checkTitleEncoding() from mediawiki
1705 // Revision 1.180 2004/05/18 16:23:39 rurban
1706 // rename split_pagename to SplitPagename
1708 // Revision 1.179 2004/05/18 16:18:37 rurban
1709 // AutoSplit at subpage seperators
1710 // RssFeed stability fix for empty feeds or broken connections
1712 // Revision 1.178 2004/05/12 10:49:55 rurban
1713 // require_once fix for those libs which are loaded before FileFinder and
1714 // its automatic include_path fix, and where require_once doesn't grok
1715 // dirname(__FILE__) != './lib'
1716 // upgrade fix with PearDB
1717 // navbar.tmpl: remove spaces for IE button alignment
1719 // Revision 1.177 2004/05/08 14:06:12 rurban
1720 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
1721 // minor stability and portability fixes
1723 // Revision 1.176 2004/05/08 11:25:15 rurban
1726 // Revision 1.175 2004/05/06 17:30:38 rurban
1727 // CategoryGroup: oops, dos2unix eol
1728 // improved phpwiki_version:
1729 // pre -= .0001 (1.3.10pre: 1030.099)
1730 // -p1 += .001 (1.3.9-p1: 1030.091)
1731 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1732 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1733 // backend->backendType(), backend->database(),
1734 // backend->listOfFields(),
1735 // backend->listOfTables(),
1737 // Revision 1.174 2004/05/06 12:02:05 rurban
1738 // fix sf.net bug#949002: [ Link | ] assertion
1740 // Revision 1.173 2004/05/03 15:00:31 rurban
1741 // added more database upgrading: session.sess_ip, page.id autp_increment
1743 // Revision 1.172 2004/04/26 20:44:34 rurban
1744 // locking table specific for better databases
1746 // Revision 1.171 2004/04/19 23:13:03 zorloc
1747 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
1749 // Revision 1.170 2004/04/19 18:27:45 rurban
1750 // Prevent from some PHP5 warnings (ref args, no :: object init)
1751 // php5 runs now through, just one wrong XmlElement object init missing
1752 // Removed unneccesary UpgradeUser lines
1753 // Changed WikiLink to omit version if current (RecentChanges)
1755 // Revision 1.169 2004/04/15 21:29:48 rurban
1756 // allow [0] with new markup: link to page "0"
1758 // Revision 1.168 2004/04/10 02:30:49 rurban
1759 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
1760 // Fixed "cannot setlocale..." (sf.net problem)
1762 // Revision 1.167 2004/04/02 15:06:55 rurban
1763 // fixed a nasty ADODB_mysql session update bug
1764 // improved UserPreferences layout (tabled hints)
1765 // fixed UserPreferences auth handling
1766 // improved auth stability
1767 // improved old cookie handling: fixed deletion of old cookies with paths
1769 // Revision 1.166 2004/04/01 15:57:10 rurban
1770 // simplified Sidebar theme: table, not absolute css positioning
1771 // added the new box methods.
1772 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
1774 // Revision 1.165 2004/03/24 19:39:03 rurban
1775 // php5 workaround code (plus some interim debugging code in XmlElement)
1776 // php5 doesn't work yet with the current XmlElement class constructors,
1777 // WikiUserNew does work better than php4.
1778 // rewrote WikiUserNew user upgrading to ease php5 update
1779 // fixed pref handling in WikiUserNew
1780 // added Email Notification
1781 // added simple Email verification
1782 // removed emailVerify userpref subclass: just a email property
1783 // changed pref binary storage layout: numarray => hash of non default values
1784 // print optimize message only if really done.
1785 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1786 // prefs should be stored in db or homepage, besides the current session.
1788 // Revision 1.164 2004/03/18 21:41:09 rurban
1789 // fixed sqlite support
1790 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
1792 // Revision 1.163 2004/03/17 18:41:49 rurban
1793 // just reformatting
1795 // Revision 1.162 2004/03/16 15:43:08 rurban
1796 // make fileSet sortable to please PageList
1798 // Revision 1.161 2004/03/12 15:48:07 rurban
1799 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1800 // simplified lib/stdlib.php:explodePageList
1802 // Revision 1.160 2004/02/28 21:14:08 rurban
1803 // generally more PHPDOC docs
1804 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
1805 // fxied WikiUserNew pref handling: empty theme not stored, save only
1806 // changed prefs, sql prefs improved, fixed password update,
1807 // removed REPLACE sql (dangerous)
1808 // moved gettext init after the locale was guessed
1809 // + some minor changes
1811 // Revision 1.158 2004/02/19 21:54:17 rurban
1812 // moved initerwiki code to PageType.php
1813 // re-enabled and fixed InlineImages support, now also for InterWiki Urls
1814 // * [File:my_image.gif] inlines the image,
1815 // * File:my_image.gif shows a plain inter-wiki link,
1816 // * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
1817 // * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
1819 // Revision 1.157 2004/02/09 03:58:12 rurban
1820 // for now default DB_SESSION to false
1822 // * not existing perms will now query the parent, and not
1823 // return the default perm
1824 // * added pagePermissions func which returns the object per page
1825 // * added getAccessDescription
1827 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1828 // * force init of authdbh in the 2 db classes
1830 // * fixed session handling (not triple auth request anymore)
1831 // * don't store cookie prefs with sessions
1832 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1834 // Revision 1.156 2004/01/26 09:17:49 rurban
1835 // * changed stored pref representation as before.
1836 // the array of objects is 1) bigger and 2)
1837 // less portable. If we would import packed pref
1838 // objects and the object definition was changed, PHP would fail.
1839 // This doesn't happen with an simple array of non-default values.
1840 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1841 // understands the interim format of array of objects also.
1842 // * simplified $prefs->get() and fixed $prefs->set()
1843 // * added $user->_userid and class '_WikiUser' portability functions
1844 // * fixed $user object ->_level upgrading, mostly using sessions.
1845 // this fixes yesterdays problems with loosing authorization level.
1846 // * fixed WikiUserNew::checkPass to return the _level
1847 // * fixed WikiUserNew::isSignedIn
1848 // * added explodePageList to class PageList, support sortby arg
1849 // * fixed UserPreferences for WikiUserNew
1850 // * fixed WikiPlugin for empty defaults array
1851 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1852 // removed sort arg, support sortby arg
1854 // Revision 1.155 2004/01/25 10:52:22 rurban
1855 // added sortby support to explodePageList() and UnfoldSubpages
1856 // fixes [ 758044 ] Plugin UnfoldSubpages does not sort (includes fix)
1858 // Revision 1.154 2004/01/25 03:49:03 rurban
1859 // added isWikiWord() to avoid redundancy
1860 // added check_php_version() to check for older php versions.
1861 // e.g. object::method calls, ...
1863 // Revision 1.153 2003/11/30 18:43:18 carstenklapp
1864 // Fixed careless mistakes in my last optimization commit.
1866 // Revision 1.152 2003/11/30 18:20:34 carstenklapp
1867 // Minor code optimization: reduce invariant loops
1869 // Revision 1.151 2003/11/29 19:30:01 carstenklapp
1870 // New function ByteFormatter.
1872 // Revision 1.150 2003/09/13 22:43:00 carstenklapp
1873 // New preference to hide LinkIcons.
1875 // Revision 1.149 2003/03/26 19:37:08 dairiki
1876 // Fix "object to string conversion" bug with external image links.
1878 // Revision 1.148 2003/03/25 21:03:02 dairiki
1879 // Cleanup debugging output.
1881 // Revision 1.147 2003/03/13 20:17:05 dairiki
1882 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1884 // Revision 1.146 2003/03/07 02:46:24 dairiki
1885 // function_usable(): New function.
1887 // Revision 1.145 2003/03/04 01:55:05 dairiki
1888 // Fix to ensure absolute URL for logo in RSS recent changes.
1890 // Revision 1.144 2003/02/26 00:39:30 dairiki
1891 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1892 // being displayed at incorrect times.
1894 // Revision 1.143 2003/02/26 00:10:26 dairiki
1895 // More/better/different checks for bad page names.
1897 // Revision 1.142 2003/02/25 22:19:46 dairiki
1898 // Add some sanity checking for pagenames.
1900 // Revision 1.141 2003/02/22 20:49:55 dairiki
1901 // Fixes for "Call-time pass by reference has been deprecated" errors.
1903 // Revision 1.140 2003/02/21 23:33:29 dairiki
1904 // Set alt="" on the link icon image tags.
1905 // (See SF bug #675141.)
1907 // Revision 1.139 2003/02/21 22:16:27 dairiki
1908 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1909 // These have been obsolete for quite awhile (I hope).
1911 // Revision 1.138 2003/02/21 04:12:36 dairiki
1912 // WikiPageName: fixes for new cached links.
1914 // Alert: new class for displaying alerts.
1916 // ExtractWikiPageLinks and friends are now gone.
1918 // LinkBracketLink moved to InlineParser.php
1920 // Revision 1.137 2003/02/18 23:13:40 dairiki
1921 // Wups again. Typo fix.
1923 // Revision 1.136 2003/02/18 21:52:07 dairiki
1924 // Fix so that one can still link to wiki pages with # in their names.
1925 // (This was made difficult by the introduction of named tags, since
1926 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1928 // Now the ~ escape for page names should work: [Page ~#1].
1930 // Revision 1.135 2003/02/18 19:17:04 dairiki
1932 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1933 // Cleanup up subpage splitting code.
1935 // Revision 1.134 2003/02/16 19:44:20 dairiki
1936 // New function hash(). This is a helper, primarily for generating
1939 // Revision 1.133 2003/02/16 04:50:09 dairiki
1941 // Rfc1123DateTime(), ParseRfc1123DateTime()
1942 // for converting unix timestamps to and from strings.
1944 // These functions produce and grok the time strings
1945 // in the format specified by RFC 2616 for use in HTTP headers
1946 // (like Last-Modified).
1948 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1949 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1950 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1953 // (c-file-style: "gnu")
1957 // c-basic-offset: 4
1958 // c-hanging-comment-ender-p: nil
1959 // indent-tabs-mode: nil