1 <?php //rcs_id('$Id: stdlib.php,v 1.198 2004-07-02 10:30:36 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 !preg_match('/[<>"]/', $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 = (int) $width; // px or % or other suffix
331 //$height = (int) $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);
340 // Older php versions crash here with certain png's:
341 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
342 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
343 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
344 if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
345 ; // it's safe to assume that this will fail.
346 elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
349 if (($width < 3 and $height < 10)
350 or ($height < 3 and $width < 20)
351 or ($height < 7 and $width < 7))
353 trigger_error(_("Invalid image size"), E_USER_NOTICE);
359 $link->setAttr('class', 'inlineimage');
366 var $items = array();
368 // var in php5.0.0.rc1 deprecated
370 function push($item) {
371 $this->items[$this->size] = $item;
377 if ($this->size == 0) {
378 return false; // stack is empty
381 return $this->items[$this->size];
390 return $this->items[$this->size - 1];
396 // end class definition
398 function SplitQueryArgs ($query_args = '')
400 $split_args = split('&', $query_args);
402 while (list($key, $val) = each($split_args))
403 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
404 $args[$m[1]] = $m[2];
408 function LinkPhpwikiURL($url, $text = '', $basepage) {
411 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
412 return HTML::strong(array('class' => 'rawurl'),
413 HTML::u(array('class' => 'baduri'),
414 _("BAD phpwiki: URL")));
418 $pagename = urldecode($m[1]);
421 if (empty($pagename) &&
422 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
423 // Convert old style links (to not break diff links in
425 $pagename = urldecode($m[2]);
426 $args = array("action" => $m[1]);
429 $args = SplitQueryArgs($qargs);
432 if (empty($pagename))
433 $pagename = $GLOBALS['request']->getArg('pagename');
435 if (isset($args['action']) && $args['action'] == 'browse')
436 unset($args['action']);
439 if (empty($args['action']))
441 else if (is_safe_action($args['action']))
442 $class = 'wikiaction';
444 if (empty($args['action']) || is_safe_action($args['action']))
445 $class = 'wikiaction';
447 // Don't allow administrative links on unlocked pages.
448 $dbi = $GLOBALS['request']->getDbh();
449 $page = $dbi->getPage($basepage);
450 if (!$page->get('locked'))
451 return HTML::span(array('class' => 'wikiunsafe'),
452 HTML::u(_("Lock page to enable link")));
453 $class = 'wikiadmin';
457 $text = HTML::span(array('class' => 'rawurl'), $url);
459 $wikipage = new WikiPageName($pagename);
460 if (!$wikipage->isValid()) {
462 return $WikiTheme->linkBadWikiWord($wikipage, $url);
465 return HTML::a(array('href' => WikiURL($pagename, $args),
471 * A class to assist in parsing wiki pagenames.
473 * Now with subpages and anchors, parsing and passing around
474 * pagenames is more complicated. This should help.
478 /** Short name for page.
480 * This is the value of $name passed to the constructor.
481 * (For use, e.g. as a default label for links to the page.)
485 /** The full page name.
487 * This is the full name of the page (without anchor).
493 * This is the referenced anchor within the page, or the empty string.
499 * @param mixed $name Page name.
500 * WikiDB_Page, WikiDB_PageRevision, or string.
501 * This can be a relative subpage name (like '/SubPage'),
502 * or can be the empty string to refer to the $basename.
504 * @param string $anchor For links to anchors in page.
506 * @param mixed $basename Page name from which to interpret
507 * relative or other non-fully-specified page names.
509 function WikiPageName($name, $basename=false, $anchor=false) {
510 if (is_string($name)) {
511 $this->shortName = $name;
513 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
515 $name = $this->_pagename($basename) . $name;
517 $name = $this->_normalize_bad_pagename($name);
521 $name = $this->_pagename($name);
522 $this->shortName = $name;
525 $this->name = $this->_check($name);
526 $this->anchor = (string)$anchor;
529 function getParent() {
531 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
533 return substr($name, 0, -strlen($tail));
536 function isValid($strict = false) {
538 return !isset($this->_errors);
539 return (is_string($this->name) and $this->name != '');
542 function getWarnings() {
544 if (isset($this->_warnings))
545 $warnings = array_merge($warnings, $this->_warnings);
546 if (isset($this->_errors))
547 $warnings = array_merge($warnings, $this->_errors);
551 return sprintf(_("'%s': Bad page name: %s"),
552 $this->shortName, join(', ', $warnings));
555 function _pagename($page) {
556 if (isa($page, 'WikiDB_Page'))
557 return $page->getName();
558 elseif (isa($page, 'WikiDB_PageRevision'))
559 return $page->getPageName();
560 elseif (isa($page, 'WikiPageName'))
562 if (!is_string($page)) {
563 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
564 $page, gettype($page), get_class($page)),
567 //assert(is_string($page));
571 function _normalize_bad_pagename($name) {
572 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
574 // Punt... You really shouldn't get here.
577 return $request->getArg('pagename');
579 assert($name[0] == SUBPAGE_SEPARATOR);
580 return substr($name, 1);
584 function _check($pagename) {
585 // Compress internal white-space to single space character.
586 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
587 if ($pagename != $orig)
588 $this->_warnings[] = _("White space converted to single space");
590 // Delete any control characters.
591 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
592 if ($pagename != $orig)
593 $this->_errors[] = _("Control characters not allowed");
595 // Strip leading and trailing white-space.
596 $pagename = trim($pagename);
599 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
600 $pagename = substr($pagename, 1);
601 if ($pagename != $orig)
602 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
604 if (preg_match('/[:;]/', $pagename))
605 $this->_warnings[] = _("';' and ':' in pagenames are deprecated");
607 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
608 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
609 $this->_errors[] = _("too long");
613 if ($pagename == '.' or $pagename == '..') {
614 $this->_errors[] = sprintf(_("illegal pagename"), $pagename);
623 * Convert old page markup to new-style markup.
625 * @param string $text Old-style wiki markup.
627 * @param string $markup_type
629 * <dt><code>"block"</code> <dd>Convert all markup.
630 * <dt><code>"inline"</code> <dd>Convert only inline markup.
631 * <dt><code>"links"</code> <dd>Convert only link markup.
634 * @return string New-style wiki markup.
636 * @bugs Footnotes don't work quite as before (esp if there are
637 * multiple references to the same footnote. But close enough,
638 * probably for now....
639 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
640 * AnciennesR%E8glesDeFormatage. ( at the 2nd attempt to do the anchored block regex )
641 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
642 * also known to crash, even with Apache1.
644 function ConvertOldMarkup ($text, $markup_type = "block") {
650 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
651 // AnciennesR%E8glesDeFormatage crashes.
652 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
653 // also known to crash, even with Apache1.
655 // I suspect this only to crash with Apache2 and IIS.
656 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
657 and preg_match("/plugin CreateToc/", $text))
659 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
660 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
661 ._("Skipped."), E_USER_WARNING);
663 //if (!DEBUG) return $text;
668 /*****************************************************************
669 * Conversions for inline markup:
676 // escape escaped brackets
680 // change ! escapes to ~'s.
681 global $WikiNameRegexp, $request;
682 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
683 $map = getInterwikiMap();
684 if ($map_regex = $map->getRegexp())
685 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
686 $bang_esc[] = $WikiNameRegexp;
687 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
690 $subs["links"] = array($orig, $repl);
693 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
696 // Convert footnote references.
697 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
698 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
700 // Convert old style emphases to HTML style emphasis.
701 $orig[] = '/__(.*?)__/';
702 $repl[] = '<strong>\\1</strong>';
703 $orig[] = "/''(.*?)''/";
704 $repl[] = '<em>\\1</em>';
706 // Escape nestled markup.
707 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
710 // in old markup headings only allowed at beginning of line
714 $subs["inline"] = array($orig, $repl);
716 /*****************************************************************
717 * Patterns which match block markup constructs which take
718 * special handling...
722 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
724 $blockpats[] = '\|(?:.*\n\|)*';
727 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
729 // Footnote definitions
730 $blockpats[] = '\[\s*(\d+)\s*\]';
734 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
738 $blockpats[] = '!{1,3}[^!]';
740 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
741 . join("|", $blockpats)
746 if ($markup_type != "block") {
747 list ($orig, $repl) = $subs[$markup_type];
748 return preg_replace($orig, $repl, $text);
751 list ($orig, $repl) = $subs['inline'];
754 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
755 // AnciennesR%E8glesDeFormatage and more
756 while (preg_match($block_re, $text, $m)) {
757 $text = substr($text, strlen($m[0]));
758 list (,$leading_text, $block) = $m;
761 if (strchr(" \t", $block[0])) {
764 $suffix = "\n</pre>\n";
766 elseif ($block[0] == '|') {
768 $prefix = "<?plugin OldStyleTable\n";
771 elseif (strchr("#*;", $block[0])) {
772 // Old-style list item
773 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
774 list (,$ind,$bullet) = $m;
775 $block = substr($block, strlen($m[0]));
777 $indent = str_repeat(' ', strlen($ind));
778 if ($bullet[0] == ';') {
779 //$term = ltrim(substr($bullet, 1));
780 //return $indent . $term . "\n" . $indent . ' ';
781 $prefix = $ind . $bullet;
784 $prefix = $indent . $bullet . ' ';
786 elseif ($block[0] == '[') {
787 // Footnote definition
788 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
790 $block = substr($block, strlen($m[0]));
791 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
793 elseif ($block[0] == '<') {
795 // HACK: no inline markup...
799 elseif ($block[0] == '!') {
801 preg_match('/^!{1,3}/', $block, $m);
803 $block = substr($block, strlen($m[0]));
809 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
810 if ($block) $block = preg_replace($orig, $repl, $block);
811 $out .= $leading_text;
816 return $out . preg_replace($orig, $repl, $text);
822 * Expand tabs in string.
824 * Converts all tabs to (the appropriate number of) spaces.
827 * @param integer $tab_width
830 function expand_tabs($str, $tab_width = 8) {
831 $split = split("\t", $str);
832 $tail = array_pop($split);
834 foreach ($split as $hunk) {
836 $pos = strlen(strrchr($expanded, "\n")) - 1;
837 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
839 return substr($expanded, 1) . $tail;
843 * Split WikiWords in page names.
845 * It has been deemed useful to split WikiWords (into "Wiki Words") in
846 * places like page titles. This is rumored to help search engines
849 * @param $page string The page name.
851 * @return string The split name.
853 function SplitPagename ($page) {
855 if (preg_match("/\s/", $page))
856 return $page; // Already split --- don't split any more.
858 // This algorithm is specialized for several languages.
859 // (Thanks to Pierrick MEIGNEN)
860 // Improvements for other languages welcome.
863 // This mess splits between a lower-case letter followed by
864 // either an upper-case or a numeral; except that it wont
865 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
866 switch ($GLOBALS['LANG']) {
871 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
874 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
877 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
878 // This the single-letter words 'I' and 'A' from any following
879 // capitalized words.
880 switch ($GLOBALS['LANG']) {
882 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
885 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
888 // Split numerals from following letters.
889 $RE[] = '/(\d)([[:alpha:]])/';
890 // Split at subpage seperators. TBD in Theme.php
891 $RE[] = "/([^${sep}]+)(${sep})/";
893 foreach ($RE as $key)
894 $RE[$key] = pcre_fix_posix_classes($key);
897 foreach ($RE as $regexp) {
898 $page = preg_replace($regexp, '\\1 \\2', $page);
903 function NoSuchRevision (&$request, $page, $version) {
904 $html = HTML(HTML::h2(_("Revision Not Found")),
905 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
906 $version, WikiLink($page, 'auto'))));
907 include_once('lib/Template.php');
908 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
914 * Get time offset for local time zone.
916 * @param $time time_t Get offset for this time. Default: now.
917 * @param $no_colon boolean Don't put colon between hours and minutes.
918 * @return string Offset as a string in the format +HH:MM.
920 function TimezoneOffset ($time = false, $no_colon = false) {
923 $secs = date('Z', $time);
932 $colon = $no_colon ? '' : ':';
933 $mins = intval(($secs + 30) / 60);
934 return sprintf("%s%02d%s%02d",
935 $sign, $mins / 60, $colon, $mins % 60);
940 * Format time in ISO-8601 format.
942 * @param $time time_t Time. Default: now.
943 * @return string Date and time in ISO-8601 format.
945 function Iso8601DateTime ($time = false) {
948 $tzoff = TimezoneOffset($time);
949 $date = date('Y-m-d', $time);
950 $time = date('H:i:s', $time);
951 return $date . 'T' . $time . $tzoff;
955 * Format time in RFC-2822 format.
957 * @param $time time_t Time. Default: now.
958 * @return string Date and time in RFC-2822 format.
960 function Rfc2822DateTime ($time = false) {
963 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
967 * Format time in RFC-1123 format.
969 * @param $time time_t Time. Default: now.
970 * @return string Date and time in RFC-1123 format.
972 function Rfc1123DateTime ($time = false) {
975 return gmdate('D, d M Y H:i:s \G\M\T', $time);
978 /** Parse date in RFC-1123 format.
980 * According to RFC 1123 we must accept dates in the following
983 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
984 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
985 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
987 * (Though we're only allowed to generate dates in the first format.)
989 function ParseRfc1123DateTime ($timestr) {
990 $timestr = trim($timestr);
991 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
992 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
994 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
996 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
997 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
999 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1000 if ($year < 70) $year += 2000;
1001 elseif ($year < 100) $year += 1900;
1003 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1004 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1006 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1013 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1015 return false; // failed
1020 * Format time to standard 'ctime' format.
1022 * @param $time time_t Time. Default: now.
1023 * @return string Date and time.
1025 function CTime ($time = false)
1027 if ($time === false)
1029 return date("D M j H:i:s Y", $time);
1034 * Format number as kilobytes or bytes.
1035 * Short format is used for PageList
1036 * Long format is used in PageInfo
1038 * @param $bytes int. Default: 0.
1039 * @param $longformat bool. Default: false.
1040 * @return class FormattedText (XmlElement.php).
1042 function ByteFormatter ($bytes = 0, $longformat = false) {
1045 if ($bytes < 1024) {
1047 $size = fmt("%s b", $bytes);
1049 $size = fmt("%s bytes", $bytes);
1052 $kb = round($bytes / 1024, 1);
1054 $size = fmt("%s k", $kb);
1056 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1062 * Internationalized printf.
1064 * This is essentially the same as PHP's built-in printf
1065 * with the following exceptions:
1067 * <li> It passes the format string through gettext().
1068 * <li> It supports the argument reordering extensions.
1075 * __printf("Differences between versions %s and %s of %s",
1076 * $new_link, $old_link, $page_link);
1079 * Then in locale/po/de.po, one can reorder the printf arguments:
1082 * msgid "Differences between %s and %s of %s."
1083 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1086 * (Note that while PHP tries to expand $vars within double-quotes,
1087 * the values in msgstr undergo no such expansion, so the '$'s
1090 * One shouldn't use reordered arguments in the default format string.
1091 * Backslashes in the default string would be necessary to escape the
1092 * '$'s, and they'll cause all kinds of trouble....
1094 function __printf ($fmt) {
1095 $args = func_get_args();
1097 echo __vsprintf($fmt, $args);
1101 * Internationalized sprintf.
1103 * This is essentially the same as PHP's built-in printf with the
1104 * following exceptions:
1107 * <li> It passes the format string through gettext().
1108 * <li> It supports the argument reordering extensions.
1113 function __sprintf ($fmt) {
1114 $args = func_get_args();
1116 return __vsprintf($fmt, $args);
1120 * Internationalized vsprintf.
1122 * This is essentially the same as PHP's built-in printf with the
1123 * following exceptions:
1126 * <li> It passes the format string through gettext().
1127 * <li> It supports the argument reordering extensions.
1132 function __vsprintf ($fmt, $args) {
1133 $fmt = gettext($fmt);
1134 // PHP's sprintf doesn't support variable with specifiers,
1135 // like sprintf("%*s", 10, "x"); --- so we won't either.
1137 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1138 // Format string has '%2$s' style argument reordering.
1139 // PHP doesn't support this.
1140 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1141 // literal variable name substitution only to keep locale
1142 // strings uncluttered
1143 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1144 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1146 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1149 // Reorder arguments appropriately.
1150 foreach($m[1] as $argnum) {
1151 if ($argnum < 1 || $argnum > count($args))
1152 trigger_error(sprintf(_("%s: argument index out of range"),
1153 $argnum), E_USER_WARNING);
1154 $newargs[] = $args[$argnum - 1];
1159 // Not all PHP's have vsprintf, so...
1160 array_unshift($args, $fmt);
1161 return call_user_func_array('sprintf', $args);
1164 function file_mtime ($filename) {
1165 if ($stat = @stat($filename))
1171 function sort_file_mtime ($a, $b) {
1172 $ma = file_mtime($a);
1173 $mb = file_mtime($b);
1174 if (!$ma or !$mb or $ma == $mb) return 0;
1175 return ($ma > $mb) ? -1 : 1;
1180 * Build an array in $this->_fileList of files from $dirname.
1181 * Subdirectories are not traversed.
1183 * (This was a function LoadDir in lib/loadsave.php)
1184 * See also http://www.php.net/manual/en/function.readdir.php
1186 function getFiles($exclude=false,$sortby=false,$limit=false) {
1187 $list = $this->_fileList;
1189 switch (Pagelist::sortby($sortby,'db')) {
1190 case 'pagename ASC': break;
1191 case 'pagename DESC':
1192 $list = array_reverse($list);
1195 usort($list,'sort_file_mtime');
1198 usort($list,'sort_file_mtime');
1199 $list = array_reverse($list);
1204 return array_splice($list,0,$limit);
1208 function _filenameSelector($filename) {
1209 if (! $this->_pattern)
1212 return glob_match ($this->_pattern, $filename, $this->_case);
1216 function fileSet($directory, $filepattern = false) {
1217 $this->_fileList = array();
1218 $this->_pattern = $filepattern;
1219 $this->_case = !isWindows();
1220 $this->_pathsep = '/';
1222 if (empty($directory)) {
1223 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1225 return; // early return
1228 @ $dir_handle = opendir($dir=$directory);
1229 if (empty($dir_handle)) {
1230 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1231 $dir), E_USER_NOTICE);
1232 return; // early return
1235 while ($filename = readdir($dir_handle)) {
1236 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1238 if ($this->_filenameSelector($filename)) {
1239 array_push($this->_fileList, "$filename");
1240 //trigger_error(sprintf(_("found file %s"), $filename),
1241 // E_USER_NOTICE); //debugging
1244 closedir($dir_handle);
1250 // expands a list containing regex's to its matching entries
1251 class ListRegexExpand {
1252 var $match, $list, $index, $case_sensitive;
1253 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1254 $this->match = str_replace('/','\/',$match);
1255 $this->list = &$list;
1256 $this->case_sensitive = $case_sensitive;
1257 //$this->index = false;
1259 function listMatchCallback ($item, $key) {
1260 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1261 unset($this->list[$this->index]);
1262 $this->list[] = $item;
1265 function expandRegex ($index, &$pages) {
1266 $this->index = $index;
1267 array_walk($pages, array($this, 'listMatchCallback'));
1272 // convert fileglob to regex style
1273 function glob_to_pcre ($glob) {
1274 $re = preg_replace('/\./', '\\.', $glob);
1275 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1276 if (!preg_match('/^[\?\*]/',$glob))
1278 if (!preg_match('/[\?\*]$/',$glob))
1283 function glob_match ($glob, $against, $case_sensitive = true) {
1284 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1287 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1288 $list = explode(',',$input);
1289 // expand wildcards from list of $allnames
1290 if (preg_match('/[\?\*]/',$input)) {
1291 // Optimizing loop invariants:
1292 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1293 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1295 if (preg_match('/[\?\*]/',$f)) {
1297 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1298 $expand->expandRegex($i, $allnames);
1305 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1306 function explodePageList($input, $perm=false, $sortby='pagename', $limit=false) {
1307 include_once("lib/PageList.php");
1308 return PageList::explodePageList($input,$perm,$sortby,$limit);
1311 // Class introspections
1314 * Determine whether object is of a specified type.
1315 * In PHP builtin since 4.2.0 as is_a()
1317 * @param $object object An object.
1318 * @param $class string Class name.
1319 * @return bool True iff $object is a $class
1320 * or a sub-type of $class.
1322 function isa ($object, $class) {
1323 $lclass = strtolower($class);
1325 return is_object($object)
1326 && ( strtolower(get_class($object)) == $lclass
1327 || is_subclass_of($object, $lclass) );
1330 /** Determine whether (possible) object has method.
1332 * @param $object mixed Object
1333 * @param $method string Method name
1334 * @return bool True iff $object is an object with has method $method.
1336 function can ($object, $method) {
1337 return is_object($object) && method_exists($object, strtolower($method));
1340 /** Determine whether a function is okay to use.
1342 * Some providers (e.g. Lycos) disable some of PHP functions for
1343 * "security reasons." This makes those functions, of course,
1344 * unusable, despite the fact the function_exists() says they
1347 * This function test to see if a function exists and is not
1348 * disallowed by PHP's disable_functions config setting.
1350 * @param string $function_name Function name
1351 * @return bool True iff function can be used.
1353 function function_usable($function_name) {
1355 if (!is_array($disabled)) {
1356 $disabled = array();
1357 // Use get_cfg_var since ini_get() is one of the disabled functions
1358 // (on Lycos, at least.)
1359 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1360 foreach ($split as $f)
1361 $disabled[strtolower($f)] = true;
1364 return ( function_exists($function_name)
1365 and ! isset($disabled[strtolower($function_name)])
1372 * This is used for generating ETags.
1374 function hash ($x) {
1375 if (is_scalar($x)) {
1378 elseif (is_array($x)) {
1380 return md5(serialize($x));
1382 elseif (is_object($x)) {
1385 trigger_error("Can't hash $x", E_USER_ERROR);
1390 * Seed the random number generator.
1392 * better_srand() ensures the randomizer is seeded only once.
1394 * How random do you want it? See:
1395 * http://www.php.net/manual/en/function.srand.php
1396 * http://www.php.net/manual/en/function.mt-srand.php
1398 function better_srand($seed = '') {
1399 static $wascalled = FALSE;
1401 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1404 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1409 * Recursively count all non-empty elements
1410 * in array of any dimension or mixed - i.e.
1411 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1412 * See http://www.php.net/manual/en/function.count.php
1414 function count_all($arg) {
1415 // skip if argument is empty
1417 //print_r($arg); //debugging
1419 // not an array, return 1 (base case)
1422 // else call recursively for all elements $arg
1423 foreach($arg as $key => $val)
1424 $count += count_all($val);
1429 function isSubPage($pagename) {
1430 return (strstr($pagename, SUBPAGE_SEPARATOR));
1433 function subPageSlice($pagename, $pos) {
1434 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1435 $pages = array_slice($pages,$pos,1);
1442 * Class for "popping up" and alert box. (Except that right now, it doesn't
1446 * This is a hackish and needs to be refactored. However it would be nice to
1447 * unify all the different methods we use for showing Alerts and Dialogs.
1448 * (E.g. "Page deleted", login form, ...)
1453 * @param object $request
1454 * @param mixed $head Header ("title") for alert box.
1455 * @param mixed $body The text in the alert box.
1456 * @param hash $buttons An array mapping button labels to URLs.
1457 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1459 function Alert($head, $body, $buttons=false) {
1460 if ($buttons === false)
1463 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1464 $this->_buttons = $buttons;
1468 * Show the alert box.
1470 function show(&$request) {
1473 $tokens = $this->_tokens;
1474 $tokens['BUTTONS'] = $this->_getButtons();
1476 $request->discardOutput();
1477 $tmpl = new Template('dialog', $request, $tokens);
1483 function _getButtons() {
1486 $buttons = $this->_buttons;
1488 $buttons = array(_("Okay") => $request->getURLtoSelf());
1491 foreach ($buttons as $label => $url)
1492 print "$label $url\n";
1493 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1494 return new XmlContent($out);
1499 // 1.3.9-p1 => 1030.091
1500 // 1.3.10pre => 1030.099
1501 function phpwiki_version() {
1502 static $PHPWIKI_VERSION;
1503 if (!isset($PHPWIKI_VERSION)) {
1504 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1505 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1506 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1507 if (substr(PHPWIKI_VERSION,-3,3) == 'pre')
1508 $PHPWIKI_VERSION -= 0.001;
1510 return $PHPWIKI_VERSION;
1513 function isWikiWord($word) {
1514 global $WikiNameRegexp;
1515 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1516 return preg_match("/^$WikiNameRegexp\$/",$word);
1519 // needed to store serialized objects-values only (perm, pref)
1520 function obj2hash ($obj, $exclude = false, $fields = false) {
1522 if (! $fields ) $fields = get_object_vars($obj);
1523 foreach ($fields as $key => $val) {
1524 if (is_array($exclude)) {
1525 if (in_array($key,$exclude)) continue;
1533 * isUtf8String($string) - cheap utf-8 detection
1535 * segfaults for strings longer than 10kb!
1536 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1537 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1539 function isUtf8String( $s ) {
1540 $ptrASCII = '[\x00-\x7F]';
1541 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1542 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1543 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1544 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1545 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1546 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1550 * Check for UTF-8 URLs; Internet Explorer produces these if you
1551 * type non-ASCII chars in the URL bar or follow unescaped links.
1552 * Requires urldecoded pagename.
1553 * Fixes sf.net bug #953949
1555 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1557 function fixTitleEncoding( $s ) {
1562 if (empty($s)) return $s;
1564 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1566 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1567 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1569 $isutf = ($ishigh ? isUtf8String($s) : true);
1570 $locharset = strtolower($charset);
1572 if( $locharset != "utf-8" and $ishigh and $isutf )
1573 // if charset == 'iso-8859-1' then simply use utf8_decode()
1574 if ($locharset == 'iso-8859-1')
1575 return utf8_decode( $s );
1577 // TODO: check for iconv support
1578 return iconv( "UTF-8", $charset, $s );
1580 if ($locharset == "utf-8" and $ishigh and !$isutf )
1581 return utf8_encode( $s );
1583 // Other languages can safely leave this function, or replace
1584 // it with one to detect and convert another legacy encoding.
1589 * MySQL fulltext index doesn't grok utf-8, so we
1590 * need to fold cases and convert to hex.
1591 * src: languages/Language.php:stripForSearch() from mediawiki
1594 function stripForSearch( $string ) {
1595 global $wikiLowerChars;
1596 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1597 return preg_replace(
1598 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1599 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1605 * Workaround for allow_url_fopen, to get the content of an external URI.
1606 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1607 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1609 function url_get_contents( $uri ) {
1610 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1611 return @file_get_contents($uri);
1613 require_once("lib/HttpClient.php");
1614 $bits = parse_url($uri);
1615 $host = $bits['host'];
1616 $port = isset($bits['port']) ? $bits['port'] : 80;
1617 $path = isset($bits['path']) ? $bits['path'] : '/';
1618 if (isset($bits['query'])) {
1619 $path .= '?'.$bits['query'];
1621 $client = new HttpClient($host, $port);
1622 $client->use_gzip = false;
1623 if (!$client->get($path)) {
1626 return $client->getContent();
1632 // $Log: not supported by cvs2svn $
1633 // Revision 1.197 2004/07/02 09:55:58 rurban
1634 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
1636 // Revision 1.196 2004/07/01 08:51:22 rurban
1637 // dumphtml: added exclude, print pagename before processing
1639 // Revision 1.195 2004/06/29 08:52:22 rurban
1640 // Use ...version() $need_content argument in WikiDB also:
1641 // To reduce the memory footprint for larger sets of pagelists,
1642 // we don't cache the content (only true or false) and
1643 // we purge the pagedata (_cached_html) also.
1644 // _cached_html is only cached for the current pagename.
1645 // => Vastly improved page existance check, ACL check, ...
1647 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1649 // Revision 1.194 2004/06/29 06:48:04 rurban
1650 // Improve LDAP auth and GROUP_LDAP membership:
1651 // no error message on false password,
1652 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
1653 // fixed two group queries (this -> user)
1654 // stdlib: ConvertOldMarkup still flawed
1656 // Revision 1.193 2004/06/28 13:27:03 rurban
1657 // CreateToc disabled for old markup and Apache2 only
1659 // Revision 1.192 2004/06/28 12:47:43 rurban
1660 // skip if non-DEBUG and old markup with CreateToc
1662 // Revision 1.191 2004/06/25 14:31:56 rurban
1663 // avoid debug_skip warning
1665 // Revision 1.190 2004/06/25 14:29:20 rurban
1666 // WikiGroup refactoring:
1667 // global group attached to user, code for not_current user.
1668 // improved helpers for special groups (avoid double invocations)
1669 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1670 // fixed a XHTML validation error on userprefs.tmpl
1672 // Revision 1.189 2004/06/20 09:45:35 rurban
1673 // php5 isa fix (wrong strtolower)
1675 // Revision 1.188 2004/06/16 10:38:58 rurban
1676 // Disallow refernces in calls if the declaration is a reference
1677 // ("allow_call_time_pass_reference clean").
1678 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1679 // but several external libraries may not.
1680 // In detail these libs look to be affected (not tested):
1684 // Revision 1.187 2004/06/14 11:31:37 rurban
1685 // renamed global $Theme to $WikiTheme (gforge nameclash)
1686 // inherit PageList default options from PageList
1687 // default sortby=pagename
1688 // use options in PageList_Selectable (limit, sortby, ...)
1689 // added action revert, with button at action=diff
1690 // added option regex to WikiAdminSearchReplace
1692 // Revision 1.186 2004/06/13 13:54:25 rurban
1693 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
1694 // FoafViewer: Check against external requirements, instead of fatal.
1695 // Change output for xhtmldumps: using file:// urls to the local fs.
1696 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
1697 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
1699 // Revision 1.185 2004/06/11 09:07:30 rurban
1700 // support theme-specific LinkIconAttr: front or after or none
1702 // Revision 1.184 2004/06/04 20:32:53 rurban
1703 // Several locale related improvements suggested by Pierrick Meignen
1704 // LDAP fix by John Cole
1705 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1707 // Revision 1.183 2004/06/01 10:22:56 rurban
1708 // added url_get_contents() used in XmlParser and elsewhere
1710 // Revision 1.182 2004/05/25 12:40:48 rurban
1711 // trim the pagename
1713 // Revision 1.181 2004/05/25 10:18:44 rurban
1714 // Check for UTF-8 URLs; Internet Explorer produces these if you
1715 // type non-ASCII chars in the URL bar or follow unescaped links.
1716 // Fixes sf.net bug #953949
1717 // src: languages/Language.php:checkTitleEncoding() from mediawiki
1719 // Revision 1.180 2004/05/18 16:23:39 rurban
1720 // rename split_pagename to SplitPagename
1722 // Revision 1.179 2004/05/18 16:18:37 rurban
1723 // AutoSplit at subpage seperators
1724 // RssFeed stability fix for empty feeds or broken connections
1726 // Revision 1.178 2004/05/12 10:49:55 rurban
1727 // require_once fix for those libs which are loaded before FileFinder and
1728 // its automatic include_path fix, and where require_once doesn't grok
1729 // dirname(__FILE__) != './lib'
1730 // upgrade fix with PearDB
1731 // navbar.tmpl: remove spaces for IE button alignment
1733 // Revision 1.177 2004/05/08 14:06:12 rurban
1734 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
1735 // minor stability and portability fixes
1737 // Revision 1.176 2004/05/08 11:25:15 rurban
1740 // Revision 1.175 2004/05/06 17:30:38 rurban
1741 // CategoryGroup: oops, dos2unix eol
1742 // improved phpwiki_version:
1743 // pre -= .0001 (1.3.10pre: 1030.099)
1744 // -p1 += .001 (1.3.9-p1: 1030.091)
1745 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1746 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1747 // backend->backendType(), backend->database(),
1748 // backend->listOfFields(),
1749 // backend->listOfTables(),
1751 // Revision 1.174 2004/05/06 12:02:05 rurban
1752 // fix sf.net bug#949002: [ Link | ] assertion
1754 // Revision 1.173 2004/05/03 15:00:31 rurban
1755 // added more database upgrading: session.sess_ip, page.id autp_increment
1757 // Revision 1.172 2004/04/26 20:44:34 rurban
1758 // locking table specific for better databases
1760 // Revision 1.171 2004/04/19 23:13:03 zorloc
1761 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
1763 // Revision 1.170 2004/04/19 18:27:45 rurban
1764 // Prevent from some PHP5 warnings (ref args, no :: object init)
1765 // php5 runs now through, just one wrong XmlElement object init missing
1766 // Removed unneccesary UpgradeUser lines
1767 // Changed WikiLink to omit version if current (RecentChanges)
1769 // Revision 1.169 2004/04/15 21:29:48 rurban
1770 // allow [0] with new markup: link to page "0"
1772 // Revision 1.168 2004/04/10 02:30:49 rurban
1773 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
1774 // Fixed "cannot setlocale..." (sf.net problem)
1776 // Revision 1.167 2004/04/02 15:06:55 rurban
1777 // fixed a nasty ADODB_mysql session update bug
1778 // improved UserPreferences layout (tabled hints)
1779 // fixed UserPreferences auth handling
1780 // improved auth stability
1781 // improved old cookie handling: fixed deletion of old cookies with paths
1783 // Revision 1.166 2004/04/01 15:57:10 rurban
1784 // simplified Sidebar theme: table, not absolute css positioning
1785 // added the new box methods.
1786 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
1788 // Revision 1.165 2004/03/24 19:39:03 rurban
1789 // php5 workaround code (plus some interim debugging code in XmlElement)
1790 // php5 doesn't work yet with the current XmlElement class constructors,
1791 // WikiUserNew does work better than php4.
1792 // rewrote WikiUserNew user upgrading to ease php5 update
1793 // fixed pref handling in WikiUserNew
1794 // added Email Notification
1795 // added simple Email verification
1796 // removed emailVerify userpref subclass: just a email property
1797 // changed pref binary storage layout: numarray => hash of non default values
1798 // print optimize message only if really done.
1799 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1800 // prefs should be stored in db or homepage, besides the current session.
1802 // Revision 1.164 2004/03/18 21:41:09 rurban
1803 // fixed sqlite support
1804 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
1806 // Revision 1.163 2004/03/17 18:41:49 rurban
1807 // just reformatting
1809 // Revision 1.162 2004/03/16 15:43:08 rurban
1810 // make fileSet sortable to please PageList
1812 // Revision 1.161 2004/03/12 15:48:07 rurban
1813 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1814 // simplified lib/stdlib.php:explodePageList
1816 // Revision 1.160 2004/02/28 21:14:08 rurban
1817 // generally more PHPDOC docs
1818 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
1819 // fxied WikiUserNew pref handling: empty theme not stored, save only
1820 // changed prefs, sql prefs improved, fixed password update,
1821 // removed REPLACE sql (dangerous)
1822 // moved gettext init after the locale was guessed
1823 // + some minor changes
1825 // Revision 1.158 2004/02/19 21:54:17 rurban
1826 // moved initerwiki code to PageType.php
1827 // re-enabled and fixed InlineImages support, now also for InterWiki Urls
1828 // * [File:my_image.gif] inlines the image,
1829 // * File:my_image.gif shows a plain inter-wiki link,
1830 // * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
1831 // * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
1833 // Revision 1.157 2004/02/09 03:58:12 rurban
1834 // for now default DB_SESSION to false
1836 // * not existing perms will now query the parent, and not
1837 // return the default perm
1838 // * added pagePermissions func which returns the object per page
1839 // * added getAccessDescription
1841 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1842 // * force init of authdbh in the 2 db classes
1844 // * fixed session handling (not triple auth request anymore)
1845 // * don't store cookie prefs with sessions
1846 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1848 // Revision 1.156 2004/01/26 09:17:49 rurban
1849 // * changed stored pref representation as before.
1850 // the array of objects is 1) bigger and 2)
1851 // less portable. If we would import packed pref
1852 // objects and the object definition was changed, PHP would fail.
1853 // This doesn't happen with an simple array of non-default values.
1854 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1855 // understands the interim format of array of objects also.
1856 // * simplified $prefs->get() and fixed $prefs->set()
1857 // * added $user->_userid and class '_WikiUser' portability functions
1858 // * fixed $user object ->_level upgrading, mostly using sessions.
1859 // this fixes yesterdays problems with loosing authorization level.
1860 // * fixed WikiUserNew::checkPass to return the _level
1861 // * fixed WikiUserNew::isSignedIn
1862 // * added explodePageList to class PageList, support sortby arg
1863 // * fixed UserPreferences for WikiUserNew
1864 // * fixed WikiPlugin for empty defaults array
1865 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1866 // removed sort arg, support sortby arg
1868 // Revision 1.155 2004/01/25 10:52:22 rurban
1869 // added sortby support to explodePageList() and UnfoldSubpages
1870 // fixes [ 758044 ] Plugin UnfoldSubpages does not sort (includes fix)
1872 // Revision 1.154 2004/01/25 03:49:03 rurban
1873 // added isWikiWord() to avoid redundancy
1874 // added check_php_version() to check for older php versions.
1875 // e.g. object::method calls, ...
1877 // Revision 1.153 2003/11/30 18:43:18 carstenklapp
1878 // Fixed careless mistakes in my last optimization commit.
1880 // Revision 1.152 2003/11/30 18:20:34 carstenklapp
1881 // Minor code optimization: reduce invariant loops
1883 // Revision 1.151 2003/11/29 19:30:01 carstenklapp
1884 // New function ByteFormatter.
1886 // Revision 1.150 2003/09/13 22:43:00 carstenklapp
1887 // New preference to hide LinkIcons.
1889 // Revision 1.149 2003/03/26 19:37:08 dairiki
1890 // Fix "object to string conversion" bug with external image links.
1892 // Revision 1.148 2003/03/25 21:03:02 dairiki
1893 // Cleanup debugging output.
1895 // Revision 1.147 2003/03/13 20:17:05 dairiki
1896 // Bug fix: Fix linking of pages whose names contain a hash ('#').
1898 // Revision 1.146 2003/03/07 02:46:24 dairiki
1899 // function_usable(): New function.
1901 // Revision 1.145 2003/03/04 01:55:05 dairiki
1902 // Fix to ensure absolute URL for logo in RSS recent changes.
1904 // Revision 1.144 2003/02/26 00:39:30 dairiki
1905 // Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
1906 // being displayed at incorrect times.
1908 // Revision 1.143 2003/02/26 00:10:26 dairiki
1909 // More/better/different checks for bad page names.
1911 // Revision 1.142 2003/02/25 22:19:46 dairiki
1912 // Add some sanity checking for pagenames.
1914 // Revision 1.141 2003/02/22 20:49:55 dairiki
1915 // Fixes for "Call-time pass by reference has been deprecated" errors.
1917 // Revision 1.140 2003/02/21 23:33:29 dairiki
1918 // Set alt="" on the link icon image tags.
1919 // (See SF bug #675141.)
1921 // Revision 1.139 2003/02/21 22:16:27 dairiki
1922 // Get rid of MakeWikiForm, and form-style MagicPhpWikiURLs.
1923 // These have been obsolete for quite awhile (I hope).
1925 // Revision 1.138 2003/02/21 04:12:36 dairiki
1926 // WikiPageName: fixes for new cached links.
1928 // Alert: new class for displaying alerts.
1930 // ExtractWikiPageLinks and friends are now gone.
1932 // LinkBracketLink moved to InlineParser.php
1934 // Revision 1.137 2003/02/18 23:13:40 dairiki
1935 // Wups again. Typo fix.
1937 // Revision 1.136 2003/02/18 21:52:07 dairiki
1938 // Fix so that one can still link to wiki pages with # in their names.
1939 // (This was made difficult by the introduction of named tags, since
1940 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1942 // Now the ~ escape for page names should work: [Page ~#1].
1944 // Revision 1.135 2003/02/18 19:17:04 dairiki
1946 // Bug fix. 'ThisIsABug' was being split to 'This IsA Bug'.
1947 // Cleanup up subpage splitting code.
1949 // Revision 1.134 2003/02/16 19:44:20 dairiki
1950 // New function hash(). This is a helper, primarily for generating
1953 // Revision 1.133 2003/02/16 04:50:09 dairiki
1955 // Rfc1123DateTime(), ParseRfc1123DateTime()
1956 // for converting unix timestamps to and from strings.
1958 // These functions produce and grok the time strings
1959 // in the format specified by RFC 2616 for use in HTTP headers
1960 // (like Last-Modified).
1962 // Revision 1.132 2003/01/04 22:19:43 carstenklapp
1963 // Bugfix UnfoldSubpages: "Undefined offset: 1" error when plugin invoked
1964 // on a page with no subpages (explodeList(): array 0-based, sizeof 1-based).
1967 // (c-file-style: "gnu")
1971 // c-basic-offset: 4
1972 // c-hanging-comment-ender-p: nil
1973 // indent-tabs-mode: nil