1 <?php //rcs_id('$Id: stdlib.php,v 1.227 2005-01-14 18:32:08 uckelman Exp $');
4 Standard functions for Wiki functionality
5 WikiURL ($pagename, $args, $get_abs_url)
7 IconForLink ($protocol_or_url)
8 PossiblyGlueIconToText($proto_or_url, $text)
10 LinkURL ($url, $linktext)
11 LinkImage ($url, $alt)
13 SplitQueryArgs ($query_args)
14 LinkPhpwikiURL ($url, $text, $basepage)
15 ConvertOldMarkup ($content, $markup_type = "block")
16 MangleXmlIdentifier($str)
17 UnMangleXmlIdentifier($str)
19 class Stack { push($item), pop(), cnt(), top() }
20 class Alert { show() }
21 class WikiPageName {getParent(),isValid(),getWarnings() }
23 expand_tabs($str, $tab_width = 8)
25 NoSuchRevision ($request, $page, $version)
26 TimezoneOffset ($time, $no_colon)
27 Iso8601DateTime ($time)
28 Rfc2822DateTime ($time)
29 ParseRfc1123DateTime ($timestr)
31 ByteFormatter ($bytes = 0, $longformat = false)
34 __vsprintf ($fmt, $args)
36 file_mtime ($filename)
37 sort_file_mtime ($a, $b)
38 class fileSet {fileSet($directory, $filepattern = false), getFiles($exclude=false, $sortby=false, $limit=false) }
39 class ListRegexExpand { listMatchCallback($item, $key), expandRegex ($index, &$pages) }
42 glob_match ($glob, $against, $case_sensitive = true)
43 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
44 explodePageList ($input, $perm = false)
46 can ($object, $method)
47 function_usable ($function_name)
49 better_srand ($seed = '')
52 subPageSlice ($pagename, $pos)
56 obj2hash ($obj, $exclude = false, $fields = false)
59 url_get_contents ($uri)
61 firstNWordsOfContent ($n, $content)
62 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
65 function: LinkInterWikiLink($link, $linktext)
66 moved to: lib/interwiki.php
67 function: linkExistingWikiWord($wikiword, $linktext, $version)
68 moved to: lib/Theme.php
69 function: LinkUnknownWikiWord($wikiword, $linktext)
70 moved to: lib/Theme.php
71 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
72 gone see: lib/plugin/RecentChanges.php
74 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
75 else define('_PHPWIKI_STDLIB_LOADED', true);
77 define('MAX_PAGENAME_LENGTH', 100);
80 * Convert string to a valid XML identifier.
82 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
84 * We would like to have, e.g. named anchors within wiki pages
85 * names like "Table of Contents" --- clearly not a valid XML
86 * fragment identifier.
88 * This function implements a one-to-one map from {any string}
89 * to {valid XML identifiers}.
92 * converting all bytes not in [A-Za-z0-9:_-],
93 * and any leading byte not in [A-Za-z] to 'xbb.',
94 * where 'bb' is the hexadecimal representation of the
97 * As a special case, the empty string is converted to 'empty.'
102 function MangleXmlIdentifier($str) {
106 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
107 "'x' . sprintf('%02x', ord('\\0')) . '.'",
111 function UnMangleXmlIdentifier($str) {
112 if ($str == 'empty.')
114 return preg_replace('/x(\w\w)\./e',
115 "sprintf('%c', hex('\\0'))",
120 * Generates a valid URL for a given Wiki pagename.
121 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
122 * If a WikiDB_Page object function will extract the name to link to.
123 * If a WikiDB_PageRevision object function will extract the name to link to.
125 * @param boolean $get_abs_url Default value is false.
126 * @return string The absolute URL to the page passed as $pagename.
128 function WikiURL($pagename, $args = '', $get_abs_url = false) {
131 if (is_object($pagename)) {
132 if (isa($pagename, 'WikiDB_Page')) {
133 $pagename = $pagename->getName();
135 elseif (isa($pagename, 'WikiDB_PageRevision')) {
136 $page = $pagename->getPage();
137 $args['version'] = $pagename->getVersion();
138 $pagename = $page->getName();
140 elseif (isa($pagename, 'WikiPageName')) {
141 $anchor = $pagename->anchor;
142 $pagename = $pagename->name;
144 $anchor = $pagename->anchor;
145 $pagename = $pagename->name;
148 if (!$get_abs_url and DEBUG and $GLOBALS['request']->getArg('start_debug')) {
150 $args = 'start_debug=' . $GLOBALS['request']->getArg('start_debug');
151 elseif (is_array($args))
152 $args['start_debug'] = $GLOBALS['request']->getArg('start_debug');
154 $args .= '&start_debug=' . $GLOBALS['request']->getArg('start_debug');
156 if (is_array($args)) {
158 foreach ($args as $key => $val) {
159 // avoid default args
160 if (USE_PATH_INFO and $key == 'pagename')
162 elseif ($key == 'action' and $val == 'browse')
164 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
165 $enc_args[] = urlencode($key) . '=' . urlencode($val);
167 $args = join('&', $enc_args);
170 if (USE_PATH_INFO or !empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX)) {
171 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
172 $url = $url . preg_replace('/%2f/i', '/', rawurlencode($pagename));
173 if (!empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX))
174 $url .= $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
179 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
180 $url .= "?pagename=" . rawurlencode($pagename);
185 $url .= "#" . MangleXmlIdentifier($anchor);
189 /** Convert relative URL to absolute URL.
191 * This converts a relative URL to one of PhpWiki's support files
192 * to an absolute one.
195 * @return string Absolute URL
197 function AbsoluteURL ($url) {
198 if (preg_match('/^https?:/', $url))
200 if ($url[0] != '/') {
201 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
202 while ($base != '/' and substr($url, 0, 3) == "../") {
203 $url = substr($url, 3);
204 $base = dirname($base);
210 return SERVER_URL . $url;
213 function DataURL ($url) {
214 if (preg_match('/^https?:/', $url))
216 $url = NormalizeWebFileName($url);
217 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
218 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
219 return AbsoluteURL($url);
223 * Generates icon in front of links.
225 * @param string $protocol_or_url URL or protocol to determine which icon to use.
227 * @return HtmlElement HtmlElement object that contains data to create img link to
228 * icon for use with url or protocol passed to the function. False if no img to be
231 function IconForLink($protocol_or_url) {
233 if (0 and $filename_suffix == false) {
234 // display apache style icon for file type instead of protocol icon
235 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
236 // - document: html, htm, text, txt, rtf, pdf, doc
237 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
238 // - audio: mp3,mp2,aiff,aif,au
239 // - multimedia: mpeg,mpg,mov,qt
241 list ($proto) = explode(':', $protocol_or_url, 2);
242 $src = $WikiTheme->getLinkIconURL($proto);
244 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
251 * Glue icon in front of or after text.
252 * Pref: 'noLinkIcons' - ignore icon if set
253 * Theme: 'LinkIcons' - 'yes' at front
254 * - 'no' display no icon
255 * - 'front' display at left
256 * - 'after' display at right
258 * @param string $protocol_or_url Protocol or URL. Used to determine the
260 * @param string $text The text.
261 * @return XmlContent.
263 function PossiblyGlueIconToText($proto_or_url, $text) {
264 global $request, $WikiTheme;
265 if ($request->getPref('noLinkIcons'))
267 $icon = IconForLink($proto_or_url);
270 if ($where = $WikiTheme->getLinkIconAttr()) {
271 if ($where == 'no') return $text;
272 if ($where != 'after') $where = 'front';
276 if ($where == 'after') {
277 // span the icon only to the last word (tie them together),
278 // to let the previous words wrap on line breaks.
279 if (!is_object($text)) {
280 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
281 list (, $prefix, $last_word) = $m;
287 $text = HTML::span(array('style' => 'white-space: nowrap'),
288 $last_word, HTML::Raw(' '), $icon);
290 $text = HTML($prefix, $text);
293 // span the icon only to the first word (tie them together),
294 // to let the next words wrap on line breaks
295 if (!is_object($text)) {
296 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
297 list (, $first_word, $tail) = $m;
303 $text = HTML::span(array('style' => 'white-space: nowrap'),
306 $text = HTML($text, $tail);
311 * Determines if the url passed to function is safe, by detecting if the characters
312 * '<', '>', or '"' are present.
314 * @param string $url URL to check for unsafe characters.
315 * @return boolean True if same, false else.
317 function IsSafeURL($url) {
318 return !preg_match('/[<>"]/', $url);
322 * Generates an HtmlElement object to store data for a link.
324 * @param string $url URL that the link will point to.
325 * @param string $linktext Text to be displayed as link.
326 * @return HtmlElement HtmlElement object that contains data to construct an html link.
328 function LinkURL($url, $linktext = '') {
329 // FIXME: Is this needed (or sufficient?)
330 if(! IsSafeURL($url)) {
331 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
332 _("BAD URL -- remove all of <, >, \"")));
336 $linktext = preg_replace("/mailto:/A", "", $url);
338 $link = HTML::a(array('href' => $url),
339 PossiblyGlueIconToText($url, $linktext));
342 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
347 * FIXME: disallow sizes which are too small.
348 * Spammers may use such (typically invisible) image attributes to higher their GoogleRank.
350 function LinkImage($url, $alt = false) {
351 // FIXME: Is this needed (or sufficient?)
352 if(! IsSafeURL($url)) {
353 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
354 _("BAD URL -- remove all of <, >, \"")));
356 // support new syntax: [image.jpg size=50% border=n]
357 $arr = split(' ',$url);
358 if (count($arr) > 1) {
361 if (empty($alt)) $alt = basename($url);
362 $link = HTML::img(array('src' => $url, 'alt' => $alt));
363 if (count($arr) > 1) {
365 foreach ($arr as $attr) {
366 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
367 $link->setAttr('width',$m[1]);
368 $link->setAttr('height',$m[1]);
370 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
371 $link->setAttr('width',$m[1]);
372 $link->setAttr('height',$m[2]);
374 if (preg_match('/^border=(\d+)$/',$attr,$m))
375 $link->setAttr('border',$m[1]);
376 if (preg_match('/^align=(\w+)$/',$attr,$m))
377 $link->setAttr('align',$m[1]);
378 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
379 $link->setAttr('hspace',$m[1]);
380 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
381 $link->setAttr('vspace',$m[1]);
384 // check width and height as spam countermeasure
385 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
386 //$width = (int) $width; // px or % or other suffix
387 //$height = (int) $height;
388 if (($width < 3 and $height < 10) or
389 ($height < 3 and $width < 20) or
390 ($height < 7 and $width < 7))
392 trigger_error(_("Invalid image size"), E_USER_NOTICE);
396 // Older php versions crash here with certain png's:
397 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
398 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
399 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
400 if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
401 ; // it's safe to assume that this will fail.
402 elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
405 if (($width < 3 and $height < 10)
406 or ($height < 3 and $width < 20)
407 or ($height < 7 and $width < 7))
409 trigger_error(_("Invalid image size"), E_USER_NOTICE);
415 $link->setAttr('class', 'inlineimage');
423 // var in php5 deprecated
425 $this->items = array();
428 function push($item) {
429 $this->items[$this->size] = $item;
435 if ($this->size == 0) {
436 return false; // stack is empty
439 return $this->items[$this->size];
448 return $this->items[$this->size - 1];
454 // end class definition
456 function SplitQueryArgs ($query_args = '')
458 $split_args = split('&', $query_args);
460 while (list($key, $val) = each($split_args))
461 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
462 $args[$m[1]] = $m[2];
466 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
469 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
470 return HTML::strong(array('class' => 'rawurl'),
471 HTML::u(array('class' => 'baduri'),
472 _("BAD phpwiki: URL")));
476 $pagename = urldecode($m[1]);
479 if (empty($pagename) &&
480 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
481 // Convert old style links (to not break diff links in
483 $pagename = urldecode($m[2]);
484 $args = array("action" => $m[1]);
487 $args = SplitQueryArgs($qargs);
490 if (empty($pagename))
491 $pagename = $GLOBALS['request']->getArg('pagename');
493 if (isset($args['action']) && $args['action'] == 'browse')
494 unset($args['action']);
497 if (empty($args['action']))
499 else if (is_safe_action($args['action']))
500 $class = 'wikiaction';
502 if (empty($args['action']) || is_safe_action($args['action']))
503 $class = 'wikiaction';
505 // Don't allow administrative links on unlocked pages.
506 $dbi = $GLOBALS['request']->getDbh();
507 $page = $dbi->getPage($basepage ? $basepage : $pagename);
508 if (!$page->get('locked'))
509 return HTML::span(array('class' => 'wikiunsafe'),
510 HTML::u(_("Lock page to enable link")));
511 $class = 'wikiadmin';
515 $text = HTML::span(array('class' => 'rawurl'), $url);
517 $wikipage = new WikiPageName($pagename);
518 if (!$wikipage->isValid()) {
520 return $WikiTheme->linkBadWikiWord($wikipage, $url);
523 return HTML::a(array('href' => WikiURL($pagename, $args),
529 * A class to assist in parsing wiki pagenames.
531 * Now with subpages and anchors, parsing and passing around
532 * pagenames is more complicated. This should help.
536 /** Short name for page.
538 * This is the value of $name passed to the constructor.
539 * (For use, e.g. as a default label for links to the page.)
543 /** The full page name.
545 * This is the full name of the page (without anchor).
551 * This is the referenced anchor within the page, or the empty string.
557 * @param mixed $name Page name.
558 * WikiDB_Page, WikiDB_PageRevision, or string.
559 * This can be a relative subpage name (like '/SubPage'),
560 * or can be the empty string to refer to the $basename.
562 * @param string $anchor For links to anchors in page.
564 * @param mixed $basename Page name from which to interpret
565 * relative or other non-fully-specified page names.
567 function WikiPageName($name, $basename=false, $anchor=false) {
568 if (is_string($name)) {
569 $this->shortName = $name;
571 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
573 $name = $this->_pagename($basename) . $name;
575 $name = $this->_normalize_bad_pagename($name);
579 $name = $this->_pagename($name);
580 $this->shortName = $name;
583 $this->name = $this->_check($name);
584 $this->anchor = (string)$anchor;
587 function getParent() {
589 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
591 return substr($name, 0, -strlen($tail));
594 function isValid($strict = false) {
596 return !isset($this->_errors);
597 return (is_string($this->name) and $this->name != '');
600 function getWarnings() {
602 if (isset($this->_warnings))
603 $warnings = array_merge($warnings, $this->_warnings);
604 if (isset($this->_errors))
605 $warnings = array_merge($warnings, $this->_errors);
609 return sprintf(_("'%s': Bad page name: %s"),
610 $this->shortName, join(', ', $warnings));
613 function _pagename($page) {
614 if (isa($page, 'WikiDB_Page'))
615 return $page->getName();
616 elseif (isa($page, 'WikiDB_PageRevision'))
617 return $page->getPageName();
618 elseif (isa($page, 'WikiPageName'))
620 if (!is_string($page)) {
621 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
622 $page, gettype($page), get_class($page)),
625 //assert(is_string($page));
629 function _normalize_bad_pagename($name) {
630 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
632 // Punt... You really shouldn't get here.
635 return $request->getArg('pagename');
637 assert($name[0] == SUBPAGE_SEPARATOR);
638 return substr($name, 1);
642 function _check($pagename) {
643 // Compress internal white-space to single space character.
644 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
645 if ($pagename != $orig)
646 $this->_warnings[] = _("White space converted to single space");
648 // Delete any control characters.
649 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
650 if ($pagename != $orig)
651 $this->_errors[] = _("Control characters not allowed");
653 // Strip leading and trailing white-space.
654 $pagename = trim($pagename);
657 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
658 $pagename = substr($pagename, 1);
659 if ($pagename != $orig)
660 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
662 if (preg_match('/[:;]/', $pagename)) {
663 $this->_warnings[] = _("';' and ':' are deprecated");
664 $pagename = str_replace(':', '', $pagename);
665 $pagename = str_replace(';', '', $pagename);
668 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
669 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
670 $this->_errors[] = _("too long");
673 if (strstr($pagename, '..')) {
674 $this->_warnings[] = sprintf(_("illegal .. removed"), $pagename);
675 $pagename = str_replace('..', '', $pagename);
683 * Convert old page markup to new-style markup.
685 * @param string $text Old-style wiki markup.
687 * @param string $markup_type
689 * <dt><code>"block"</code> <dd>Convert all markup.
690 * <dt><code>"inline"</code> <dd>Convert only inline markup.
691 * <dt><code>"links"</code> <dd>Convert only link markup.
694 * @return string New-style wiki markup.
696 * @bugs Footnotes don't work quite as before (esp if there are
697 * multiple references to the same footnote. But close enough,
698 * probably for now....
699 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
700 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
701 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
702 * also known to crash, even with Apache1.
704 function ConvertOldMarkup ($text, $markup_type = "block") {
710 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
711 // AnciennesR%E8glesDeFormatage crashes.
712 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
713 // also known to crash, even with Apache1.
715 // I suspect this only to crash with Apache2 and IIS.
716 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
717 and preg_match("/plugin CreateToc/", $text))
719 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
720 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
721 ._("Skipped."), E_USER_WARNING);
723 //if (!DEBUG) return $text;
728 /*****************************************************************
729 * Conversions for inline markup:
736 // escape escaped brackets
740 // change ! escapes to ~'s.
741 global $WikiNameRegexp, $request;
742 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
743 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
744 if (check_php_version(4,3,9)) {
745 $map = getInterwikiMap();
746 if ($map_regex = $map->getRegexp())
747 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
749 $bang_esc[] = $WikiNameRegexp;
750 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
753 $subs["links"] = array($orig, $repl);
755 // Temporarily URL-encode pairs of underscores in links to hide
756 // them from the re for bold markup.
757 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
758 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
761 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
764 // Convert footnote references.
765 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
766 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
768 // Convert old style emphases to HTML style emphasis.
769 $orig[] = '/__(.*?)__/';
770 $repl[] = '<strong>\\1</strong>';
771 $orig[] = "/''(.*?)''/";
772 $repl[] = '<em>\\1</em>';
774 // Escape nestled markup.
775 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
778 // in old markup headings only allowed at beginning of line
782 // Convert URL-encoded pairs of underscores in links back to
783 // real underscores after bold markup has been converted.
784 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
785 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
787 $subs["inline"] = array($orig, $repl);
789 /*****************************************************************
790 * Patterns which match block markup constructs which take
791 * special handling...
795 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
797 $blockpats[] = '\|(?:.*\n\|)*';
800 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
802 // Footnote definitions
803 $blockpats[] = '\[\s*(\d+)\s*\]';
807 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
811 $blockpats[] = '!{1,3}[^!]';
813 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
814 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
816 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
817 . join("|", $blockpats)
822 if ($markup_type != "block") {
823 list ($orig, $repl) = $subs[$markup_type];
824 return preg_replace($orig, $repl, $text);
827 list ($orig, $repl) = $subs['inline'];
830 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
831 // AnciennesR%E8glesDeFormatage and more
832 // See http://www.pcre.org/pcre.txt LIMITATIONS
833 while (preg_match($block_re, $text, $m)) {
834 $text = substr($text, strlen($m[0]));
835 list (,$leading_text, $block) = $m;
838 if (strchr(" \t", $block[0])) {
841 $suffix = "\n</pre>\n";
843 elseif ($block[0] == '|') {
845 $prefix = "<?plugin OldStyleTable\n";
848 elseif (strchr("#*;", $block[0])) {
849 // Old-style list item
850 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
851 list (,$ind,$bullet) = $m;
852 $block = substr($block, strlen($m[0]));
854 $indent = str_repeat(' ', strlen($ind));
855 if ($bullet[0] == ';') {
856 //$term = ltrim(substr($bullet, 1));
857 //return $indent . $term . "\n" . $indent . ' ';
858 $prefix = $ind . $bullet;
861 $prefix = $indent . $bullet . ' ';
863 elseif ($block[0] == '[') {
864 // Footnote definition
865 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
867 $block = substr($block, strlen($m[0]));
868 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
870 elseif ($block[0] == '<') {
872 // HACK: no inline markup...
876 elseif ($block[0] == '!') {
878 preg_match('/^!{1,3}/', $block, $m);
880 $block = substr($block, strlen($m[0]));
886 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
887 if ($block) $block = preg_replace($orig, $repl, $block);
888 $out .= $leading_text;
893 return $out . preg_replace($orig, $repl, $text);
899 * Expand tabs in string.
901 * Converts all tabs to (the appropriate number of) spaces.
904 * @param integer $tab_width
907 function expand_tabs($str, $tab_width = 8) {
908 $split = split("\t", $str);
909 $tail = array_pop($split);
911 foreach ($split as $hunk) {
913 $pos = strlen(strrchr($expanded, "\n")) - 1;
914 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
916 return substr($expanded, 1) . $tail;
920 * Split WikiWords in page names.
922 * It has been deemed useful to split WikiWords (into "Wiki Words") in
923 * places like page titles. This is rumored to help search engines
926 * @param $page string The page name.
928 * @return string The split name.
930 function SplitPagename ($page) {
932 if (preg_match("/\s/", $page))
933 return $page; // Already split --- don't split any more.
935 // This algorithm is specialized for several languages.
936 // (Thanks to Pierrick MEIGNEN)
937 // Improvements for other languages welcome.
940 // This mess splits between a lower-case letter followed by
941 // either an upper-case or a numeral; except that it wont
942 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
943 switch ($GLOBALS['LANG']) {
948 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
951 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
954 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
955 // This the single-letter words 'I' and 'A' from any following
956 // capitalized words.
957 switch ($GLOBALS['LANG']) {
959 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
962 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
965 // Split numerals from following letters.
966 $RE[] = '/(\d)([[:alpha:]])/';
967 // Split at subpage seperators. TBD in Theme.php
968 $RE[] = "/([^${sep}]+)(${sep})/";
970 foreach ($RE as $key)
971 $RE[$key] = pcre_fix_posix_classes($key);
974 foreach ($RE as $regexp) {
975 $page = preg_replace($regexp, '\\1 \\2', $page);
980 function NoSuchRevision (&$request, $page, $version) {
981 $html = HTML(HTML::h2(_("Revision Not Found")),
982 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
983 $version, WikiLink($page, 'auto'))));
984 include_once('lib/Template.php');
985 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
991 * Get time offset for local time zone.
993 * @param $time time_t Get offset for this time. Default: now.
994 * @param $no_colon boolean Don't put colon between hours and minutes.
995 * @return string Offset as a string in the format +HH:MM.
997 function TimezoneOffset ($time = false, $no_colon = false) {
1000 $secs = date('Z', $time);
1009 $colon = $no_colon ? '' : ':';
1010 $mins = intval(($secs + 30) / 60);
1011 return sprintf("%s%02d%s%02d",
1012 $sign, $mins / 60, $colon, $mins % 60);
1017 * Format time in ISO-8601 format.
1019 * @param $time time_t Time. Default: now.
1020 * @return string Date and time in ISO-8601 format.
1022 function Iso8601DateTime ($time = false) {
1023 if ($time === false)
1025 $tzoff = TimezoneOffset($time);
1026 $date = date('Y-m-d', $time);
1027 $time = date('H:i:s', $time);
1028 return $date . 'T' . $time . $tzoff;
1032 * Format time in RFC-2822 format.
1034 * @param $time time_t Time. Default: now.
1035 * @return string Date and time in RFC-2822 format.
1037 function Rfc2822DateTime ($time = false) {
1038 if ($time === false)
1040 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1044 * Format time in RFC-1123 format.
1046 * @param $time time_t Time. Default: now.
1047 * @return string Date and time in RFC-1123 format.
1049 function Rfc1123DateTime ($time = false) {
1050 if ($time === false)
1052 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1055 /** Parse date in RFC-1123 format.
1057 * According to RFC 1123 we must accept dates in the following
1060 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1061 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1062 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1064 * (Though we're only allowed to generate dates in the first format.)
1066 function ParseRfc1123DateTime ($timestr) {
1067 $timestr = trim($timestr);
1068 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1069 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1071 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1073 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1074 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1076 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1077 if ($year < 70) $year += 2000;
1078 elseif ($year < 100) $year += 1900;
1080 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1081 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1083 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1090 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1092 return false; // failed
1097 * Format time to standard 'ctime' format.
1099 * @param $time time_t Time. Default: now.
1100 * @return string Date and time.
1102 function CTime ($time = false)
1104 if ($time === false)
1106 return date("D M j H:i:s Y", $time);
1111 * Format number as kilobytes or bytes.
1112 * Short format is used for PageList
1113 * Long format is used in PageInfo
1115 * @param $bytes int. Default: 0.
1116 * @param $longformat bool. Default: false.
1117 * @return class FormattedText (XmlElement.php).
1119 function ByteFormatter ($bytes = 0, $longformat = false) {
1122 if ($bytes < 1024) {
1124 $size = fmt("%s b", $bytes);
1126 $size = fmt("%s bytes", $bytes);
1129 $kb = round($bytes / 1024, 1);
1131 $size = fmt("%s k", $kb);
1133 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1139 * Internationalized printf.
1141 * This is essentially the same as PHP's built-in printf
1142 * with the following exceptions:
1144 * <li> It passes the format string through gettext().
1145 * <li> It supports the argument reordering extensions.
1152 * __printf("Differences between versions %s and %s of %s",
1153 * $new_link, $old_link, $page_link);
1156 * Then in locale/po/de.po, one can reorder the printf arguments:
1159 * msgid "Differences between %s and %s of %s."
1160 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1163 * (Note that while PHP tries to expand $vars within double-quotes,
1164 * the values in msgstr undergo no such expansion, so the '$'s
1167 * One shouldn't use reordered arguments in the default format string.
1168 * Backslashes in the default string would be necessary to escape the
1169 * '$'s, and they'll cause all kinds of trouble....
1171 function __printf ($fmt) {
1172 $args = func_get_args();
1174 echo __vsprintf($fmt, $args);
1178 * Internationalized sprintf.
1180 * This is essentially the same as PHP's built-in printf with the
1181 * following exceptions:
1184 * <li> It passes the format string through gettext().
1185 * <li> It supports the argument reordering extensions.
1190 function __sprintf ($fmt) {
1191 $args = func_get_args();
1193 return __vsprintf($fmt, $args);
1197 * Internationalized vsprintf.
1199 * This is essentially the same as PHP's built-in printf with the
1200 * following exceptions:
1203 * <li> It passes the format string through gettext().
1204 * <li> It supports the argument reordering extensions.
1209 function __vsprintf ($fmt, $args) {
1210 $fmt = gettext($fmt);
1211 // PHP's sprintf doesn't support variable with specifiers,
1212 // like sprintf("%*s", 10, "x"); --- so we won't either.
1214 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1215 // Format string has '%2$s' style argument reordering.
1216 // PHP doesn't support this.
1217 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1218 // literal variable name substitution only to keep locale
1219 // strings uncluttered
1220 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1221 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1223 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1226 // Reorder arguments appropriately.
1227 foreach($m[1] as $argnum) {
1228 if ($argnum < 1 || $argnum > count($args))
1229 trigger_error(sprintf(_("%s: argument index out of range"),
1230 $argnum), E_USER_WARNING);
1231 $newargs[] = $args[$argnum - 1];
1236 // Not all PHP's have vsprintf, so...
1237 array_unshift($args, $fmt);
1238 return call_user_func_array('sprintf', $args);
1241 function file_mtime ($filename) {
1242 if ($stat = @stat($filename))
1248 function sort_file_mtime ($a, $b) {
1249 $ma = file_mtime($a);
1250 $mb = file_mtime($b);
1251 if (!$ma or !$mb or $ma == $mb) return 0;
1252 return ($ma > $mb) ? -1 : 1;
1257 * Build an array in $this->_fileList of files from $dirname.
1258 * Subdirectories are not traversed.
1260 * (This was a function LoadDir in lib/loadsave.php)
1261 * See also http://www.php.net/manual/en/function.readdir.php
1263 function getFiles($exclude=false, $sortby=false, $limit=false) {
1264 $list = $this->_fileList;
1267 require_once('lib/PageList.php');
1268 switch (Pagelist::sortby($sortby, 'db')) {
1269 case 'pagename ASC': break;
1270 case 'pagename DESC':
1271 $list = array_reverse($list);
1274 usort($list,'sort_file_mtime');
1277 usort($list,'sort_file_mtime');
1278 $list = array_reverse($list);
1283 return array_splice($list, 0, $limit);
1287 function _filenameSelector($filename) {
1288 if (! $this->_pattern)
1291 return glob_match ($this->_pattern, $filename, $this->_case);
1295 function fileSet($directory, $filepattern = false) {
1296 $this->_fileList = array();
1297 $this->_pattern = $filepattern;
1298 $this->_case = !isWindows();
1299 $this->_pathsep = '/';
1301 if (empty($directory)) {
1302 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1304 return; // early return
1307 @ $dir_handle = opendir($dir=$directory);
1308 if (empty($dir_handle)) {
1309 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1310 $dir), E_USER_NOTICE);
1311 return; // early return
1314 while ($filename = readdir($dir_handle)) {
1315 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1317 if ($this->_filenameSelector($filename)) {
1318 array_push($this->_fileList, "$filename");
1319 //trigger_error(sprintf(_("found file %s"), $filename),
1320 // E_USER_NOTICE); //debugging
1323 closedir($dir_handle);
1329 // expands a list containing regex's to its matching entries
1330 class ListRegexExpand {
1331 //var $match, $list, $index, $case_sensitive;
1332 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1333 $this->match = str_replace('/','\/',$match);
1334 $this->list = &$list;
1335 $this->case_sensitive = $case_sensitive;
1336 //$this->index = false;
1338 function listMatchCallback ($item, $key) {
1339 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1340 unset($this->list[$this->index]);
1341 $this->list[] = $item;
1344 function expandRegex ($index, &$pages) {
1345 $this->index = $index;
1346 array_walk($pages, array($this, 'listMatchCallback'));
1351 // convert fileglob to regex style:
1352 // convert some wildcards to pcre style, escape the rest
1353 // escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | :
1354 function glob_to_pcre ($glob) {
1355 // check simple case: no need to escape
1356 if (strcspn($glob, ".\\+*?[^]$(){}=!<>|:") == strlen($glob))
1358 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1359 $glob = strtr($glob, "\\", "\xff");
1360 // first convert some unescaped expressions to pcre style: . => \.
1362 $re = preg_replace('/([^\xff])?(['.preg_quote($escape).'])/', "\\1\xff\\2", $glob);
1365 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1366 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1367 if (!preg_match('/^[\?\*]/',$glob))
1369 if (!preg_match('/[\?\*]$/',$glob))
1372 // .*? handled above, now escape the rest
1373 $escape = '\[](){}=!<>|:';
1374 while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1375 $re = preg_replace('/([^\xff])(['.preg_quote($escape).'])/', "\\1\xff\\2", $re);
1376 return strtr($re, "\xff", "\\");
1379 function glob_match ($glob, $against, $case_sensitive = true) {
1380 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1383 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1384 $list = explode(',',$input);
1385 // expand wildcards from list of $allnames
1386 if (preg_match('/[\?\*]/',$input)) {
1387 // Optimizing loop invariants:
1388 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1389 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1391 if (preg_match('/[\?\*]/',$f)) {
1393 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1394 $expand->expandRegex($i, $allnames);
1401 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1402 function explodePageList($input, $include_empty=false, $sortby='pagename', $limit=false, $exclude=false) {
1403 include_once("lib/PageList.php");
1404 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1407 // Class introspections
1410 * Determine whether object is of a specified type.
1411 * In PHP builtin since 4.2.0 as is_a()
1413 * @param $object object An object.
1414 * @param $class string Class name.
1415 * @return bool True iff $object is a $class
1416 * or a sub-type of $class.
1418 function isa ($object, $class) {
1419 //if (check_php_version(5))
1420 // return $object instanceof $class;
1421 if (check_php_version(4,2) and !check_php_version(5))
1422 return is_a($object, $class);
1424 $lclass = check_php_version(5) ? $class : strtolower($class);
1425 return is_object($object)
1426 && ( strtolower(get_class($object)) == strtolower($class)
1427 || is_subclass_of($object, $lclass) );
1430 /** Determine whether (possible) object has method.
1432 * @param $object mixed Object
1433 * @param $method string Method name
1434 * @return bool True iff $object is an object with has method $method.
1436 function can ($object, $method) {
1437 return is_object($object) && method_exists($object, strtolower($method));
1440 /** Determine whether a function is okay to use.
1442 * Some providers (e.g. Lycos) disable some of PHP functions for
1443 * "security reasons." This makes those functions, of course,
1444 * unusable, despite the fact the function_exists() says they
1447 * This function test to see if a function exists and is not
1448 * disallowed by PHP's disable_functions config setting.
1450 * @param string $function_name Function name
1451 * @return bool True iff function can be used.
1453 function function_usable($function_name) {
1455 if (!is_array($disabled)) {
1456 $disabled = array();
1457 // Use get_cfg_var since ini_get() is one of the disabled functions
1458 // (on Lycos, at least.)
1459 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1460 foreach ($split as $f)
1461 $disabled[strtolower($f)] = true;
1464 return ( function_exists($function_name)
1465 and ! isset($disabled[strtolower($function_name)])
1472 * This is used for generating ETags.
1474 function hash ($x) {
1475 if (is_scalar($x)) {
1478 elseif (is_array($x)) {
1480 return md5(serialize($x));
1482 elseif (is_object($x)) {
1485 trigger_error("Can't hash $x", E_USER_ERROR);
1490 * Seed the random number generator.
1492 * better_srand() ensures the randomizer is seeded only once.
1494 * How random do you want it? See:
1495 * http://www.php.net/manual/en/function.srand.php
1496 * http://www.php.net/manual/en/function.mt-srand.php
1498 function better_srand($seed = '') {
1499 static $wascalled = FALSE;
1501 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1502 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1504 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1509 * Recursively count all non-empty elements
1510 * in array of any dimension or mixed - i.e.
1511 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1512 * See http://www.php.net/manual/en/function.count.php
1514 function count_all($arg) {
1515 // skip if argument is empty
1517 //print_r($arg); //debugging
1519 // not an array, return 1 (base case)
1522 // else call recursively for all elements $arg
1523 foreach($arg as $key => $val)
1524 $count += count_all($val);
1529 function isSubPage($pagename) {
1530 return (strstr($pagename, SUBPAGE_SEPARATOR));
1533 function subPageSlice($pagename, $pos) {
1534 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1535 $pages = array_slice($pages,$pos,1);
1542 * Class for "popping up" and alert box. (Except that right now, it doesn't
1546 * This is a hackish and needs to be refactored. However it would be nice to
1547 * unify all the different methods we use for showing Alerts and Dialogs.
1548 * (E.g. "Page deleted", login form, ...)
1553 * @param object $request
1554 * @param mixed $head Header ("title") for alert box.
1555 * @param mixed $body The text in the alert box.
1556 * @param hash $buttons An array mapping button labels to URLs.
1557 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1559 function Alert($head, $body, $buttons=false) {
1560 if ($buttons === false)
1563 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1564 $this->_buttons = $buttons;
1568 * Show the alert box.
1573 $tokens = $this->_tokens;
1574 $tokens['BUTTONS'] = $this->_getButtons();
1576 $request->discardOutput();
1577 $tmpl = new Template('dialog', $request, $tokens);
1583 function _getButtons() {
1586 $buttons = $this->_buttons;
1588 $buttons = array(_("Okay") => $request->getURLtoSelf());
1591 foreach ($buttons as $label => $url)
1592 print "$label $url\n";
1593 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1594 return new XmlContent($out);
1599 // 1.3.9-p1 => 1030.091
1600 // 1.3.10pre => 1030.099
1601 // 1.3.11pre-20041120 => 1030.1120041120
1602 function phpwiki_version() {
1603 static $PHPWIKI_VERSION;
1604 if (!isset($PHPWIKI_VERSION)) {
1605 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1606 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1607 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1608 if (strstr(PHPWIKI_VERSION, 'pre'))
1609 $PHPWIKI_VERSION -= 0.01;
1611 return $PHPWIKI_VERSION;
1614 function isWikiWord($word) {
1615 global $WikiNameRegexp;
1616 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1617 return preg_match("/^$WikiNameRegexp\$/",$word);
1620 // needed to store serialized objects-values only (perm, pref)
1621 function obj2hash ($obj, $exclude = false, $fields = false) {
1623 if (! $fields ) $fields = get_object_vars($obj);
1624 foreach ($fields as $key => $val) {
1625 if (is_array($exclude)) {
1626 if (in_array($key,$exclude)) continue;
1634 * isUtf8String($string) - cheap utf-8 detection
1636 * segfaults for strings longer than 10kb!
1637 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1638 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1640 function isUtf8String( $s ) {
1641 $ptrASCII = '[\x00-\x7F]';
1642 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1643 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1644 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1645 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1646 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1647 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1651 * Check for UTF-8 URLs; Internet Explorer produces these if you
1652 * type non-ASCII chars in the URL bar or follow unescaped links.
1653 * Requires urldecoded pagename.
1654 * Fixes sf.net bug #953949
1656 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1658 function fixTitleEncoding( $s ) {
1663 if (empty($s)) return $s;
1665 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1667 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1668 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1670 $isutf = ($ishigh ? isUtf8String($s) : true);
1671 $locharset = strtolower($charset);
1673 if( $locharset != "utf-8" and $ishigh and $isutf )
1674 // if charset == 'iso-8859-1' then simply use utf8_decode()
1675 if ($locharset == 'iso-8859-1')
1676 return utf8_decode( $s );
1678 // TODO: check for iconv support
1679 return iconv( "UTF-8", $charset, $s );
1681 if ($locharset == "utf-8" and $ishigh and !$isutf )
1682 return utf8_encode( $s );
1684 // Other languages can safely leave this function, or replace
1685 // it with one to detect and convert another legacy encoding.
1690 * MySQL fulltext index doesn't grok utf-8, so we
1691 * need to fold cases and convert to hex.
1692 * src: languages/Language.php:stripForSearch() from mediawiki
1695 function stripForSearch( $string ) {
1696 global $wikiLowerChars;
1697 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1698 return preg_replace(
1699 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1700 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1706 * Workaround for allow_url_fopen, to get the content of an external URI.
1707 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1708 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1710 function url_get_contents( $uri ) {
1711 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1712 return @file_get_contents($uri);
1714 require_once("lib/HttpClient.php");
1715 $bits = parse_url($uri);
1716 $host = $bits['host'];
1717 $port = isset($bits['port']) ? $bits['port'] : 80;
1718 $path = isset($bits['path']) ? $bits['path'] : '/';
1719 if (isset($bits['query'])) {
1720 $path .= '?'.$bits['query'];
1722 $client = new HttpClient($host, $port);
1723 $client->use_gzip = false;
1724 if (!$client->get($path)) {
1727 return $client->getContent();
1733 * Generate consecutively named strings:
1734 * Name, Name2, Name3, ...
1736 function GenerateId($name) {
1737 static $ids = array();
1738 if (empty($ids[$name])) {
1743 return $name . $ids[$name];
1747 // from IncludePage. To be of general use.
1748 // content: string or array of strings
1749 function firstNWordsOfContent( $n, $content ) {
1750 if ($content and $n > 0) {
1751 if (is_array($content)) {
1752 // fixme: return a list of lines then?
1753 $content = join("\n", $content);
1754 $return_array = true;
1756 foreach ($content as $line) {
1757 $words = explode(' ', $line);
1758 if ($wordcount + count($words) > $n) {
1759 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1760 . sprintf(_("... (first %s words)"), $n);
1763 $wordcount += count($words);
1769 // fixme: use better whitespace/word seperators
1770 $words = explode(' ', $content);
1771 if (count($words) > $n) {
1772 return join(' ', array_slice($words, 0, $n))
1773 . sprintf(_("... (first %s words)"), $n);
1783 // moved from lib/plugin/IncludePage.php
1784 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1785 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1787 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
1788 . " \\s*$\\n?" // possible blank lines
1789 . " ( (?: ^.*\\n? )*? )" // some lines
1790 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1791 implode("\n", $content),
1793 // Strip trailing blanks lines and ---- <hr>s
1794 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1796 $text = $match[1] . $section ."\n". $text;
1797 return explode("\n", $text);
1800 $mesg = $page ." ". $section;
1803 return array(sprintf(_("<%s: no such section>"), $mesg));
1806 // use this faster version: only load ExternalReferrer if we came from an external referrer
1807 function isExternalReferrer(&$request) {
1808 if ($referrer = $request->get('HTTP_REFERER')) {
1809 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
1810 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
1811 require_once("lib/ExternalReferrer.php");
1812 $se = new SearchEngines();
1813 return $se->parseSearchQuery($referrer);
1819 * useful for PECL overrides: cvsclient, ldap, soap.
1821 function loadPhpExtension($extension) {
1822 if (!extension_loaded($extension)) {
1823 $soname = (isWindows() ? 'php_' : '') . $extension . (isWindows() ? '.dll' : '.so');
1827 return extension_loaded($extension);
1830 function string_starts_with($string, $prefix) {
1831 return (substr($string, 0, strlen($prefix)) == $prefix);
1835 * Ensure that the script will have another $secs time left.
1836 * Works only if safe_mode is off.
1837 * For example not to timeout on waiting socket connections.
1838 * Use the socket timeout as arg.
1840 function longer_timeout($secs = 30) {
1841 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
1842 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
1843 if ($timeleft < $secs)
1844 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
1847 function printSimpleTrace($bt) {
1849 echo "Traceback:\n";
1850 foreach ($bt as $i => $elem) {
1851 if (!array_key_exists('file', $elem)) {
1854 echo join(" ",array_values($elem)),"\n";
1855 //print " " . $elem['file'] . ':' . $elem['line'] . " " .$elem['function']"\n";
1859 // $Log: not supported by cvs2svn $
1860 // Revision 1.226 2004/12/26 17:12:06 rurban
1861 // avoid stdargs in url, php5 fixes
1863 // Revision 1.225 2004/12/22 19:02:29 rurban
1864 // fix glob for starting * or ?
1866 // Revision 1.224 2004/12/20 12:11:50 rurban
1867 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
1868 // not reproducable other than on sf.net, but this seems to fix it.
1870 // Revision 1.223 2004/12/18 16:49:29 rurban
1871 // fix RPC for !USE_PATH_INFO, add debugging helper
1873 // Revision 1.222 2004/12/17 16:40:45 rurban
1874 // add not yet used url helper
1876 // Revision 1.221 2004/12/06 19:49:58 rurban
1877 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
1878 // renamed delete_page to purge_page.
1879 // enable action=edit&version=-1 to force creation of a new version.
1880 // added BABYCART_PATH config
1881 // fixed magiqc in adodb.inc.php
1882 // and some more docs
1884 // Revision 1.220 2004/11/30 17:47:41 rurban
1885 // added mt_srand, check for native isa
1887 // Revision 1.219 2004/11/26 18:39:02 rurban
1888 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1890 // Revision 1.218 2004/11/25 08:28:48 rurban
1893 // Revision 1.217 2004/11/16 17:31:03 rurban
1894 // re-enable old block markup conversion
1896 // Revision 1.216 2004/11/11 18:31:26 rurban
1897 // add simple backtrace on such general failures to get at least an idea where
1899 // Revision 1.215 2004/11/11 14:34:12 rurban
1900 // minor clarifications
1902 // Revision 1.214 2004/11/11 11:01:20 rurban
1903 // fix loadPhpExtension
1905 // Revision 1.213 2004/11/01 10:43:57 rurban
1906 // seperate PassUser methods into seperate dir (memory usage)
1907 // fix WikiUser (old) overlarge data session
1908 // remove wikidb arg from various page class methods, use global ->_dbi instead
1911 // Revision 1.212 2004/10/22 09:15:39 rurban
1912 // Alert::show has no arg anymore
1914 // Revision 1.211 2004/10/22 09:05:11 rurban
1915 // added longer_timeout (HttpClient)
1918 // Revision 1.210 2004/10/14 21:06:02 rurban
1919 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
1921 // Revision 1.209 2004/10/14 19:19:34 rurban
1922 // loadsave: check if the dumped file will be accessible from outside.
1923 // and some other minor fixes. (cvsclient native not yet ready)
1925 // Revision 1.208 2004/10/12 13:13:20 rurban
1926 // php5 compatibility (5.0.1 ok)
1928 // Revision 1.207 2004/09/26 12:21:40 rurban
1929 // removed old log entries.
1930 // added persistent start_debug on internal links and DEBUG
1931 // added isExternalReferrer (not yet used)
1933 // Revision 1.206 2004/09/25 16:28:36 rurban
1934 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
1936 // Revision 1.205 2004/09/23 13:59:35 rurban
1937 // Before removing a page display a sample of 100 words.
1939 // Revision 1.204 2004/09/17 13:19:15 rurban
1940 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
1943 // Revision 1.203 2004/09/16 08:00:52 rurban
1944 // just some comments
1946 // Revision 1.202 2004/09/14 10:11:44 rurban
1947 // start 2nd Id with ...Plugin2
1949 // Revision 1.201 2004/09/14 10:06:42 rurban
1950 // generate iterated plugin ids, set plugin span id also
1952 // Revision 1.200 2004/08/05 17:34:26 rurban
1953 // move require to sortby branch
1955 // Revision 1.199 2004/08/05 10:38:15 rurban
1956 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
1959 // Revision 1.198 2004/07/02 10:30:36 rurban
1960 // always disable getimagesize for < php-4.3 with external png's
1962 // Revision 1.197 2004/07/02 09:55:58 rurban
1963 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
1965 // Revision 1.196 2004/07/01 08:51:22 rurban
1966 // dumphtml: added exclude, print pagename before processing
1968 // Revision 1.195 2004/06/29 08:52:22 rurban
1969 // Use ...version() $need_content argument in WikiDB also:
1970 // To reduce the memory footprint for larger sets of pagelists,
1971 // we don't cache the content (only true or false) and
1972 // we purge the pagedata (_cached_html) also.
1973 // _cached_html is only cached for the current pagename.
1974 // => Vastly improved page existance check, ACL check, ...
1976 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1978 // Revision 1.194 2004/06/29 06:48:04 rurban
1979 // Improve LDAP auth and GROUP_LDAP membership:
1980 // no error message on false password,
1981 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
1982 // fixed two group queries (this -> user)
1983 // stdlib: ConvertOldMarkup still flawed
1985 // Revision 1.193 2004/06/28 13:27:03 rurban
1986 // CreateToc disabled for old markup and Apache2 only
1988 // Revision 1.192 2004/06/28 12:47:43 rurban
1989 // skip if non-DEBUG and old markup with CreateToc
1991 // Revision 1.191 2004/06/25 14:31:56 rurban
1992 // avoid debug_skip warning
1994 // Revision 1.190 2004/06/25 14:29:20 rurban
1995 // WikiGroup refactoring:
1996 // global group attached to user, code for not_current user.
1997 // improved helpers for special groups (avoid double invocations)
1998 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1999 // fixed a XHTML validation error on userprefs.tmpl
2001 // Revision 1.189 2004/06/20 09:45:35 rurban
2002 // php5 isa fix (wrong strtolower)
2004 // Revision 1.188 2004/06/16 10:38:58 rurban
2005 // Disallow refernces in calls if the declaration is a reference
2006 // ("allow_call_time_pass_reference clean").
2007 // PhpWiki is now allow_call_time_pass_reference = Off clean,
2008 // but several external libraries may not.
2009 // In detail these libs look to be affected (not tested):
2013 // Revision 1.187 2004/06/14 11:31:37 rurban
2014 // renamed global $Theme to $WikiTheme (gforge nameclash)
2015 // inherit PageList default options from PageList
2016 // default sortby=pagename
2017 // use options in PageList_Selectable (limit, sortby, ...)
2018 // added action revert, with button at action=diff
2019 // added option regex to WikiAdminSearchReplace
2021 // Revision 1.186 2004/06/13 13:54:25 rurban
2022 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2023 // FoafViewer: Check against external requirements, instead of fatal.
2024 // Change output for xhtmldumps: using file:// urls to the local fs.
2025 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2026 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2028 // Revision 1.185 2004/06/11 09:07:30 rurban
2029 // support theme-specific LinkIconAttr: front or after or none
2031 // Revision 1.184 2004/06/04 20:32:53 rurban
2032 // Several locale related improvements suggested by Pierrick Meignen
2033 // LDAP fix by John Cole
2034 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2036 // Revision 1.183 2004/06/01 10:22:56 rurban
2037 // added url_get_contents() used in XmlParser and elsewhere
2039 // Revision 1.182 2004/05/25 12:40:48 rurban
2040 // trim the pagename
2042 // Revision 1.181 2004/05/25 10:18:44 rurban
2043 // Check for UTF-8 URLs; Internet Explorer produces these if you
2044 // type non-ASCII chars in the URL bar or follow unescaped links.
2045 // Fixes sf.net bug #953949
2046 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2048 // Revision 1.180 2004/05/18 16:23:39 rurban
2049 // rename split_pagename to SplitPagename
2051 // Revision 1.179 2004/05/18 16:18:37 rurban
2052 // AutoSplit at subpage seperators
2053 // RssFeed stability fix for empty feeds or broken connections
2055 // Revision 1.178 2004/05/12 10:49:55 rurban
2056 // require_once fix for those libs which are loaded before FileFinder and
2057 // its automatic include_path fix, and where require_once doesn't grok
2058 // dirname(__FILE__) != './lib'
2059 // upgrade fix with PearDB
2060 // navbar.tmpl: remove spaces for IE button alignment
2062 // Revision 1.177 2004/05/08 14:06:12 rurban
2063 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2064 // minor stability and portability fixes
2066 // Revision 1.176 2004/05/08 11:25:15 rurban
2069 // Revision 1.175 2004/05/06 17:30:38 rurban
2070 // CategoryGroup: oops, dos2unix eol
2071 // improved phpwiki_version:
2072 // pre -= .0001 (1.3.10pre: 1030.099)
2073 // -p1 += .001 (1.3.9-p1: 1030.091)
2074 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2075 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2076 // backend->backendType(), backend->database(),
2077 // backend->listOfFields(),
2078 // backend->listOfTables(),
2080 // Revision 1.174 2004/05/06 12:02:05 rurban
2081 // fix sf.net bug#949002: [ Link | ] assertion
2083 // Revision 1.173 2004/05/03 15:00:31 rurban
2084 // added more database upgrading: session.sess_ip, page.id autp_increment
2086 // Revision 1.172 2004/04/26 20:44:34 rurban
2087 // locking table specific for better databases
2089 // Revision 1.171 2004/04/19 23:13:03 zorloc
2090 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
2092 // Revision 1.170 2004/04/19 18:27:45 rurban
2093 // Prevent from some PHP5 warnings (ref args, no :: object init)
2094 // php5 runs now through, just one wrong XmlElement object init missing
2095 // Removed unneccesary UpgradeUser lines
2096 // Changed WikiLink to omit version if current (RecentChanges)
2098 // Revision 1.169 2004/04/15 21:29:48 rurban
2099 // allow [0] with new markup: link to page "0"
2101 // Revision 1.168 2004/04/10 02:30:49 rurban
2102 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2103 // Fixed "cannot setlocale..." (sf.net problem)
2105 // Revision 1.167 2004/04/02 15:06:55 rurban
2106 // fixed a nasty ADODB_mysql session update bug
2107 // improved UserPreferences layout (tabled hints)
2108 // fixed UserPreferences auth handling
2109 // improved auth stability
2110 // improved old cookie handling: fixed deletion of old cookies with paths
2112 // Revision 1.166 2004/04/01 15:57:10 rurban
2113 // simplified Sidebar theme: table, not absolute css positioning
2114 // added the new box methods.
2115 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2117 // Revision 1.165 2004/03/24 19:39:03 rurban
2118 // php5 workaround code (plus some interim debugging code in XmlElement)
2119 // php5 doesn't work yet with the current XmlElement class constructors,
2120 // WikiUserNew does work better than php4.
2121 // rewrote WikiUserNew user upgrading to ease php5 update
2122 // fixed pref handling in WikiUserNew
2123 // added Email Notification
2124 // added simple Email verification
2125 // removed emailVerify userpref subclass: just a email property
2126 // changed pref binary storage layout: numarray => hash of non default values
2127 // print optimize message only if really done.
2128 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2129 // prefs should be stored in db or homepage, besides the current session.
2131 // Revision 1.164 2004/03/18 21:41:09 rurban
2132 // fixed sqlite support
2133 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2135 // Revision 1.163 2004/03/17 18:41:49 rurban
2136 // just reformatting
2138 // Revision 1.162 2004/03/16 15:43:08 rurban
2139 // make fileSet sortable to please PageList
2141 // Revision 1.161 2004/03/12 15:48:07 rurban
2142 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2143 // simplified lib/stdlib.php:explodePageList
2145 // Revision 1.160 2004/02/28 21:14:08 rurban
2146 // generally more PHPDOC docs
2147 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2148 // fxied WikiUserNew pref handling: empty theme not stored, save only
2149 // changed prefs, sql prefs improved, fixed password update,
2150 // removed REPLACE sql (dangerous)
2151 // moved gettext init after the locale was guessed
2152 // + some minor changes
2155 // (c-file-style: "gnu")
2159 // c-basic-offset: 4
2160 // c-hanging-comment-ender-p: nil
2161 // indent-tabs-mode: nil