1 <?php //rcs_id('$Id: stdlib.php,v 1.222 2004-12-17 16:40:45 rurban 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 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
160 $enc_args[] = urlencode($key) . '=' . urlencode($val);
162 $args = join('&', $enc_args);
165 if (USE_PATH_INFO or !empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX)) {
166 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
167 $url = $url . preg_replace('/%2f/i', '/', rawurlencode($pagename));
168 if (!empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX))
169 $url .= $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
174 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
175 $url .= "?pagename=" . rawurlencode($pagename);
180 $url .= "#" . MangleXmlIdentifier($anchor);
184 /** Convert relative URL to absolute URL.
186 * This converts a relative URL to one of PhpWiki's support files
187 * to an absolute one.
190 * @return string Absolute URL
192 function AbsoluteURL ($url) {
193 if (preg_match('/^https?:/', $url))
195 if ($url[0] != '/') {
196 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
197 while ($base != '/' and substr($url, 0, 3) == "../") {
198 $url = substr($url, 3);
199 $base = dirname($base);
205 return SERVER_URL . $url;
208 /*function DataURL ($url) {
209 if (preg_match('/^https?:/', $url))
211 return AbsoluteURL(NormalizeWebFileName($url));
215 * Generates icon in front of links.
217 * @param string $protocol_or_url URL or protocol to determine which icon to use.
219 * @return HtmlElement HtmlElement object that contains data to create img link to
220 * icon for use with url or protocol passed to the function. False if no img to be
223 function IconForLink($protocol_or_url) {
225 if (0 and $filename_suffix == false) {
226 // display apache style icon for file type instead of protocol icon
227 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
228 // - document: html, htm, text, txt, rtf, pdf, doc
229 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
230 // - audio: mp3,mp2,aiff,aif,au
231 // - multimedia: mpeg,mpg,mov,qt
233 list ($proto) = explode(':', $protocol_or_url, 2);
234 $src = $WikiTheme->getLinkIconURL($proto);
236 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
243 * Glue icon in front of or after text.
244 * Pref: 'noLinkIcons' - ignore icon if set
245 * Theme: 'LinkIcons' - 'yes' at front
246 * - 'no' display no icon
247 * - 'front' display at left
248 * - 'after' display at right
250 * @param string $protocol_or_url Protocol or URL. Used to determine the
252 * @param string $text The text.
253 * @return XmlContent.
255 function PossiblyGlueIconToText($proto_or_url, $text) {
256 global $request, $WikiTheme;
257 if ($request->getPref('noLinkIcons'))
259 $icon = IconForLink($proto_or_url);
262 if ($where = $WikiTheme->getLinkIconAttr()) {
263 if ($where == 'no') return $text;
264 if ($where != 'after') $where = 'front';
268 if ($where == 'after') {
269 // span the icon only to the last word (tie them together),
270 // to let the previous words wrap on line breaks.
271 if (!is_object($text)) {
272 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
273 list (, $prefix, $last_word) = $m;
279 $text = HTML::span(array('style' => 'white-space: nowrap'),
280 $last_word, HTML::Raw(' '), $icon);
282 $text = HTML($prefix, $text);
285 // span the icon only to the first word (tie them together),
286 // to let the next words wrap on line breaks
287 if (!is_object($text)) {
288 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
289 list (, $first_word, $tail) = $m;
295 $text = HTML::span(array('style' => 'white-space: nowrap'),
298 $text = HTML($text, $tail);
303 * Determines if the url passed to function is safe, by detecting if the characters
304 * '<', '>', or '"' are present.
306 * @param string $url URL to check for unsafe characters.
307 * @return boolean True if same, false else.
309 function IsSafeURL($url) {
310 return !preg_match('/[<>"]/', $url);
314 * Generates an HtmlElement object to store data for a link.
316 * @param string $url URL that the link will point to.
317 * @param string $linktext Text to be displayed as link.
318 * @return HtmlElement HtmlElement object that contains data to construct an html link.
320 function LinkURL($url, $linktext = '') {
321 // FIXME: Is this needed (or sufficient?)
322 if(! IsSafeURL($url)) {
323 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
324 _("BAD URL -- remove all of <, >, \"")));
328 $linktext = preg_replace("/mailto:/A", "", $url);
330 $link = HTML::a(array('href' => $url),
331 PossiblyGlueIconToText($url, $linktext));
334 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
339 * FIXME: disallow sizes which are too small.
340 * Spammers may use such (typically invisible) image attributes to higher their GoogleRank.
342 function LinkImage($url, $alt = false) {
343 // FIXME: Is this needed (or sufficient?)
344 if(! IsSafeURL($url)) {
345 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
346 _("BAD URL -- remove all of <, >, \"")));
348 // support new syntax: [image.jpg size=50% border=n]
349 $arr = split(' ',$url);
350 if (count($arr) > 1) {
353 if (empty($alt)) $alt = basename($url);
354 $link = HTML::img(array('src' => $url, 'alt' => $alt));
355 if (count($arr) > 1) {
357 foreach ($arr as $attr) {
358 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
359 $link->setAttr('width',$m[1]);
360 $link->setAttr('height',$m[1]);
362 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
363 $link->setAttr('width',$m[1]);
364 $link->setAttr('height',$m[2]);
366 if (preg_match('/^border=(\d+)$/',$attr,$m))
367 $link->setAttr('border',$m[1]);
368 if (preg_match('/^align=(\w+)$/',$attr,$m))
369 $link->setAttr('align',$m[1]);
370 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
371 $link->setAttr('hspace',$m[1]);
372 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
373 $link->setAttr('vspace',$m[1]);
376 // check width and height as spam countermeasure
377 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
378 //$width = (int) $width; // px or % or other suffix
379 //$height = (int) $height;
380 if (($width < 3 and $height < 10) or
381 ($height < 3 and $width < 20) or
382 ($height < 7 and $width < 7))
384 trigger_error(_("Invalid image size"), E_USER_NOTICE);
388 // Older php versions crash here with certain png's:
389 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
390 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
391 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
392 if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
393 ; // it's safe to assume that this will fail.
394 elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
397 if (($width < 3 and $height < 10)
398 or ($height < 3 and $width < 20)
399 or ($height < 7 and $width < 7))
401 trigger_error(_("Invalid image size"), E_USER_NOTICE);
407 $link->setAttr('class', 'inlineimage');
415 // var in php5 deprecated
417 $this->items = array();
420 function push($item) {
421 $this->items[$this->size] = $item;
427 if ($this->size == 0) {
428 return false; // stack is empty
431 return $this->items[$this->size];
440 return $this->items[$this->size - 1];
446 // end class definition
448 function SplitQueryArgs ($query_args = '')
450 $split_args = split('&', $query_args);
452 while (list($key, $val) = each($split_args))
453 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
454 $args[$m[1]] = $m[2];
458 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
461 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
462 return HTML::strong(array('class' => 'rawurl'),
463 HTML::u(array('class' => 'baduri'),
464 _("BAD phpwiki: URL")));
468 $pagename = urldecode($m[1]);
471 if (empty($pagename) &&
472 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
473 // Convert old style links (to not break diff links in
475 $pagename = urldecode($m[2]);
476 $args = array("action" => $m[1]);
479 $args = SplitQueryArgs($qargs);
482 if (empty($pagename))
483 $pagename = $GLOBALS['request']->getArg('pagename');
485 if (isset($args['action']) && $args['action'] == 'browse')
486 unset($args['action']);
489 if (empty($args['action']))
491 else if (is_safe_action($args['action']))
492 $class = 'wikiaction';
494 if (empty($args['action']) || is_safe_action($args['action']))
495 $class = 'wikiaction';
497 // Don't allow administrative links on unlocked pages.
498 $dbi = $GLOBALS['request']->getDbh();
499 $page = $dbi->getPage($basepage ? $basepage : $pagename);
500 if (!$page->get('locked'))
501 return HTML::span(array('class' => 'wikiunsafe'),
502 HTML::u(_("Lock page to enable link")));
503 $class = 'wikiadmin';
507 $text = HTML::span(array('class' => 'rawurl'), $url);
509 $wikipage = new WikiPageName($pagename);
510 if (!$wikipage->isValid()) {
512 return $WikiTheme->linkBadWikiWord($wikipage, $url);
515 return HTML::a(array('href' => WikiURL($pagename, $args),
521 * A class to assist in parsing wiki pagenames.
523 * Now with subpages and anchors, parsing and passing around
524 * pagenames is more complicated. This should help.
528 /** Short name for page.
530 * This is the value of $name passed to the constructor.
531 * (For use, e.g. as a default label for links to the page.)
535 /** The full page name.
537 * This is the full name of the page (without anchor).
543 * This is the referenced anchor within the page, or the empty string.
549 * @param mixed $name Page name.
550 * WikiDB_Page, WikiDB_PageRevision, or string.
551 * This can be a relative subpage name (like '/SubPage'),
552 * or can be the empty string to refer to the $basename.
554 * @param string $anchor For links to anchors in page.
556 * @param mixed $basename Page name from which to interpret
557 * relative or other non-fully-specified page names.
559 function WikiPageName($name, $basename=false, $anchor=false) {
560 if (is_string($name)) {
561 $this->shortName = $name;
563 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
565 $name = $this->_pagename($basename) . $name;
567 $name = $this->_normalize_bad_pagename($name);
571 $name = $this->_pagename($name);
572 $this->shortName = $name;
575 $this->name = $this->_check($name);
576 $this->anchor = (string)$anchor;
579 function getParent() {
581 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
583 return substr($name, 0, -strlen($tail));
586 function isValid($strict = false) {
588 return !isset($this->_errors);
589 return (is_string($this->name) and $this->name != '');
592 function getWarnings() {
594 if (isset($this->_warnings))
595 $warnings = array_merge($warnings, $this->_warnings);
596 if (isset($this->_errors))
597 $warnings = array_merge($warnings, $this->_errors);
601 return sprintf(_("'%s': Bad page name: %s"),
602 $this->shortName, join(', ', $warnings));
605 function _pagename($page) {
606 if (isa($page, 'WikiDB_Page'))
607 return $page->getName();
608 elseif (isa($page, 'WikiDB_PageRevision'))
609 return $page->getPageName();
610 elseif (isa($page, 'WikiPageName'))
612 if (!is_string($page)) {
613 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
614 $page, gettype($page), get_class($page)),
617 //assert(is_string($page));
621 function _normalize_bad_pagename($name) {
622 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
624 // Punt... You really shouldn't get here.
627 return $request->getArg('pagename');
629 assert($name[0] == SUBPAGE_SEPARATOR);
630 return substr($name, 1);
634 function _check($pagename) {
635 // Compress internal white-space to single space character.
636 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
637 if ($pagename != $orig)
638 $this->_warnings[] = _("White space converted to single space");
640 // Delete any control characters.
641 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
642 if ($pagename != $orig)
643 $this->_errors[] = _("Control characters not allowed");
645 // Strip leading and trailing white-space.
646 $pagename = trim($pagename);
649 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
650 $pagename = substr($pagename, 1);
651 if ($pagename != $orig)
652 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
654 if (preg_match('/[:;]/', $pagename)) {
655 $this->_warnings[] = _("';' and ':' are deprecated");
656 $pagename = str_replace(':', '', $pagename);
657 $pagename = str_replace(';', '', $pagename);
660 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
661 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
662 $this->_errors[] = _("too long");
665 if (strstr($pagename, '..')) {
666 $this->_warnings[] = sprintf(_("illegal .. removed"), $pagename);
667 $pagename = str_replace('..', '', $pagename);
675 * Convert old page markup to new-style markup.
677 * @param string $text Old-style wiki markup.
679 * @param string $markup_type
681 * <dt><code>"block"</code> <dd>Convert all markup.
682 * <dt><code>"inline"</code> <dd>Convert only inline markup.
683 * <dt><code>"links"</code> <dd>Convert only link markup.
686 * @return string New-style wiki markup.
688 * @bugs Footnotes don't work quite as before (esp if there are
689 * multiple references to the same footnote. But close enough,
690 * probably for now....
691 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
692 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
693 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
694 * also known to crash, even with Apache1.
696 function ConvertOldMarkup ($text, $markup_type = "block") {
702 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
703 // AnciennesR%E8glesDeFormatage crashes.
704 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
705 // also known to crash, even with Apache1.
707 // I suspect this only to crash with Apache2 and IIS.
708 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
709 and preg_match("/plugin CreateToc/", $text))
711 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
712 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
713 ._("Skipped."), E_USER_WARNING);
715 //if (!DEBUG) return $text;
720 /*****************************************************************
721 * Conversions for inline markup:
728 // escape escaped brackets
732 // change ! escapes to ~'s.
733 global $WikiNameRegexp, $request;
734 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
735 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
736 if (check_php_version(4,3,9)) {
737 $map = getInterwikiMap();
738 if ($map_regex = $map->getRegexp())
739 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
741 $bang_esc[] = $WikiNameRegexp;
742 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
745 $subs["links"] = array($orig, $repl);
748 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
751 // Convert footnote references.
752 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
753 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
755 // Convert old style emphases to HTML style emphasis.
756 $orig[] = '/__(.*?)__/';
757 $repl[] = '<strong>\\1</strong>';
758 $orig[] = "/''(.*?)''/";
759 $repl[] = '<em>\\1</em>';
761 // Escape nestled markup.
762 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
765 // in old markup headings only allowed at beginning of line
769 $subs["inline"] = array($orig, $repl);
771 /*****************************************************************
772 * Patterns which match block markup constructs which take
773 * special handling...
777 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
779 $blockpats[] = '\|(?:.*\n\|)*';
782 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
784 // Footnote definitions
785 $blockpats[] = '\[\s*(\d+)\s*\]';
789 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
793 $blockpats[] = '!{1,3}[^!]';
795 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
796 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
798 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
799 . join("|", $blockpats)
804 if ($markup_type != "block") {
805 list ($orig, $repl) = $subs[$markup_type];
806 return preg_replace($orig, $repl, $text);
809 list ($orig, $repl) = $subs['inline'];
812 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
813 // AnciennesR%E8glesDeFormatage and more
814 // See http://www.pcre.org/pcre.txt LIMITATIONS
815 while (preg_match($block_re, $text, $m)) {
816 $text = substr($text, strlen($m[0]));
817 list (,$leading_text, $block) = $m;
820 if (strchr(" \t", $block[0])) {
823 $suffix = "\n</pre>\n";
825 elseif ($block[0] == '|') {
827 $prefix = "<?plugin OldStyleTable\n";
830 elseif (strchr("#*;", $block[0])) {
831 // Old-style list item
832 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
833 list (,$ind,$bullet) = $m;
834 $block = substr($block, strlen($m[0]));
836 $indent = str_repeat(' ', strlen($ind));
837 if ($bullet[0] == ';') {
838 //$term = ltrim(substr($bullet, 1));
839 //return $indent . $term . "\n" . $indent . ' ';
840 $prefix = $ind . $bullet;
843 $prefix = $indent . $bullet . ' ';
845 elseif ($block[0] == '[') {
846 // Footnote definition
847 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
849 $block = substr($block, strlen($m[0]));
850 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
852 elseif ($block[0] == '<') {
854 // HACK: no inline markup...
858 elseif ($block[0] == '!') {
860 preg_match('/^!{1,3}/', $block, $m);
862 $block = substr($block, strlen($m[0]));
868 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
869 if ($block) $block = preg_replace($orig, $repl, $block);
870 $out .= $leading_text;
875 return $out . preg_replace($orig, $repl, $text);
881 * Expand tabs in string.
883 * Converts all tabs to (the appropriate number of) spaces.
886 * @param integer $tab_width
889 function expand_tabs($str, $tab_width = 8) {
890 $split = split("\t", $str);
891 $tail = array_pop($split);
893 foreach ($split as $hunk) {
895 $pos = strlen(strrchr($expanded, "\n")) - 1;
896 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
898 return substr($expanded, 1) . $tail;
902 * Split WikiWords in page names.
904 * It has been deemed useful to split WikiWords (into "Wiki Words") in
905 * places like page titles. This is rumored to help search engines
908 * @param $page string The page name.
910 * @return string The split name.
912 function SplitPagename ($page) {
914 if (preg_match("/\s/", $page))
915 return $page; // Already split --- don't split any more.
917 // This algorithm is specialized for several languages.
918 // (Thanks to Pierrick MEIGNEN)
919 // Improvements for other languages welcome.
922 // This mess splits between a lower-case letter followed by
923 // either an upper-case or a numeral; except that it wont
924 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
925 switch ($GLOBALS['LANG']) {
930 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
933 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
936 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
937 // This the single-letter words 'I' and 'A' from any following
938 // capitalized words.
939 switch ($GLOBALS['LANG']) {
941 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
944 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
947 // Split numerals from following letters.
948 $RE[] = '/(\d)([[:alpha:]])/';
949 // Split at subpage seperators. TBD in Theme.php
950 $RE[] = "/([^${sep}]+)(${sep})/";
952 foreach ($RE as $key)
953 $RE[$key] = pcre_fix_posix_classes($key);
956 foreach ($RE as $regexp) {
957 $page = preg_replace($regexp, '\\1 \\2', $page);
962 function NoSuchRevision (&$request, $page, $version) {
963 $html = HTML(HTML::h2(_("Revision Not Found")),
964 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
965 $version, WikiLink($page, 'auto'))));
966 include_once('lib/Template.php');
967 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
973 * Get time offset for local time zone.
975 * @param $time time_t Get offset for this time. Default: now.
976 * @param $no_colon boolean Don't put colon between hours and minutes.
977 * @return string Offset as a string in the format +HH:MM.
979 function TimezoneOffset ($time = false, $no_colon = false) {
982 $secs = date('Z', $time);
991 $colon = $no_colon ? '' : ':';
992 $mins = intval(($secs + 30) / 60);
993 return sprintf("%s%02d%s%02d",
994 $sign, $mins / 60, $colon, $mins % 60);
999 * Format time in ISO-8601 format.
1001 * @param $time time_t Time. Default: now.
1002 * @return string Date and time in ISO-8601 format.
1004 function Iso8601DateTime ($time = false) {
1005 if ($time === false)
1007 $tzoff = TimezoneOffset($time);
1008 $date = date('Y-m-d', $time);
1009 $time = date('H:i:s', $time);
1010 return $date . 'T' . $time . $tzoff;
1014 * Format time in RFC-2822 format.
1016 * @param $time time_t Time. Default: now.
1017 * @return string Date and time in RFC-2822 format.
1019 function Rfc2822DateTime ($time = false) {
1020 if ($time === false)
1022 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1026 * Format time in RFC-1123 format.
1028 * @param $time time_t Time. Default: now.
1029 * @return string Date and time in RFC-1123 format.
1031 function Rfc1123DateTime ($time = false) {
1032 if ($time === false)
1034 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1037 /** Parse date in RFC-1123 format.
1039 * According to RFC 1123 we must accept dates in the following
1042 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1043 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1044 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1046 * (Though we're only allowed to generate dates in the first format.)
1048 function ParseRfc1123DateTime ($timestr) {
1049 $timestr = trim($timestr);
1050 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1051 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1053 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1055 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1056 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1058 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1059 if ($year < 70) $year += 2000;
1060 elseif ($year < 100) $year += 1900;
1062 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1063 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1065 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1072 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1074 return false; // failed
1079 * Format time to standard 'ctime' format.
1081 * @param $time time_t Time. Default: now.
1082 * @return string Date and time.
1084 function CTime ($time = false)
1086 if ($time === false)
1088 return date("D M j H:i:s Y", $time);
1093 * Format number as kilobytes or bytes.
1094 * Short format is used for PageList
1095 * Long format is used in PageInfo
1097 * @param $bytes int. Default: 0.
1098 * @param $longformat bool. Default: false.
1099 * @return class FormattedText (XmlElement.php).
1101 function ByteFormatter ($bytes = 0, $longformat = false) {
1104 if ($bytes < 1024) {
1106 $size = fmt("%s b", $bytes);
1108 $size = fmt("%s bytes", $bytes);
1111 $kb = round($bytes / 1024, 1);
1113 $size = fmt("%s k", $kb);
1115 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1121 * Internationalized printf.
1123 * This is essentially the same as PHP's built-in printf
1124 * with the following exceptions:
1126 * <li> It passes the format string through gettext().
1127 * <li> It supports the argument reordering extensions.
1134 * __printf("Differences between versions %s and %s of %s",
1135 * $new_link, $old_link, $page_link);
1138 * Then in locale/po/de.po, one can reorder the printf arguments:
1141 * msgid "Differences between %s and %s of %s."
1142 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1145 * (Note that while PHP tries to expand $vars within double-quotes,
1146 * the values in msgstr undergo no such expansion, so the '$'s
1149 * One shouldn't use reordered arguments in the default format string.
1150 * Backslashes in the default string would be necessary to escape the
1151 * '$'s, and they'll cause all kinds of trouble....
1153 function __printf ($fmt) {
1154 $args = func_get_args();
1156 echo __vsprintf($fmt, $args);
1160 * Internationalized sprintf.
1162 * This is essentially the same as PHP's built-in printf with the
1163 * following exceptions:
1166 * <li> It passes the format string through gettext().
1167 * <li> It supports the argument reordering extensions.
1172 function __sprintf ($fmt) {
1173 $args = func_get_args();
1175 return __vsprintf($fmt, $args);
1179 * Internationalized vsprintf.
1181 * This is essentially the same as PHP's built-in printf with the
1182 * following exceptions:
1185 * <li> It passes the format string through gettext().
1186 * <li> It supports the argument reordering extensions.
1191 function __vsprintf ($fmt, $args) {
1192 $fmt = gettext($fmt);
1193 // PHP's sprintf doesn't support variable with specifiers,
1194 // like sprintf("%*s", 10, "x"); --- so we won't either.
1196 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1197 // Format string has '%2$s' style argument reordering.
1198 // PHP doesn't support this.
1199 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1200 // literal variable name substitution only to keep locale
1201 // strings uncluttered
1202 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1203 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1205 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1208 // Reorder arguments appropriately.
1209 foreach($m[1] as $argnum) {
1210 if ($argnum < 1 || $argnum > count($args))
1211 trigger_error(sprintf(_("%s: argument index out of range"),
1212 $argnum), E_USER_WARNING);
1213 $newargs[] = $args[$argnum - 1];
1218 // Not all PHP's have vsprintf, so...
1219 array_unshift($args, $fmt);
1220 return call_user_func_array('sprintf', $args);
1223 function file_mtime ($filename) {
1224 if ($stat = @stat($filename))
1230 function sort_file_mtime ($a, $b) {
1231 $ma = file_mtime($a);
1232 $mb = file_mtime($b);
1233 if (!$ma or !$mb or $ma == $mb) return 0;
1234 return ($ma > $mb) ? -1 : 1;
1239 * Build an array in $this->_fileList of files from $dirname.
1240 * Subdirectories are not traversed.
1242 * (This was a function LoadDir in lib/loadsave.php)
1243 * See also http://www.php.net/manual/en/function.readdir.php
1245 function getFiles($exclude=false, $sortby=false, $limit=false) {
1246 $list = $this->_fileList;
1249 require_once('lib/PageList.php');
1250 switch (Pagelist::sortby($sortby, 'db')) {
1251 case 'pagename ASC': break;
1252 case 'pagename DESC':
1253 $list = array_reverse($list);
1256 usort($list,'sort_file_mtime');
1259 usort($list,'sort_file_mtime');
1260 $list = array_reverse($list);
1265 return array_splice($list, 0, $limit);
1269 function _filenameSelector($filename) {
1270 if (! $this->_pattern)
1273 return glob_match ($this->_pattern, $filename, $this->_case);
1277 function fileSet($directory, $filepattern = false) {
1278 $this->_fileList = array();
1279 $this->_pattern = $filepattern;
1280 $this->_case = !isWindows();
1281 $this->_pathsep = '/';
1283 if (empty($directory)) {
1284 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1286 return; // early return
1289 @ $dir_handle = opendir($dir=$directory);
1290 if (empty($dir_handle)) {
1291 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1292 $dir), E_USER_NOTICE);
1293 return; // early return
1296 while ($filename = readdir($dir_handle)) {
1297 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1299 if ($this->_filenameSelector($filename)) {
1300 array_push($this->_fileList, "$filename");
1301 //trigger_error(sprintf(_("found file %s"), $filename),
1302 // E_USER_NOTICE); //debugging
1305 closedir($dir_handle);
1311 // expands a list containing regex's to its matching entries
1312 class ListRegexExpand {
1313 //var $match, $list, $index, $case_sensitive;
1314 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1315 $this->match = str_replace('/','\/',$match);
1316 $this->list = &$list;
1317 $this->case_sensitive = $case_sensitive;
1318 //$this->index = false;
1320 function listMatchCallback ($item, $key) {
1321 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1322 unset($this->list[$this->index]);
1323 $this->list[] = $item;
1326 function expandRegex ($index, &$pages) {
1327 $this->index = $index;
1328 array_walk($pages, array($this, 'listMatchCallback'));
1333 // convert fileglob to regex style
1334 function glob_to_pcre ($glob) {
1335 $re = preg_replace('/\./', '\\.', $glob);
1336 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1337 if (!preg_match('/^[\?\*]/',$glob))
1339 if (!preg_match('/[\?\*]$/',$glob))
1344 function glob_match ($glob, $against, $case_sensitive = true) {
1345 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1348 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1349 $list = explode(',',$input);
1350 // expand wildcards from list of $allnames
1351 if (preg_match('/[\?\*]/',$input)) {
1352 // Optimizing loop invariants:
1353 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1354 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1356 if (preg_match('/[\?\*]/',$f)) {
1358 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1359 $expand->expandRegex($i, $allnames);
1366 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1367 function explodePageList($input, $include_empty=false, $sortby='pagename', $limit=false, $exclude=false) {
1368 include_once("lib/PageList.php");
1369 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1372 // Class introspections
1375 * Determine whether object is of a specified type.
1376 * In PHP builtin since 4.2.0 as is_a()
1378 * @param $object object An object.
1379 * @param $class string Class name.
1380 * @return bool True iff $object is a $class
1381 * or a sub-type of $class.
1383 function isa ($object, $class) {
1384 if (check_php_version(4,2))
1385 return is_a($object, $class);
1387 $lclass = strtolower($class);
1388 return is_object($object)
1389 && ( strtolower(get_class($object)) == $lclass
1390 || is_subclass_of($object, $lclass) );
1393 /** Determine whether (possible) object has method.
1395 * @param $object mixed Object
1396 * @param $method string Method name
1397 * @return bool True iff $object is an object with has method $method.
1399 function can ($object, $method) {
1400 return is_object($object) && method_exists($object, strtolower($method));
1403 /** Determine whether a function is okay to use.
1405 * Some providers (e.g. Lycos) disable some of PHP functions for
1406 * "security reasons." This makes those functions, of course,
1407 * unusable, despite the fact the function_exists() says they
1410 * This function test to see if a function exists and is not
1411 * disallowed by PHP's disable_functions config setting.
1413 * @param string $function_name Function name
1414 * @return bool True iff function can be used.
1416 function function_usable($function_name) {
1418 if (!is_array($disabled)) {
1419 $disabled = array();
1420 // Use get_cfg_var since ini_get() is one of the disabled functions
1421 // (on Lycos, at least.)
1422 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1423 foreach ($split as $f)
1424 $disabled[strtolower($f)] = true;
1427 return ( function_exists($function_name)
1428 and ! isset($disabled[strtolower($function_name)])
1435 * This is used for generating ETags.
1437 function hash ($x) {
1438 if (is_scalar($x)) {
1441 elseif (is_array($x)) {
1443 return md5(serialize($x));
1445 elseif (is_object($x)) {
1448 trigger_error("Can't hash $x", E_USER_ERROR);
1453 * Seed the random number generator.
1455 * better_srand() ensures the randomizer is seeded only once.
1457 * How random do you want it? See:
1458 * http://www.php.net/manual/en/function.srand.php
1459 * http://www.php.net/manual/en/function.mt-srand.php
1461 function better_srand($seed = '') {
1462 static $wascalled = FALSE;
1464 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1465 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1467 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1472 * Recursively count all non-empty elements
1473 * in array of any dimension or mixed - i.e.
1474 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1475 * See http://www.php.net/manual/en/function.count.php
1477 function count_all($arg) {
1478 // skip if argument is empty
1480 //print_r($arg); //debugging
1482 // not an array, return 1 (base case)
1485 // else call recursively for all elements $arg
1486 foreach($arg as $key => $val)
1487 $count += count_all($val);
1492 function isSubPage($pagename) {
1493 return (strstr($pagename, SUBPAGE_SEPARATOR));
1496 function subPageSlice($pagename, $pos) {
1497 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1498 $pages = array_slice($pages,$pos,1);
1505 * Class for "popping up" and alert box. (Except that right now, it doesn't
1509 * This is a hackish and needs to be refactored. However it would be nice to
1510 * unify all the different methods we use for showing Alerts and Dialogs.
1511 * (E.g. "Page deleted", login form, ...)
1516 * @param object $request
1517 * @param mixed $head Header ("title") for alert box.
1518 * @param mixed $body The text in the alert box.
1519 * @param hash $buttons An array mapping button labels to URLs.
1520 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1522 function Alert($head, $body, $buttons=false) {
1523 if ($buttons === false)
1526 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1527 $this->_buttons = $buttons;
1531 * Show the alert box.
1536 $tokens = $this->_tokens;
1537 $tokens['BUTTONS'] = $this->_getButtons();
1539 $request->discardOutput();
1540 $tmpl = new Template('dialog', $request, $tokens);
1546 function _getButtons() {
1549 $buttons = $this->_buttons;
1551 $buttons = array(_("Okay") => $request->getURLtoSelf());
1554 foreach ($buttons as $label => $url)
1555 print "$label $url\n";
1556 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1557 return new XmlContent($out);
1562 // 1.3.9-p1 => 1030.091
1563 // 1.3.10pre => 1030.099
1564 // 1.3.11pre-20041120 => 1030.1120041120
1565 function phpwiki_version() {
1566 static $PHPWIKI_VERSION;
1567 if (!isset($PHPWIKI_VERSION)) {
1568 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1569 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1570 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1571 if (strstr(PHPWIKI_VERSION, 'pre'))
1572 $PHPWIKI_VERSION -= 0.01;
1574 return $PHPWIKI_VERSION;
1577 function isWikiWord($word) {
1578 global $WikiNameRegexp;
1579 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1580 return preg_match("/^$WikiNameRegexp\$/",$word);
1583 // needed to store serialized objects-values only (perm, pref)
1584 function obj2hash ($obj, $exclude = false, $fields = false) {
1586 if (! $fields ) $fields = get_object_vars($obj);
1587 foreach ($fields as $key => $val) {
1588 if (is_array($exclude)) {
1589 if (in_array($key,$exclude)) continue;
1597 * isUtf8String($string) - cheap utf-8 detection
1599 * segfaults for strings longer than 10kb!
1600 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1601 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1603 function isUtf8String( $s ) {
1604 $ptrASCII = '[\x00-\x7F]';
1605 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1606 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1607 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1608 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1609 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1610 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1614 * Check for UTF-8 URLs; Internet Explorer produces these if you
1615 * type non-ASCII chars in the URL bar or follow unescaped links.
1616 * Requires urldecoded pagename.
1617 * Fixes sf.net bug #953949
1619 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1621 function fixTitleEncoding( $s ) {
1626 if (empty($s)) return $s;
1628 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1630 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1631 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1633 $isutf = ($ishigh ? isUtf8String($s) : true);
1634 $locharset = strtolower($charset);
1636 if( $locharset != "utf-8" and $ishigh and $isutf )
1637 // if charset == 'iso-8859-1' then simply use utf8_decode()
1638 if ($locharset == 'iso-8859-1')
1639 return utf8_decode( $s );
1641 // TODO: check for iconv support
1642 return iconv( "UTF-8", $charset, $s );
1644 if ($locharset == "utf-8" and $ishigh and !$isutf )
1645 return utf8_encode( $s );
1647 // Other languages can safely leave this function, or replace
1648 // it with one to detect and convert another legacy encoding.
1653 * MySQL fulltext index doesn't grok utf-8, so we
1654 * need to fold cases and convert to hex.
1655 * src: languages/Language.php:stripForSearch() from mediawiki
1658 function stripForSearch( $string ) {
1659 global $wikiLowerChars;
1660 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1661 return preg_replace(
1662 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1663 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1669 * Workaround for allow_url_fopen, to get the content of an external URI.
1670 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1671 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1673 function url_get_contents( $uri ) {
1674 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1675 return @file_get_contents($uri);
1677 require_once("lib/HttpClient.php");
1678 $bits = parse_url($uri);
1679 $host = $bits['host'];
1680 $port = isset($bits['port']) ? $bits['port'] : 80;
1681 $path = isset($bits['path']) ? $bits['path'] : '/';
1682 if (isset($bits['query'])) {
1683 $path .= '?'.$bits['query'];
1685 $client = new HttpClient($host, $port);
1686 $client->use_gzip = false;
1687 if (!$client->get($path)) {
1690 return $client->getContent();
1696 * Generate consecutively named strings:
1697 * Name, Name2, Name3, ...
1699 function GenerateId($name) {
1700 static $ids = array();
1701 if (empty($ids[$name])) {
1706 return $name . $ids[$name];
1710 // from IncludePage. To be of general use.
1711 // content: string or array of strings
1712 function firstNWordsOfContent( $n, $content ) {
1713 if ($content and $n > 0) {
1714 if (is_array($content)) {
1715 // fixme: return a list of lines then?
1716 $content = join("\n", $content);
1717 $return_array = true;
1719 foreach ($content as $line) {
1720 $words = explode(' ', $line);
1721 if ($wordcount + count($words) > $n) {
1722 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1723 . sprintf(_("... (first %s words)"), $n);
1726 $wordcount += count($words);
1732 // fixme: use better whitespace/word seperators
1733 $words = explode(' ', $content);
1734 if (count($words) > $n) {
1735 return join(' ', array_slice($words, 0, $n))
1736 . sprintf(_("... (first %s words)"), $n);
1746 // moved from lib/plugin/IncludePage.php
1747 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1748 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1750 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
1751 . " \\s*$\\n?" // possible blank lines
1752 . " ( (?: ^.*\\n? )*? )" // some lines
1753 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1754 implode("\n", $content),
1756 // Strip trailing blanks lines and ---- <hr>s
1757 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1759 $text = $match[1] . $section ."\n". $text;
1760 return explode("\n", $text);
1763 $mesg = $page ." ". $section;
1766 return array(sprintf(_("<%s: no such section>"), $mesg));
1769 // use this faster version: only load ExternalReferrer if we came from an external referrer
1770 function isExternalReferrer(&$request) {
1771 if ($referrer = $request->get('HTTP_REFERER')) {
1772 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
1773 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
1774 require_once("lib/ExternalReferrer.php");
1775 $se = new SearchEngines();
1776 return $se->parseSearchQuery($referrer);
1782 * useful for PECL overrides: cvsclient, ldap, soap.
1784 function loadPhpExtension($extension) {
1785 if (!extension_loaded($extension)) {
1786 $soname = (isWindows() ? 'php_' : '') . $extension . (isWindows() ? '.dll' : '.so');
1790 return extension_loaded($extension);
1793 function string_starts_with($string, $prefix) {
1794 return (substr($string, 0, strlen($prefix)) == $prefix);
1798 * Ensure that the script will have another $secs time left.
1799 * Works only if safe_mode is off.
1800 * For example not to timeout on waiting socket connections.
1801 * Use the socket timeout as arg.
1803 function longer_timeout($secs = 30) {
1804 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
1805 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
1806 if ($timeleft < $secs)
1807 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
1810 function printSimpleTrace($bt) {
1812 echo "Traceback:\n";
1813 foreach ($bt as $i => $elem) {
1814 if (!array_key_exists('file', $elem)) {
1817 echo join(" ",array_values($elem)),"\n";
1818 //print " " . $elem['file'] . ':' . $elem['line'] . " " .$elem['function']"\n";
1822 // $Log: not supported by cvs2svn $
1823 // Revision 1.221 2004/12/06 19:49:58 rurban
1824 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
1825 // renamed delete_page to purge_page.
1826 // enable action=edit&version=-1 to force creation of a new version.
1827 // added BABYCART_PATH config
1828 // fixed magiqc in adodb.inc.php
1829 // and some more docs
1831 // Revision 1.220 2004/11/30 17:47:41 rurban
1832 // added mt_srand, check for native isa
1834 // Revision 1.219 2004/11/26 18:39:02 rurban
1835 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1837 // Revision 1.218 2004/11/25 08:28:48 rurban
1840 // Revision 1.217 2004/11/16 17:31:03 rurban
1841 // re-enable old block markup conversion
1843 // Revision 1.216 2004/11/11 18:31:26 rurban
1844 // add simple backtrace on such general failures to get at least an idea where
1846 // Revision 1.215 2004/11/11 14:34:12 rurban
1847 // minor clarifications
1849 // Revision 1.214 2004/11/11 11:01:20 rurban
1850 // fix loadPhpExtension
1852 // Revision 1.213 2004/11/01 10:43:57 rurban
1853 // seperate PassUser methods into seperate dir (memory usage)
1854 // fix WikiUser (old) overlarge data session
1855 // remove wikidb arg from various page class methods, use global ->_dbi instead
1858 // Revision 1.212 2004/10/22 09:15:39 rurban
1859 // Alert::show has no arg anymore
1861 // Revision 1.211 2004/10/22 09:05:11 rurban
1862 // added longer_timeout (HttpClient)
1865 // Revision 1.210 2004/10/14 21:06:02 rurban
1866 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
1868 // Revision 1.209 2004/10/14 19:19:34 rurban
1869 // loadsave: check if the dumped file will be accessible from outside.
1870 // and some other minor fixes. (cvsclient native not yet ready)
1872 // Revision 1.208 2004/10/12 13:13:20 rurban
1873 // php5 compatibility (5.0.1 ok)
1875 // Revision 1.207 2004/09/26 12:21:40 rurban
1876 // removed old log entries.
1877 // added persistent start_debug on internal links and DEBUG
1878 // added isExternalReferrer (not yet used)
1880 // Revision 1.206 2004/09/25 16:28:36 rurban
1881 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
1883 // Revision 1.205 2004/09/23 13:59:35 rurban
1884 // Before removing a page display a sample of 100 words.
1886 // Revision 1.204 2004/09/17 13:19:15 rurban
1887 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
1890 // Revision 1.203 2004/09/16 08:00:52 rurban
1891 // just some comments
1893 // Revision 1.202 2004/09/14 10:11:44 rurban
1894 // start 2nd Id with ...Plugin2
1896 // Revision 1.201 2004/09/14 10:06:42 rurban
1897 // generate iterated plugin ids, set plugin span id also
1899 // Revision 1.200 2004/08/05 17:34:26 rurban
1900 // move require to sortby branch
1902 // Revision 1.199 2004/08/05 10:38:15 rurban
1903 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
1906 // Revision 1.198 2004/07/02 10:30:36 rurban
1907 // always disable getimagesize for < php-4.3 with external png's
1909 // Revision 1.197 2004/07/02 09:55:58 rurban
1910 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
1912 // Revision 1.196 2004/07/01 08:51:22 rurban
1913 // dumphtml: added exclude, print pagename before processing
1915 // Revision 1.195 2004/06/29 08:52:22 rurban
1916 // Use ...version() $need_content argument in WikiDB also:
1917 // To reduce the memory footprint for larger sets of pagelists,
1918 // we don't cache the content (only true or false) and
1919 // we purge the pagedata (_cached_html) also.
1920 // _cached_html is only cached for the current pagename.
1921 // => Vastly improved page existance check, ACL check, ...
1923 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1925 // Revision 1.194 2004/06/29 06:48:04 rurban
1926 // Improve LDAP auth and GROUP_LDAP membership:
1927 // no error message on false password,
1928 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
1929 // fixed two group queries (this -> user)
1930 // stdlib: ConvertOldMarkup still flawed
1932 // Revision 1.193 2004/06/28 13:27:03 rurban
1933 // CreateToc disabled for old markup and Apache2 only
1935 // Revision 1.192 2004/06/28 12:47:43 rurban
1936 // skip if non-DEBUG and old markup with CreateToc
1938 // Revision 1.191 2004/06/25 14:31:56 rurban
1939 // avoid debug_skip warning
1941 // Revision 1.190 2004/06/25 14:29:20 rurban
1942 // WikiGroup refactoring:
1943 // global group attached to user, code for not_current user.
1944 // improved helpers for special groups (avoid double invocations)
1945 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1946 // fixed a XHTML validation error on userprefs.tmpl
1948 // Revision 1.189 2004/06/20 09:45:35 rurban
1949 // php5 isa fix (wrong strtolower)
1951 // Revision 1.188 2004/06/16 10:38:58 rurban
1952 // Disallow refernces in calls if the declaration is a reference
1953 // ("allow_call_time_pass_reference clean").
1954 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1955 // but several external libraries may not.
1956 // In detail these libs look to be affected (not tested):
1960 // Revision 1.187 2004/06/14 11:31:37 rurban
1961 // renamed global $Theme to $WikiTheme (gforge nameclash)
1962 // inherit PageList default options from PageList
1963 // default sortby=pagename
1964 // use options in PageList_Selectable (limit, sortby, ...)
1965 // added action revert, with button at action=diff
1966 // added option regex to WikiAdminSearchReplace
1968 // Revision 1.186 2004/06/13 13:54:25 rurban
1969 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
1970 // FoafViewer: Check against external requirements, instead of fatal.
1971 // Change output for xhtmldumps: using file:// urls to the local fs.
1972 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
1973 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
1975 // Revision 1.185 2004/06/11 09:07:30 rurban
1976 // support theme-specific LinkIconAttr: front or after or none
1978 // Revision 1.184 2004/06/04 20:32:53 rurban
1979 // Several locale related improvements suggested by Pierrick Meignen
1980 // LDAP fix by John Cole
1981 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1983 // Revision 1.183 2004/06/01 10:22:56 rurban
1984 // added url_get_contents() used in XmlParser and elsewhere
1986 // Revision 1.182 2004/05/25 12:40:48 rurban
1987 // trim the pagename
1989 // Revision 1.181 2004/05/25 10:18:44 rurban
1990 // Check for UTF-8 URLs; Internet Explorer produces these if you
1991 // type non-ASCII chars in the URL bar or follow unescaped links.
1992 // Fixes sf.net bug #953949
1993 // src: languages/Language.php:checkTitleEncoding() from mediawiki
1995 // Revision 1.180 2004/05/18 16:23:39 rurban
1996 // rename split_pagename to SplitPagename
1998 // Revision 1.179 2004/05/18 16:18:37 rurban
1999 // AutoSplit at subpage seperators
2000 // RssFeed stability fix for empty feeds or broken connections
2002 // Revision 1.178 2004/05/12 10:49:55 rurban
2003 // require_once fix for those libs which are loaded before FileFinder and
2004 // its automatic include_path fix, and where require_once doesn't grok
2005 // dirname(__FILE__) != './lib'
2006 // upgrade fix with PearDB
2007 // navbar.tmpl: remove spaces for IE button alignment
2009 // Revision 1.177 2004/05/08 14:06:12 rurban
2010 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2011 // minor stability and portability fixes
2013 // Revision 1.176 2004/05/08 11:25:15 rurban
2016 // Revision 1.175 2004/05/06 17:30:38 rurban
2017 // CategoryGroup: oops, dos2unix eol
2018 // improved phpwiki_version:
2019 // pre -= .0001 (1.3.10pre: 1030.099)
2020 // -p1 += .001 (1.3.9-p1: 1030.091)
2021 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2022 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2023 // backend->backendType(), backend->database(),
2024 // backend->listOfFields(),
2025 // backend->listOfTables(),
2027 // Revision 1.174 2004/05/06 12:02:05 rurban
2028 // fix sf.net bug#949002: [ Link | ] assertion
2030 // Revision 1.173 2004/05/03 15:00:31 rurban
2031 // added more database upgrading: session.sess_ip, page.id autp_increment
2033 // Revision 1.172 2004/04/26 20:44:34 rurban
2034 // locking table specific for better databases
2036 // Revision 1.171 2004/04/19 23:13:03 zorloc
2037 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
2039 // Revision 1.170 2004/04/19 18:27:45 rurban
2040 // Prevent from some PHP5 warnings (ref args, no :: object init)
2041 // php5 runs now through, just one wrong XmlElement object init missing
2042 // Removed unneccesary UpgradeUser lines
2043 // Changed WikiLink to omit version if current (RecentChanges)
2045 // Revision 1.169 2004/04/15 21:29:48 rurban
2046 // allow [0] with new markup: link to page "0"
2048 // Revision 1.168 2004/04/10 02:30:49 rurban
2049 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2050 // Fixed "cannot setlocale..." (sf.net problem)
2052 // Revision 1.167 2004/04/02 15:06:55 rurban
2053 // fixed a nasty ADODB_mysql session update bug
2054 // improved UserPreferences layout (tabled hints)
2055 // fixed UserPreferences auth handling
2056 // improved auth stability
2057 // improved old cookie handling: fixed deletion of old cookies with paths
2059 // Revision 1.166 2004/04/01 15:57:10 rurban
2060 // simplified Sidebar theme: table, not absolute css positioning
2061 // added the new box methods.
2062 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2064 // Revision 1.165 2004/03/24 19:39:03 rurban
2065 // php5 workaround code (plus some interim debugging code in XmlElement)
2066 // php5 doesn't work yet with the current XmlElement class constructors,
2067 // WikiUserNew does work better than php4.
2068 // rewrote WikiUserNew user upgrading to ease php5 update
2069 // fixed pref handling in WikiUserNew
2070 // added Email Notification
2071 // added simple Email verification
2072 // removed emailVerify userpref subclass: just a email property
2073 // changed pref binary storage layout: numarray => hash of non default values
2074 // print optimize message only if really done.
2075 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2076 // prefs should be stored in db or homepage, besides the current session.
2078 // Revision 1.164 2004/03/18 21:41:09 rurban
2079 // fixed sqlite support
2080 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2082 // Revision 1.163 2004/03/17 18:41:49 rurban
2083 // just reformatting
2085 // Revision 1.162 2004/03/16 15:43:08 rurban
2086 // make fileSet sortable to please PageList
2088 // Revision 1.161 2004/03/12 15:48:07 rurban
2089 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2090 // simplified lib/stdlib.php:explodePageList
2092 // Revision 1.160 2004/02/28 21:14:08 rurban
2093 // generally more PHPDOC docs
2094 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2095 // fxied WikiUserNew pref handling: empty theme not stored, save only
2096 // changed prefs, sql prefs improved, fixed password update,
2097 // removed REPLACE sql (dangerous)
2098 // moved gettext init after the locale was guessed
2099 // + some minor changes
2102 // (c-file-style: "gnu")
2106 // c-basic-offset: 4
2107 // c-hanging-comment-ender-p: nil
2108 // indent-tabs-mode: nil