1 <?php //rcs_id('$Id: stdlib.php,v 1.207 2004-09-26 12:21:40 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);
81 * Convert string to a valid XML identifier.
83 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
85 * We would like to have, e.g. named anchors within wiki pages
86 * names like "Table of Contents" --- clearly not a valid XML
87 * fragment identifier.
89 * This function implements a one-to-one map from {any string}
90 * to {valid XML identifiers}.
93 * converting all bytes not in [A-Za-z0-9:_-],
94 * and any leading byte not in [A-Za-z] to 'xbb.',
95 * where 'bb' is the hexadecimal representation of the
98 * As a special case, the empty string is converted to 'empty.'
103 function MangleXmlIdentifier($str) {
107 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
108 "'x' . sprintf('%02x', ord('\\0')) . '.'",
112 function UnMangleXmlIdentifier($str) {
113 if ($str == 'empty.')
115 return preg_replace('/x(\w\w)\./e',
116 "sprintf('%c', hex('\\0'))",
121 * Generates a valid URL for a given Wiki pagename.
122 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
123 * If a WikiDB_Page object function will extract the name to link to.
124 * If a WikiDB_PageRevision object function will extract the name to link to.
126 * @param boolean $get_abs_url Default value is false.
127 * @return string The absolute URL to the page passed as $pagename.
129 function WikiURL($pagename, $args = '', $get_abs_url = false) {
132 if (is_object($pagename)) {
133 if (isa($pagename, 'WikiDB_Page')) {
134 $pagename = $pagename->getName();
136 elseif (isa($pagename, 'WikiDB_PageRevision')) {
137 $page = $pagename->getPage();
138 $args['version'] = $pagename->getVersion();
139 $pagename = $page->getName();
141 elseif (isa($pagename, 'WikiPageName')) {
142 $anchor = $pagename->anchor;
143 $pagename = $pagename->name;
145 $anchor = $pagename->anchor;
146 $pagename = $pagename->name;
149 if (!$get_abs_url and DEBUG and $GLOBALS['request']->getArg('start_debug')) {
151 $args = 'start_debug=' . $GLOBALS['request']->getArg('start_debug');
152 elseif (is_array($args))
153 $args['start_debug'] = $GLOBALS['request']->getArg('start_debug');
155 $args .= '&start_debug=' . $GLOBALS['request']->getArg('start_debug');
157 if (is_array($args)) {
159 foreach ($args as $key => $val) {
160 if (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
161 $enc_args[] = urlencode($key) . '=' . urlencode($val);
163 $args = join('&', $enc_args);
167 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
168 $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
173 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
174 $url .= "?pagename=" . rawurlencode($pagename);
179 $url .= "#" . MangleXmlIdentifier($anchor);
183 /** Convert relative URL to absolute URL.
185 * This converts a relative URL to one of PhpWiki's support files
186 * to an absolute one.
189 * @return string Absolute URL
191 function AbsoluteURL ($url) {
192 if (preg_match('/^https?:/', $url))
194 if ($url[0] != '/') {
195 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
196 while ($base != '/' and substr($url, 0, 3) == "../") {
197 $url = substr($url, 3);
198 $base = dirname($base);
204 return SERVER_URL . $url;
208 * Generates icon in front of links.
210 * @param string $protocol_or_url URL or protocol to determine which icon to use.
212 * @return HtmlElement HtmlElement object that contains data to create img link to
213 * icon for use with url or protocol passed to the function. False if no img to be
216 function IconForLink($protocol_or_url) {
218 if (0 and $filename_suffix == false) {
219 // display apache style icon for file type instead of protocol icon
220 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
221 // - document: html, htm, text, txt, rtf, pdf, doc
222 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
223 // - audio: mp3,mp2,aiff,aif,au
224 // - multimedia: mpeg,mpg,mov,qt
226 list ($proto) = explode(':', $protocol_or_url, 2);
227 $src = $WikiTheme->getLinkIconURL($proto);
229 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
236 * Glue icon in front of or after text.
237 * Pref: 'noLinkIcons' - ignore icon if set
238 * Theme: 'LinkIcons' - 'yes' at front
239 * - 'no' display no icon
240 * - 'front' display at left
241 * - 'after' display at right
243 * @param string $protocol_or_url Protocol or URL. Used to determine the
245 * @param string $text The text.
246 * @return XmlContent.
248 function PossiblyGlueIconToText($proto_or_url, $text) {
249 global $request, $WikiTheme;
250 if ($request->getPref('noLinkIcons'))
252 $icon = IconForLink($proto_or_url);
255 if ($where = $WikiTheme->getLinkIconAttr()) {
256 if ($where == 'no') return $text;
257 if ($where != 'after') $where = 'front';
261 if ($where == 'after') {
262 // span the icon only to the last word (tie them together),
263 // to let the previous words wrap on line breaks.
264 if (!is_object($text)) {
265 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
266 list (, $prefix, $last_word) = $m;
272 $text = HTML::span(array('style' => 'white-space: nowrap'),
273 $last_word, HTML::Raw(' '), $icon);
275 $text = HTML($prefix, $text);
278 // span the icon only to the first word (tie them together),
279 // to let the next words wrap on line breaks
280 if (!is_object($text)) {
281 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
282 list (, $first_word, $tail) = $m;
288 $text = HTML::span(array('style' => 'white-space: nowrap'),
291 $text = HTML($text, $tail);
296 * Determines if the url passed to function is safe, by detecting if the characters
297 * '<', '>', or '"' are present.
299 * @param string $url URL to check for unsafe characters.
300 * @return boolean True if same, false else.
302 function IsSafeURL($url) {
303 return !preg_match('/[<>"]/', $url);
307 * Generates an HtmlElement object to store data for a link.
309 * @param string $url URL that the link will point to.
310 * @param string $linktext Text to be displayed as link.
311 * @return HtmlElement HtmlElement object that contains data to construct an html link.
313 function LinkURL($url, $linktext = '') {
314 // FIXME: Is this needed (or sufficient?)
315 if(! IsSafeURL($url)) {
316 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
317 _("BAD URL -- remove all of <, >, \"")));
321 $linktext = preg_replace("/mailto:/A", "", $url);
323 $link = HTML::a(array('href' => $url),
324 PossiblyGlueIconToText($url, $linktext));
327 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
332 * FIXME: disallow sizes which are too small.
333 * Spammers may use such (typically invisible) image attributes to higher their GoogleRank.
335 function LinkImage($url, $alt = false) {
336 // FIXME: Is this needed (or sufficient?)
337 if(! IsSafeURL($url)) {
338 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
339 _("BAD URL -- remove all of <, >, \"")));
341 // support new syntax: [image.jpg size=50% border=n]
342 $arr = split(' ',$url);
343 if (count($arr) > 1) {
346 if (empty($alt)) $alt = basename($url);
347 $link = HTML::img(array('src' => $url, 'alt' => $alt));
348 if (count($arr) > 1) {
350 foreach ($arr as $attr) {
351 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
352 $link->setAttr('width',$m[1]);
353 $link->setAttr('height',$m[1]);
355 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
356 $link->setAttr('width',$m[1]);
357 $link->setAttr('height',$m[2]);
359 if (preg_match('/^border=(\d+)$/',$attr,$m))
360 $link->setAttr('border',$m[1]);
361 if (preg_match('/^align=(\w+)$/',$attr,$m))
362 $link->setAttr('align',$m[1]);
363 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
364 $link->setAttr('hspace',$m[1]);
365 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
366 $link->setAttr('vspace',$m[1]);
369 // check width and height as spam countermeasure
370 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
371 //$width = (int) $width; // px or % or other suffix
372 //$height = (int) $height;
373 if (($width < 3 and $height < 10) or
374 ($height < 3 and $width < 20) or
375 ($height < 7 and $width < 7))
377 trigger_error(_("Invalid image size"), E_USER_NOTICE);
381 // Older php versions crash here with certain png's:
382 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
383 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
384 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
385 if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
386 ; // it's safe to assume that this will fail.
387 elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
390 if (($width < 3 and $height < 10)
391 or ($height < 3 and $width < 20)
392 or ($height < 7 and $width < 7))
394 trigger_error(_("Invalid image size"), E_USER_NOTICE);
400 $link->setAttr('class', 'inlineimage');
407 var $items = array();
409 // var in php5.0.0.rc1 deprecated
411 function push($item) {
412 $this->items[$this->size] = $item;
418 if ($this->size == 0) {
419 return false; // stack is empty
422 return $this->items[$this->size];
431 return $this->items[$this->size - 1];
437 // end class definition
439 function SplitQueryArgs ($query_args = '')
441 $split_args = split('&', $query_args);
443 while (list($key, $val) = each($split_args))
444 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
445 $args[$m[1]] = $m[2];
449 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
452 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
453 return HTML::strong(array('class' => 'rawurl'),
454 HTML::u(array('class' => 'baduri'),
455 _("BAD phpwiki: URL")));
459 $pagename = urldecode($m[1]);
462 if (empty($pagename) &&
463 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
464 // Convert old style links (to not break diff links in
466 $pagename = urldecode($m[2]);
467 $args = array("action" => $m[1]);
470 $args = SplitQueryArgs($qargs);
473 if (empty($pagename))
474 $pagename = $GLOBALS['request']->getArg('pagename');
476 if (isset($args['action']) && $args['action'] == 'browse')
477 unset($args['action']);
480 if (empty($args['action']))
482 else if (is_safe_action($args['action']))
483 $class = 'wikiaction';
485 if (empty($args['action']) || is_safe_action($args['action']))
486 $class = 'wikiaction';
488 // Don't allow administrative links on unlocked pages.
489 $dbi = $GLOBALS['request']->getDbh();
490 $page = $dbi->getPage($basepage ? $basepage : $pagename);
491 if (!$page->get('locked'))
492 return HTML::span(array('class' => 'wikiunsafe'),
493 HTML::u(_("Lock page to enable link")));
494 $class = 'wikiadmin';
498 $text = HTML::span(array('class' => 'rawurl'), $url);
500 $wikipage = new WikiPageName($pagename);
501 if (!$wikipage->isValid()) {
503 return $WikiTheme->linkBadWikiWord($wikipage, $url);
506 return HTML::a(array('href' => WikiURL($pagename, $args),
512 * A class to assist in parsing wiki pagenames.
514 * Now with subpages and anchors, parsing and passing around
515 * pagenames is more complicated. This should help.
519 /** Short name for page.
521 * This is the value of $name passed to the constructor.
522 * (For use, e.g. as a default label for links to the page.)
526 /** The full page name.
528 * This is the full name of the page (without anchor).
534 * This is the referenced anchor within the page, or the empty string.
540 * @param mixed $name Page name.
541 * WikiDB_Page, WikiDB_PageRevision, or string.
542 * This can be a relative subpage name (like '/SubPage'),
543 * or can be the empty string to refer to the $basename.
545 * @param string $anchor For links to anchors in page.
547 * @param mixed $basename Page name from which to interpret
548 * relative or other non-fully-specified page names.
550 function WikiPageName($name, $basename=false, $anchor=false) {
551 if (is_string($name)) {
552 $this->shortName = $name;
554 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
556 $name = $this->_pagename($basename) . $name;
558 $name = $this->_normalize_bad_pagename($name);
562 $name = $this->_pagename($name);
563 $this->shortName = $name;
566 $this->name = $this->_check($name);
567 $this->anchor = (string)$anchor;
570 function getParent() {
572 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
574 return substr($name, 0, -strlen($tail));
577 function isValid($strict = false) {
579 return !isset($this->_errors);
580 return (is_string($this->name) and $this->name != '');
583 function getWarnings() {
585 if (isset($this->_warnings))
586 $warnings = array_merge($warnings, $this->_warnings);
587 if (isset($this->_errors))
588 $warnings = array_merge($warnings, $this->_errors);
592 return sprintf(_("'%s': Bad page name: %s"),
593 $this->shortName, join(', ', $warnings));
596 function _pagename($page) {
597 if (isa($page, 'WikiDB_Page'))
598 return $page->getName();
599 elseif (isa($page, 'WikiDB_PageRevision'))
600 return $page->getPageName();
601 elseif (isa($page, 'WikiPageName'))
603 if (!is_string($page)) {
604 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
605 $page, gettype($page), get_class($page)),
608 //assert(is_string($page));
612 function _normalize_bad_pagename($name) {
613 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
615 // Punt... You really shouldn't get here.
618 return $request->getArg('pagename');
620 assert($name[0] == SUBPAGE_SEPARATOR);
621 return substr($name, 1);
625 function _check($pagename) {
626 // Compress internal white-space to single space character.
627 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
628 if ($pagename != $orig)
629 $this->_warnings[] = _("White space converted to single space");
631 // Delete any control characters.
632 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
633 if ($pagename != $orig)
634 $this->_errors[] = _("Control characters not allowed");
636 // Strip leading and trailing white-space.
637 $pagename = trim($pagename);
640 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
641 $pagename = substr($pagename, 1);
642 if ($pagename != $orig)
643 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
645 if (preg_match('/[:;]/', $pagename)) {
646 $this->_warnings[] = _("';' and ':' are deprecated");
647 $pagename = str_replace(':', '', $pagename);
648 $pagename = str_replace(';', '', $pagename);
651 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
652 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
653 $this->_errors[] = _("too long");
656 if (strstr($pagename, '..')) {
657 $this->_warnings[] = sprintf(_("illegal .. removed"), $pagename);
658 $pagename = str_replace('..', '', $pagename);
666 * Convert old page markup to new-style markup.
668 * @param string $text Old-style wiki markup.
670 * @param string $markup_type
672 * <dt><code>"block"</code> <dd>Convert all markup.
673 * <dt><code>"inline"</code> <dd>Convert only inline markup.
674 * <dt><code>"links"</code> <dd>Convert only link markup.
677 * @return string New-style wiki markup.
679 * @bugs Footnotes don't work quite as before (esp if there are
680 * multiple references to the same footnote. But close enough,
681 * probably for now....
682 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
683 * AnciennesR%E8glesDeFormatage. ( at the 2nd attempt to do the anchored block regex )
684 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
685 * also known to crash, even with Apache1.
687 function ConvertOldMarkup ($text, $markup_type = "block") {
693 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
694 // AnciennesR%E8glesDeFormatage crashes.
695 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
696 // also known to crash, even with Apache1.
698 // I suspect this only to crash with Apache2 and IIS.
699 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
700 and preg_match("/plugin CreateToc/", $text))
702 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
703 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
704 ._("Skipped."), E_USER_WARNING);
706 //if (!DEBUG) return $text;
711 /*****************************************************************
712 * Conversions for inline markup:
719 // escape escaped brackets
723 // change ! escapes to ~'s.
724 global $WikiNameRegexp, $request;
725 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
726 $map = getInterwikiMap();
727 if ($map_regex = $map->getRegexp())
728 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
729 $bang_esc[] = $WikiNameRegexp;
730 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
733 $subs["links"] = array($orig, $repl);
736 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
739 // Convert footnote references.
740 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
741 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
743 // Convert old style emphases to HTML style emphasis.
744 $orig[] = '/__(.*?)__/';
745 $repl[] = '<strong>\\1</strong>';
746 $orig[] = "/''(.*?)''/";
747 $repl[] = '<em>\\1</em>';
749 // Escape nestled markup.
750 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
753 // in old markup headings only allowed at beginning of line
757 $subs["inline"] = array($orig, $repl);
759 /*****************************************************************
760 * Patterns which match block markup constructs which take
761 * special handling...
765 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
767 $blockpats[] = '\|(?:.*\n\|)*';
770 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
772 // Footnote definitions
773 $blockpats[] = '\[\s*(\d+)\s*\]';
777 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
781 $blockpats[] = '!{1,3}[^!]';
783 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
784 . join("|", $blockpats)
789 if ($markup_type != "block") {
790 list ($orig, $repl) = $subs[$markup_type];
791 return preg_replace($orig, $repl, $text);
794 list ($orig, $repl) = $subs['inline'];
797 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
798 // AnciennesR%E8glesDeFormatage and more
799 while (preg_match($block_re, $text, $m)) {
800 $text = substr($text, strlen($m[0]));
801 list (,$leading_text, $block) = $m;
804 if (strchr(" \t", $block[0])) {
807 $suffix = "\n</pre>\n";
809 elseif ($block[0] == '|') {
811 $prefix = "<?plugin OldStyleTable\n";
814 elseif (strchr("#*;", $block[0])) {
815 // Old-style list item
816 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
817 list (,$ind,$bullet) = $m;
818 $block = substr($block, strlen($m[0]));
820 $indent = str_repeat(' ', strlen($ind));
821 if ($bullet[0] == ';') {
822 //$term = ltrim(substr($bullet, 1));
823 //return $indent . $term . "\n" . $indent . ' ';
824 $prefix = $ind . $bullet;
827 $prefix = $indent . $bullet . ' ';
829 elseif ($block[0] == '[') {
830 // Footnote definition
831 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
833 $block = substr($block, strlen($m[0]));
834 $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
836 elseif ($block[0] == '<') {
838 // HACK: no inline markup...
842 elseif ($block[0] == '!') {
844 preg_match('/^!{1,3}/', $block, $m);
846 $block = substr($block, strlen($m[0]));
852 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
853 if ($block) $block = preg_replace($orig, $repl, $block);
854 $out .= $leading_text;
859 return $out . preg_replace($orig, $repl, $text);
865 * Expand tabs in string.
867 * Converts all tabs to (the appropriate number of) spaces.
870 * @param integer $tab_width
873 function expand_tabs($str, $tab_width = 8) {
874 $split = split("\t", $str);
875 $tail = array_pop($split);
877 foreach ($split as $hunk) {
879 $pos = strlen(strrchr($expanded, "\n")) - 1;
880 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
882 return substr($expanded, 1) . $tail;
886 * Split WikiWords in page names.
888 * It has been deemed useful to split WikiWords (into "Wiki Words") in
889 * places like page titles. This is rumored to help search engines
892 * @param $page string The page name.
894 * @return string The split name.
896 function SplitPagename ($page) {
898 if (preg_match("/\s/", $page))
899 return $page; // Already split --- don't split any more.
901 // This algorithm is specialized for several languages.
902 // (Thanks to Pierrick MEIGNEN)
903 // Improvements for other languages welcome.
906 // This mess splits between a lower-case letter followed by
907 // either an upper-case or a numeral; except that it wont
908 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
909 switch ($GLOBALS['LANG']) {
914 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
917 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
920 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
921 // This the single-letter words 'I' and 'A' from any following
922 // capitalized words.
923 switch ($GLOBALS['LANG']) {
925 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
928 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
931 // Split numerals from following letters.
932 $RE[] = '/(\d)([[:alpha:]])/';
933 // Split at subpage seperators. TBD in Theme.php
934 $RE[] = "/([^${sep}]+)(${sep})/";
936 foreach ($RE as $key)
937 $RE[$key] = pcre_fix_posix_classes($key);
940 foreach ($RE as $regexp) {
941 $page = preg_replace($regexp, '\\1 \\2', $page);
946 function NoSuchRevision (&$request, $page, $version) {
947 $html = HTML(HTML::h2(_("Revision Not Found")),
948 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
949 $version, WikiLink($page, 'auto'))));
950 include_once('lib/Template.php');
951 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
957 * Get time offset for local time zone.
959 * @param $time time_t Get offset for this time. Default: now.
960 * @param $no_colon boolean Don't put colon between hours and minutes.
961 * @return string Offset as a string in the format +HH:MM.
963 function TimezoneOffset ($time = false, $no_colon = false) {
966 $secs = date('Z', $time);
975 $colon = $no_colon ? '' : ':';
976 $mins = intval(($secs + 30) / 60);
977 return sprintf("%s%02d%s%02d",
978 $sign, $mins / 60, $colon, $mins % 60);
983 * Format time in ISO-8601 format.
985 * @param $time time_t Time. Default: now.
986 * @return string Date and time in ISO-8601 format.
988 function Iso8601DateTime ($time = false) {
991 $tzoff = TimezoneOffset($time);
992 $date = date('Y-m-d', $time);
993 $time = date('H:i:s', $time);
994 return $date . 'T' . $time . $tzoff;
998 * Format time in RFC-2822 format.
1000 * @param $time time_t Time. Default: now.
1001 * @return string Date and time in RFC-2822 format.
1003 function Rfc2822DateTime ($time = false) {
1004 if ($time === false)
1006 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1010 * Format time in RFC-1123 format.
1012 * @param $time time_t Time. Default: now.
1013 * @return string Date and time in RFC-1123 format.
1015 function Rfc1123DateTime ($time = false) {
1016 if ($time === false)
1018 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1021 /** Parse date in RFC-1123 format.
1023 * According to RFC 1123 we must accept dates in the following
1026 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1027 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1028 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1030 * (Though we're only allowed to generate dates in the first format.)
1032 function ParseRfc1123DateTime ($timestr) {
1033 $timestr = trim($timestr);
1034 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1035 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1037 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1039 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1040 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1042 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1043 if ($year < 70) $year += 2000;
1044 elseif ($year < 100) $year += 1900;
1046 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1047 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1049 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1056 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1058 return false; // failed
1063 * Format time to standard 'ctime' format.
1065 * @param $time time_t Time. Default: now.
1066 * @return string Date and time.
1068 function CTime ($time = false)
1070 if ($time === false)
1072 return date("D M j H:i:s Y", $time);
1077 * Format number as kilobytes or bytes.
1078 * Short format is used for PageList
1079 * Long format is used in PageInfo
1081 * @param $bytes int. Default: 0.
1082 * @param $longformat bool. Default: false.
1083 * @return class FormattedText (XmlElement.php).
1085 function ByteFormatter ($bytes = 0, $longformat = false) {
1088 if ($bytes < 1024) {
1090 $size = fmt("%s b", $bytes);
1092 $size = fmt("%s bytes", $bytes);
1095 $kb = round($bytes / 1024, 1);
1097 $size = fmt("%s k", $kb);
1099 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1105 * Internationalized printf.
1107 * This is essentially the same as PHP's built-in printf
1108 * with the following exceptions:
1110 * <li> It passes the format string through gettext().
1111 * <li> It supports the argument reordering extensions.
1118 * __printf("Differences between versions %s and %s of %s",
1119 * $new_link, $old_link, $page_link);
1122 * Then in locale/po/de.po, one can reorder the printf arguments:
1125 * msgid "Differences between %s and %s of %s."
1126 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1129 * (Note that while PHP tries to expand $vars within double-quotes,
1130 * the values in msgstr undergo no such expansion, so the '$'s
1133 * One shouldn't use reordered arguments in the default format string.
1134 * Backslashes in the default string would be necessary to escape the
1135 * '$'s, and they'll cause all kinds of trouble....
1137 function __printf ($fmt) {
1138 $args = func_get_args();
1140 echo __vsprintf($fmt, $args);
1144 * Internationalized sprintf.
1146 * This is essentially the same as PHP's built-in printf with the
1147 * following exceptions:
1150 * <li> It passes the format string through gettext().
1151 * <li> It supports the argument reordering extensions.
1156 function __sprintf ($fmt) {
1157 $args = func_get_args();
1159 return __vsprintf($fmt, $args);
1163 * Internationalized vsprintf.
1165 * This is essentially the same as PHP's built-in printf with the
1166 * following exceptions:
1169 * <li> It passes the format string through gettext().
1170 * <li> It supports the argument reordering extensions.
1175 function __vsprintf ($fmt, $args) {
1176 $fmt = gettext($fmt);
1177 // PHP's sprintf doesn't support variable with specifiers,
1178 // like sprintf("%*s", 10, "x"); --- so we won't either.
1180 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1181 // Format string has '%2$s' style argument reordering.
1182 // PHP doesn't support this.
1183 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1184 // literal variable name substitution only to keep locale
1185 // strings uncluttered
1186 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1187 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1189 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1192 // Reorder arguments appropriately.
1193 foreach($m[1] as $argnum) {
1194 if ($argnum < 1 || $argnum > count($args))
1195 trigger_error(sprintf(_("%s: argument index out of range"),
1196 $argnum), E_USER_WARNING);
1197 $newargs[] = $args[$argnum - 1];
1202 // Not all PHP's have vsprintf, so...
1203 array_unshift($args, $fmt);
1204 return call_user_func_array('sprintf', $args);
1207 function file_mtime ($filename) {
1208 if ($stat = @stat($filename))
1214 function sort_file_mtime ($a, $b) {
1215 $ma = file_mtime($a);
1216 $mb = file_mtime($b);
1217 if (!$ma or !$mb or $ma == $mb) return 0;
1218 return ($ma > $mb) ? -1 : 1;
1223 * Build an array in $this->_fileList of files from $dirname.
1224 * Subdirectories are not traversed.
1226 * (This was a function LoadDir in lib/loadsave.php)
1227 * See also http://www.php.net/manual/en/function.readdir.php
1229 function getFiles($exclude=false, $sortby=false, $limit=false) {
1230 $list = $this->_fileList;
1233 require_once('lib/PageList.php');
1234 switch (Pagelist::sortby($sortby, 'db')) {
1235 case 'pagename ASC': break;
1236 case 'pagename DESC':
1237 $list = array_reverse($list);
1240 usort($list,'sort_file_mtime');
1243 usort($list,'sort_file_mtime');
1244 $list = array_reverse($list);
1249 return array_splice($list, 0, $limit);
1253 function _filenameSelector($filename) {
1254 if (! $this->_pattern)
1257 return glob_match ($this->_pattern, $filename, $this->_case);
1261 function fileSet($directory, $filepattern = false) {
1262 $this->_fileList = array();
1263 $this->_pattern = $filepattern;
1264 $this->_case = !isWindows();
1265 $this->_pathsep = '/';
1267 if (empty($directory)) {
1268 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1270 return; // early return
1273 @ $dir_handle = opendir($dir=$directory);
1274 if (empty($dir_handle)) {
1275 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1276 $dir), E_USER_NOTICE);
1277 return; // early return
1280 while ($filename = readdir($dir_handle)) {
1281 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1283 if ($this->_filenameSelector($filename)) {
1284 array_push($this->_fileList, "$filename");
1285 //trigger_error(sprintf(_("found file %s"), $filename),
1286 // E_USER_NOTICE); //debugging
1289 closedir($dir_handle);
1295 // expands a list containing regex's to its matching entries
1296 class ListRegexExpand {
1297 var $match, $list, $index, $case_sensitive;
1298 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1299 $this->match = str_replace('/','\/',$match);
1300 $this->list = &$list;
1301 $this->case_sensitive = $case_sensitive;
1302 //$this->index = false;
1304 function listMatchCallback ($item, $key) {
1305 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), $item)) {
1306 unset($this->list[$this->index]);
1307 $this->list[] = $item;
1310 function expandRegex ($index, &$pages) {
1311 $this->index = $index;
1312 array_walk($pages, array($this, 'listMatchCallback'));
1317 // convert fileglob to regex style
1318 function glob_to_pcre ($glob) {
1319 $re = preg_replace('/\./', '\\.', $glob);
1320 $re = preg_replace(array('/\*/','/\?/'), array('.*','.'), $glob);
1321 if (!preg_match('/^[\?\*]/',$glob))
1323 if (!preg_match('/[\?\*]$/',$glob))
1328 function glob_match ($glob, $against, $case_sensitive = true) {
1329 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), $against);
1332 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1333 $list = explode(',',$input);
1334 // expand wildcards from list of $allnames
1335 if (preg_match('/[\?\*]/',$input)) {
1336 // Optimizing loop invariants:
1337 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1338 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1340 if (preg_match('/[\?\*]/',$f)) {
1342 $expand = new ListRegexExpand($list, $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1343 $expand->expandRegex($i, $allnames);
1350 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1351 function explodePageList($input, $perm=false, $sortby='pagename', $limit=false) {
1352 include_once("lib/PageList.php");
1353 return PageList::explodePageList($input,$perm,$sortby,$limit);
1356 // Class introspections
1359 * Determine whether object is of a specified type.
1360 * In PHP builtin since 4.2.0 as is_a()
1362 * @param $object object An object.
1363 * @param $class string Class name.
1364 * @return bool True iff $object is a $class
1365 * or a sub-type of $class.
1367 function isa ($object, $class) {
1368 $lclass = strtolower($class);
1370 return is_object($object)
1371 && ( strtolower(get_class($object)) == $lclass
1372 || is_subclass_of($object, $lclass) );
1375 /** Determine whether (possible) object has method.
1377 * @param $object mixed Object
1378 * @param $method string Method name
1379 * @return bool True iff $object is an object with has method $method.
1381 function can ($object, $method) {
1382 return is_object($object) && method_exists($object, strtolower($method));
1385 /** Determine whether a function is okay to use.
1387 * Some providers (e.g. Lycos) disable some of PHP functions for
1388 * "security reasons." This makes those functions, of course,
1389 * unusable, despite the fact the function_exists() says they
1392 * This function test to see if a function exists and is not
1393 * disallowed by PHP's disable_functions config setting.
1395 * @param string $function_name Function name
1396 * @return bool True iff function can be used.
1398 function function_usable($function_name) {
1400 if (!is_array($disabled)) {
1401 $disabled = array();
1402 // Use get_cfg_var since ini_get() is one of the disabled functions
1403 // (on Lycos, at least.)
1404 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1405 foreach ($split as $f)
1406 $disabled[strtolower($f)] = true;
1409 return ( function_exists($function_name)
1410 and ! isset($disabled[strtolower($function_name)])
1417 * This is used for generating ETags.
1419 function hash ($x) {
1420 if (is_scalar($x)) {
1423 elseif (is_array($x)) {
1425 return md5(serialize($x));
1427 elseif (is_object($x)) {
1430 trigger_error("Can't hash $x", E_USER_ERROR);
1435 * Seed the random number generator.
1437 * better_srand() ensures the randomizer is seeded only once.
1439 * How random do you want it? See:
1440 * http://www.php.net/manual/en/function.srand.php
1441 * http://www.php.net/manual/en/function.mt-srand.php
1443 function better_srand($seed = '') {
1444 static $wascalled = FALSE;
1446 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1449 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1454 * Recursively count all non-empty elements
1455 * in array of any dimension or mixed - i.e.
1456 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1457 * See http://www.php.net/manual/en/function.count.php
1459 function count_all($arg) {
1460 // skip if argument is empty
1462 //print_r($arg); //debugging
1464 // not an array, return 1 (base case)
1467 // else call recursively for all elements $arg
1468 foreach($arg as $key => $val)
1469 $count += count_all($val);
1474 function isSubPage($pagename) {
1475 return (strstr($pagename, SUBPAGE_SEPARATOR));
1478 function subPageSlice($pagename, $pos) {
1479 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1480 $pages = array_slice($pages,$pos,1);
1487 * Class for "popping up" and alert box. (Except that right now, it doesn't
1491 * This is a hackish and needs to be refactored. However it would be nice to
1492 * unify all the different methods we use for showing Alerts and Dialogs.
1493 * (E.g. "Page deleted", login form, ...)
1498 * @param object $request
1499 * @param mixed $head Header ("title") for alert box.
1500 * @param mixed $body The text in the alert box.
1501 * @param hash $buttons An array mapping button labels to URLs.
1502 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1504 function Alert($head, $body, $buttons=false) {
1505 if ($buttons === false)
1508 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1509 $this->_buttons = $buttons;
1513 * Show the alert box.
1515 function show(&$request) {
1518 $tokens = $this->_tokens;
1519 $tokens['BUTTONS'] = $this->_getButtons();
1521 $request->discardOutput();
1522 $tmpl = new Template('dialog', $request, $tokens);
1528 function _getButtons() {
1531 $buttons = $this->_buttons;
1533 $buttons = array(_("Okay") => $request->getURLtoSelf());
1536 foreach ($buttons as $label => $url)
1537 print "$label $url\n";
1538 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1539 return new XmlContent($out);
1544 // 1.3.9-p1 => 1030.091
1545 // 1.3.10pre => 1030.099
1546 function phpwiki_version() {
1547 static $PHPWIKI_VERSION;
1548 if (!isset($PHPWIKI_VERSION)) {
1549 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1550 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1551 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1552 if (substr(PHPWIKI_VERSION,-3,3) == 'pre')
1553 $PHPWIKI_VERSION -= 0.001;
1555 return $PHPWIKI_VERSION;
1558 function isWikiWord($word) {
1559 global $WikiNameRegexp;
1560 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1561 return preg_match("/^$WikiNameRegexp\$/",$word);
1564 // needed to store serialized objects-values only (perm, pref)
1565 function obj2hash ($obj, $exclude = false, $fields = false) {
1567 if (! $fields ) $fields = get_object_vars($obj);
1568 foreach ($fields as $key => $val) {
1569 if (is_array($exclude)) {
1570 if (in_array($key,$exclude)) continue;
1578 * isUtf8String($string) - cheap utf-8 detection
1580 * segfaults for strings longer than 10kb!
1581 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1582 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1584 function isUtf8String( $s ) {
1585 $ptrASCII = '[\x00-\x7F]';
1586 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1587 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1588 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1589 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1590 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1591 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1595 * Check for UTF-8 URLs; Internet Explorer produces these if you
1596 * type non-ASCII chars in the URL bar or follow unescaped links.
1597 * Requires urldecoded pagename.
1598 * Fixes sf.net bug #953949
1600 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1602 function fixTitleEncoding( $s ) {
1607 if (empty($s)) return $s;
1609 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1611 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1612 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1614 $isutf = ($ishigh ? isUtf8String($s) : true);
1615 $locharset = strtolower($charset);
1617 if( $locharset != "utf-8" and $ishigh and $isutf )
1618 // if charset == 'iso-8859-1' then simply use utf8_decode()
1619 if ($locharset == 'iso-8859-1')
1620 return utf8_decode( $s );
1622 // TODO: check for iconv support
1623 return iconv( "UTF-8", $charset, $s );
1625 if ($locharset == "utf-8" and $ishigh and !$isutf )
1626 return utf8_encode( $s );
1628 // Other languages can safely leave this function, or replace
1629 // it with one to detect and convert another legacy encoding.
1634 * MySQL fulltext index doesn't grok utf-8, so we
1635 * need to fold cases and convert to hex.
1636 * src: languages/Language.php:stripForSearch() from mediawiki
1639 function stripForSearch( $string ) {
1640 global $wikiLowerChars;
1641 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1642 return preg_replace(
1643 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1644 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1650 * Workaround for allow_url_fopen, to get the content of an external URI.
1651 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1652 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1654 function url_get_contents( $uri ) {
1655 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1656 return @file_get_contents($uri);
1658 require_once("lib/HttpClient.php");
1659 $bits = parse_url($uri);
1660 $host = $bits['host'];
1661 $port = isset($bits['port']) ? $bits['port'] : 80;
1662 $path = isset($bits['path']) ? $bits['path'] : '/';
1663 if (isset($bits['query'])) {
1664 $path .= '?'.$bits['query'];
1666 $client = new HttpClient($host, $port);
1667 $client->use_gzip = false;
1668 if (!$client->get($path)) {
1671 return $client->getContent();
1677 * Generate consecutively named strings:
1678 * Name, Name2, Name3, ...
1680 function GenerateId($name) {
1681 static $ids = array();
1682 if (empty($ids[$name])) {
1687 return $name . $ids[$name];
1691 // from IncludePage. To be of general use.
1692 // content: string or array of strings
1693 function firstNWordsOfContent( $n, $content ) {
1694 if ($content and $n > 0) {
1695 if (is_array($content)) {
1696 // fixme: return a list of lines then?
1697 $content = join("\n", $content);
1698 $return_array = true;
1700 foreach ($content as $line) {
1701 $words = explode(' ', $line);
1702 if ($wordcount + count($words) > $n) {
1703 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1704 . sprintf(_("... (first %s words)"), $n);
1707 $wordcount += count($words);
1713 // fixme: use better whitespace/word seperators
1714 $words = explode(' ', $content);
1715 if (count($words) > $n) {
1716 return join(' ', array_slice($words, 0, $n))
1717 . sprintf(_("... (first %s words)"), $n);
1727 // moved from lib/plugin/IncludePage.php
1728 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1729 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1731 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
1732 . " \\s*$\\n?" // possible blank lines
1733 . " ( (?: ^.*\\n? )*? )" // some lines
1734 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1735 implode("\n", $content),
1737 // Strip trailing blanks lines and ---- <hr>s
1738 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1740 $text = $match[1] . $section ."\n". $text;
1741 return explode("\n", $text);
1744 $mesg = $page ." ". $section;
1747 return array(sprintf(_("<%s: no such section>"), $mesg));
1750 function isExternalReferrer(&$request) {
1751 if ($referrer = $request->get('HTTP_REFERER')) {
1752 $home = SCRIPT_NAME; // was SERVER_URL, but we want to check sister wiki's also
1753 if (substr(strtolower($referrer),0,strlen($home)) == strtolower($home)) return false;
1754 require_once("lib/ExternalReferrer.php");
1755 $se = new SearchEngines();
1756 return $se->parseSearchQuery($referrer);
1761 // $Log: not supported by cvs2svn $
1762 // Revision 1.206 2004/09/25 16:28:36 rurban
1763 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
1765 // Revision 1.205 2004/09/23 13:59:35 rurban
1766 // Before removing a page display a sample of 100 words.
1768 // Revision 1.204 2004/09/17 13:19:15 rurban
1769 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
1772 // Revision 1.203 2004/09/16 08:00:52 rurban
1773 // just some comments
1775 // Revision 1.202 2004/09/14 10:11:44 rurban
1776 // start 2nd Id with ...Plugin2
1778 // Revision 1.201 2004/09/14 10:06:42 rurban
1779 // generate iterated plugin ids, set plugin span id also
1781 // Revision 1.200 2004/08/05 17:34:26 rurban
1782 // move require to sortby branch
1784 // Revision 1.199 2004/08/05 10:38:15 rurban
1785 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
1788 // Revision 1.198 2004/07/02 10:30:36 rurban
1789 // always disable getimagesize for < php-4.3 with external png's
1791 // Revision 1.197 2004/07/02 09:55:58 rurban
1792 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
1794 // Revision 1.196 2004/07/01 08:51:22 rurban
1795 // dumphtml: added exclude, print pagename before processing
1797 // Revision 1.195 2004/06/29 08:52:22 rurban
1798 // Use ...version() $need_content argument in WikiDB also:
1799 // To reduce the memory footprint for larger sets of pagelists,
1800 // we don't cache the content (only true or false) and
1801 // we purge the pagedata (_cached_html) also.
1802 // _cached_html is only cached for the current pagename.
1803 // => Vastly improved page existance check, ACL check, ...
1805 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1807 // Revision 1.194 2004/06/29 06:48:04 rurban
1808 // Improve LDAP auth and GROUP_LDAP membership:
1809 // no error message on false password,
1810 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
1811 // fixed two group queries (this -> user)
1812 // stdlib: ConvertOldMarkup still flawed
1814 // Revision 1.193 2004/06/28 13:27:03 rurban
1815 // CreateToc disabled for old markup and Apache2 only
1817 // Revision 1.192 2004/06/28 12:47:43 rurban
1818 // skip if non-DEBUG and old markup with CreateToc
1820 // Revision 1.191 2004/06/25 14:31:56 rurban
1821 // avoid debug_skip warning
1823 // Revision 1.190 2004/06/25 14:29:20 rurban
1824 // WikiGroup refactoring:
1825 // global group attached to user, code for not_current user.
1826 // improved helpers for special groups (avoid double invocations)
1827 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1828 // fixed a XHTML validation error on userprefs.tmpl
1830 // Revision 1.189 2004/06/20 09:45:35 rurban
1831 // php5 isa fix (wrong strtolower)
1833 // Revision 1.188 2004/06/16 10:38:58 rurban
1834 // Disallow refernces in calls if the declaration is a reference
1835 // ("allow_call_time_pass_reference clean").
1836 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1837 // but several external libraries may not.
1838 // In detail these libs look to be affected (not tested):
1842 // Revision 1.187 2004/06/14 11:31:37 rurban
1843 // renamed global $Theme to $WikiTheme (gforge nameclash)
1844 // inherit PageList default options from PageList
1845 // default sortby=pagename
1846 // use options in PageList_Selectable (limit, sortby, ...)
1847 // added action revert, with button at action=diff
1848 // added option regex to WikiAdminSearchReplace
1850 // Revision 1.186 2004/06/13 13:54:25 rurban
1851 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
1852 // FoafViewer: Check against external requirements, instead of fatal.
1853 // Change output for xhtmldumps: using file:// urls to the local fs.
1854 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
1855 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
1857 // Revision 1.185 2004/06/11 09:07:30 rurban
1858 // support theme-specific LinkIconAttr: front or after or none
1860 // Revision 1.184 2004/06/04 20:32:53 rurban
1861 // Several locale related improvements suggested by Pierrick Meignen
1862 // LDAP fix by John Cole
1863 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1865 // Revision 1.183 2004/06/01 10:22:56 rurban
1866 // added url_get_contents() used in XmlParser and elsewhere
1868 // Revision 1.182 2004/05/25 12:40:48 rurban
1869 // trim the pagename
1871 // Revision 1.181 2004/05/25 10:18:44 rurban
1872 // Check for UTF-8 URLs; Internet Explorer produces these if you
1873 // type non-ASCII chars in the URL bar or follow unescaped links.
1874 // Fixes sf.net bug #953949
1875 // src: languages/Language.php:checkTitleEncoding() from mediawiki
1877 // Revision 1.180 2004/05/18 16:23:39 rurban
1878 // rename split_pagename to SplitPagename
1880 // Revision 1.179 2004/05/18 16:18:37 rurban
1881 // AutoSplit at subpage seperators
1882 // RssFeed stability fix for empty feeds or broken connections
1884 // Revision 1.178 2004/05/12 10:49:55 rurban
1885 // require_once fix for those libs which are loaded before FileFinder and
1886 // its automatic include_path fix, and where require_once doesn't grok
1887 // dirname(__FILE__) != './lib'
1888 // upgrade fix with PearDB
1889 // navbar.tmpl: remove spaces for IE button alignment
1891 // Revision 1.177 2004/05/08 14:06:12 rurban
1892 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
1893 // minor stability and portability fixes
1895 // Revision 1.176 2004/05/08 11:25:15 rurban
1898 // Revision 1.175 2004/05/06 17:30:38 rurban
1899 // CategoryGroup: oops, dos2unix eol
1900 // improved phpwiki_version:
1901 // pre -= .0001 (1.3.10pre: 1030.099)
1902 // -p1 += .001 (1.3.9-p1: 1030.091)
1903 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1904 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1905 // backend->backendType(), backend->database(),
1906 // backend->listOfFields(),
1907 // backend->listOfTables(),
1909 // Revision 1.174 2004/05/06 12:02:05 rurban
1910 // fix sf.net bug#949002: [ Link | ] assertion
1912 // Revision 1.173 2004/05/03 15:00:31 rurban
1913 // added more database upgrading: session.sess_ip, page.id autp_increment
1915 // Revision 1.172 2004/04/26 20:44:34 rurban
1916 // locking table specific for better databases
1918 // Revision 1.171 2004/04/19 23:13:03 zorloc
1919 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
1921 // Revision 1.170 2004/04/19 18:27:45 rurban
1922 // Prevent from some PHP5 warnings (ref args, no :: object init)
1923 // php5 runs now through, just one wrong XmlElement object init missing
1924 // Removed unneccesary UpgradeUser lines
1925 // Changed WikiLink to omit version if current (RecentChanges)
1927 // Revision 1.169 2004/04/15 21:29:48 rurban
1928 // allow [0] with new markup: link to page "0"
1930 // Revision 1.168 2004/04/10 02:30:49 rurban
1931 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
1932 // Fixed "cannot setlocale..." (sf.net problem)
1934 // Revision 1.167 2004/04/02 15:06:55 rurban
1935 // fixed a nasty ADODB_mysql session update bug
1936 // improved UserPreferences layout (tabled hints)
1937 // fixed UserPreferences auth handling
1938 // improved auth stability
1939 // improved old cookie handling: fixed deletion of old cookies with paths
1941 // Revision 1.166 2004/04/01 15:57:10 rurban
1942 // simplified Sidebar theme: table, not absolute css positioning
1943 // added the new box methods.
1944 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
1946 // Revision 1.165 2004/03/24 19:39:03 rurban
1947 // php5 workaround code (plus some interim debugging code in XmlElement)
1948 // php5 doesn't work yet with the current XmlElement class constructors,
1949 // WikiUserNew does work better than php4.
1950 // rewrote WikiUserNew user upgrading to ease php5 update
1951 // fixed pref handling in WikiUserNew
1952 // added Email Notification
1953 // added simple Email verification
1954 // removed emailVerify userpref subclass: just a email property
1955 // changed pref binary storage layout: numarray => hash of non default values
1956 // print optimize message only if really done.
1957 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1958 // prefs should be stored in db or homepage, besides the current session.
1960 // Revision 1.164 2004/03/18 21:41:09 rurban
1961 // fixed sqlite support
1962 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
1964 // Revision 1.163 2004/03/17 18:41:49 rurban
1965 // just reformatting
1967 // Revision 1.162 2004/03/16 15:43:08 rurban
1968 // make fileSet sortable to please PageList
1970 // Revision 1.161 2004/03/12 15:48:07 rurban
1971 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1972 // simplified lib/stdlib.php:explodePageList
1974 // Revision 1.160 2004/02/28 21:14:08 rurban
1975 // generally more PHPDOC docs
1976 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
1977 // fxied WikiUserNew pref handling: empty theme not stored, save only
1978 // changed prefs, sql prefs improved, fixed password update,
1979 // removed REPLACE sql (dangerous)
1980 // moved gettext init after the locale was guessed
1981 // + some minor changes
1984 // (c-file-style: "gnu")
1988 // c-basic-offset: 4
1989 // c-hanging-comment-ender-p: nil
1990 // indent-tabs-mode: nil