1 <?php //rcs_id('$Id: stdlib.php,v 1.274 2008-05-06 19:29:06 rurban Exp $');
3 Copyright 1999-2008 $ThePhpWikiProgrammingTeam
5 This file is part of PhpWiki.
7 PhpWiki is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 PhpWiki is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with PhpWiki; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 Standard functions for Wiki functionality
24 WikiURL ($pagename, $args, $get_abs_url)
26 IconForLink ($protocol_or_url)
27 PossiblyGlueIconToText($proto_or_url, $text)
29 LinkURL ($url, $linktext)
30 LinkImage ($url, $alt)
32 SplitQueryArgs ($query_args)
33 LinkPhpwikiURL ($url, $text, $basepage)
34 ConvertOldMarkup ($content, $markup_type = "block")
35 MangleXmlIdentifier($str)
36 UnMangleXmlIdentifier($str)
38 class Stack { push($item), pop(), cnt(), top() }
39 class Alert { show() }
40 class WikiPageName {getParent(),isValid(),getWarnings() }
42 expand_tabs($str, $tab_width = 8)
44 NoSuchRevision ($request, $page, $version)
45 TimezoneOffset ($time, $no_colon)
46 Iso8601DateTime ($time)
47 Rfc2822DateTime ($time)
48 ParseRfc1123DateTime ($timestr)
50 ByteFormatter ($bytes = 0, $longformat = false)
53 __vsprintf ($fmt, $args)
55 file_mtime ($filename)
56 sort_file_mtime ($a, $b)
57 class fileSet {fileSet($directory, $filepattern = false),
58 getFiles($exclude='', $sortby='', $limit='') }
59 class ListRegexExpand { listMatchCallback($item, $key),
60 expandRegex ($index, &$pages) }
63 glob_match ($glob, $against, $case_sensitive = true)
64 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
65 explodePageList ($input, $perm = false)
67 can ($object, $method)
68 function_usable ($function_name)
70 better_srand ($seed = '')
73 subPageSlice ($pagename, $pos)
77 obj2hash ($obj, $exclude = false, $fields = false)
80 url_get_contents ($uri)
82 firstNWordsOfContent ($n, $content)
83 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
86 charset_convert($from, $to, $data)
88 function: LinkInterWikiLink($link, $linktext)
89 moved to: lib/interwiki.php
90 function: linkExistingWikiWord($wikiword, $linktext, $version)
91 moved to: lib/Theme.php
92 function: LinkUnknownWikiWord($wikiword, $linktext)
93 moved to: lib/Theme.php
94 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
95 gone see: lib/plugin/RecentChanges.php
97 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
98 else define('_PHPWIKI_STDLIB_LOADED', true);
100 define('MAX_PAGENAME_LENGTH', 100);
103 * Convert string to a valid XML identifier.
105 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
107 * We would like to have, e.g. named anchors within wiki pages
108 * names like "Table of Contents" --- clearly not a valid XML
109 * fragment identifier.
111 * This function implements a one-to-one map from {any string}
112 * to {valid XML identifiers}.
115 * converting all bytes not in [A-Za-z0-9:_-],
116 * and any leading byte not in [A-Za-z] to 'xbb.',
117 * where 'bb' is the hexadecimal representation of the
120 * As a special case, the empty string is converted to 'empty.'
125 function MangleXmlIdentifier($str) {
129 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
130 "'x' . sprintf('%02x', ord('\\0')) . '.'",
134 function UnMangleXmlIdentifier($str) {
135 if ($str == 'empty.')
137 return preg_replace('/x(\w\w)\./e',
138 "sprintf('%c', hex('\\0'))",
143 * Returns a name for the WIKI_ID cookie that should be unique on the host.
144 * But for it to be unique you must have set a unique WIKI_NAME in your
145 * configuration file.
146 * @return string The name of the WIKI_ID cookie to use for this wiki.
148 function GetCookieName() {
149 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
153 * Generates a valid URL for a given Wiki pagename.
154 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
155 * If a WikiDB_Page object function will extract the name to link to.
156 * If a WikiDB_PageRevision object function will extract the name to link to.
158 * @param boolean $get_abs_url Default value is false.
159 * @return string The absolute URL to the page passed as $pagename.
161 function WikiURL($pagename, $args = '', $get_abs_url = false) {
162 global $request, $WikiTheme;
165 if (is_object($pagename)) {
166 if (isa($pagename, 'WikiDB_Page')) {
167 $pagename = $pagename->getName();
169 elseif (isa($pagename, 'WikiDB_PageRevision')) {
170 $page = $pagename->getPage();
171 $args['version'] = $pagename->getVersion();
172 $pagename = $page->getName();
174 elseif (isa($pagename, 'WikiPageName')) {
175 $anchor = $pagename->anchor;
176 $pagename = $pagename->name;
178 $anchor = $pagename->anchor;
179 $pagename = $pagename->name;
182 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
184 $args = 'start_debug=' . $request->getArg('start_debug');
185 elseif (is_array($args))
186 $args['start_debug'] = $request->getArg('start_debug');
188 $args .= '&start_debug=' . $request->getArg('start_debug');
190 if (is_array($args)) {
192 foreach ($args as $key => $val) {
193 // avoid default args
194 if (USE_PATH_INFO and $key == 'pagename')
196 elseif ($key == 'action' and $val == 'browse')
198 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
199 $enc_args[] = urlencode($key) . '=' . urlencode($val);
201 $args = join('&', $enc_args);
204 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
205 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
206 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
208 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
209 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
210 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
213 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
215 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
225 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
226 $url .= "?pagename=" . rawurlencode($pagename);
231 $url .= "#" . MangleXmlIdentifier($anchor);
235 /** Convert relative URL to absolute URL.
237 * This converts a relative URL to one of PhpWiki's support files
238 * to an absolute one.
241 * @return string Absolute URL
243 function AbsoluteURL ($url) {
244 if (preg_match('/^https?:/', $url))
246 if ($url[0] != '/') {
247 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
248 while ($base != '/' and substr($url, 0, 3) == "../") {
249 $url = substr($url, 3);
250 $base = dirname($base);
256 return SERVER_URL . $url;
259 function DataURL ($url) {
260 if (preg_match('/^https?:/', $url))
262 $url = NormalizeWebFileName($url);
263 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
264 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
265 return AbsoluteURL($url);
269 * Generates icon in front of links.
271 * @param string $protocol_or_url URL or protocol to determine which icon to use.
273 * @return HtmlElement HtmlElement object that contains data to create img link to
274 * icon for use with url or protocol passed to the function. False if no img to be
277 function IconForLink($protocol_or_url) {
279 if (0 and $filename_suffix == false) {
280 // display apache style icon for file type instead of protocol icon
281 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
282 // - document: html, htm, text, txt, rtf, pdf, doc
283 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
284 // - audio: mp3,mp2,aiff,aif,au
285 // - multimedia: mpeg,mpg,mov,qt
287 list ($proto) = explode(':', $protocol_or_url, 2);
288 $src = $WikiTheme->getLinkIconURL($proto);
290 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
297 * Glue icon in front of or after text.
298 * Pref: 'noLinkIcons' - ignore icon if set
299 * Theme: 'LinkIcons' - 'yes' at front
300 * - 'no' display no icon
301 * - 'front' display at left
302 * - 'after' display at right
304 * @param string $protocol_or_url Protocol or URL. Used to determine the
306 * @param string $text The text.
307 * @return XmlContent.
309 function PossiblyGlueIconToText($proto_or_url, $text) {
310 global $request, $WikiTheme;
311 if ($request->getPref('noLinkIcons'))
313 $icon = IconForLink($proto_or_url);
316 if ($where = $WikiTheme->getLinkIconAttr()) {
317 if ($where == 'no') return $text;
318 if ($where != 'after') $where = 'front';
322 if ($where == 'after') {
323 // span the icon only to the last word (tie them together),
324 // to let the previous words wrap on line breaks.
325 if (!is_object($text)) {
326 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
327 list (, $prefix, $last_word) = $m;
333 $text = HTML::span(array('style' => 'white-space: nowrap'),
334 $last_word, HTML::Raw(' '), $icon);
336 $text = HTML($prefix, $text);
339 // span the icon only to the first word (tie them together),
340 // to let the next words wrap on line breaks
341 if (!is_object($text)) {
342 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
343 list (, $first_word, $tail) = $m;
349 $text = HTML::span(array('style' => 'white-space: nowrap'),
352 $text = HTML($text, $tail);
357 * Determines if the url passed to function is safe, by detecting if the characters
358 * '<', '>', or '"' are present.
359 * Check against their urlencoded values also.
361 * @param string $url URL to check for unsafe characters.
362 * @return boolean True if same, false else.
364 function IsSafeURL($url) {
365 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
369 * Generates an HtmlElement object to store data for a link.
371 * @param string $url URL that the link will point to.
372 * @param string $linktext Text to be displayed as link.
373 * @return HtmlElement HtmlElement object that contains data to construct an html link.
375 function LinkURL($url, $linktext = '') {
376 // FIXME: Is this needed (or sufficient?)
377 if(! IsSafeURL($url)) {
378 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
379 _("BAD URL -- remove all of <, >, \"")));
383 $linktext = preg_replace("/mailto:/A", "", $url);
384 $args = array('href' => $url);
385 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
386 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
387 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
389 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
396 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
397 * Disallows sizes which are too small.
398 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
400 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
402 function LinkImage($url, $alt = false) {
403 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
404 // Disallow tags in img src urls. Typical CSS attacks.
405 // FIXME: Is this needed (or sufficient?)
407 $arr = split(' ',$url);
408 if (count($arr) > 1) {
411 if(! IsSafeURL($url)) {
412 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
413 _("BAD URL -- remove all of <, >, \"")));
415 // support new syntax: [image.jpg size=50% border=n]
416 //if (!preg_match("/\.(".$force_img.")/i", $url))
417 if (empty($alt)) $alt = basename($url);
418 $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
419 if (count($arr) > 1) {
421 foreach ($arr as $attr) {
422 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
423 $link->setAttr('width',$m[1]);
424 $link->setAttr('height',$m[1]);
426 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
427 $link->setAttr('width',$m[1]);
428 $link->setAttr('height',$m[2]);
430 if (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
431 $link->setAttr('width',$m[1]);
432 if (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
433 $link->setAttr('height',$m[1]);
434 if (preg_match('/^border=(\d+)$/',$attr,$m))
435 $link->setAttr('border',$m[1]);
436 if (preg_match('/^align=(\w+)$/',$attr,$m))
437 $link->setAttr('align',$m[1]);
438 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
439 $link->setAttr('hspace',$m[1]);
440 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
441 $link->setAttr('vspace',$m[1]);
444 // Check width and height as spam countermeasure
445 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
446 //$width = (int) $width; // px or % or other suffix
447 //$height = (int) $height;
448 if (($width < 3 and $height < 10) or
449 ($height < 3 and $width < 20) or
450 ($height < 7 and $width < 7))
452 trigger_error(_("Invalid image size"), E_USER_WARNING);
457 // Prepare for getimagesize($url)
458 // $url only valid for external urls, otherwise local path
459 // Older php versions crash here with certain png's:
460 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
461 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
462 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
463 if (DISABLE_GETIMAGESIZE)
465 elseif (! preg_match("/\.$force_img$/i", $url))
466 ; // only valid image extensions or scripts assumed to generate images
467 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
468 ; // it's safe to assume that this will fail.
469 elseif (preg_match("/^http/",$url)) // external url
470 $size = @getimagesize($url);
472 if (file_exists($file = NormalizeLocalFileName($url))) { // here
473 $size = @getimagesize($file);
474 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
475 $size = @getimagesize($file);
476 $link->setAttr('src', rawurldecode($url));
477 } elseif (string_starts_with($url, getUploadDataPath())) { // there
478 $file = substr($file, strlen(getUploadDataPath()));
479 $size = @getimagesize(getUploadFilePath().rawurldecode($file));
480 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
481 } else { // elsewhere
482 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
488 if (($width < 3 and $height < 10)
489 or ($height < 3 and $width < 20)
490 or ($height < 7 and $width < 7))
492 trigger_error(_("Invalid image size"), E_USER_WARNING);
498 $link->setAttr('class', 'inlineimage');
500 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
501 * png|jpg|gif|jpeg|bmp|pl|cgi
502 * Note: Allow cgi's (pl,cgi) returning images.
504 if (!preg_match("/\.(".$force_img.")/i", $url)) {
505 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
506 // => HTML::object(array('src' => $url)) ...;
507 return ImgObject($link, $ori_url);
513 * <object> / <embed> tags instead of <img> for all non-image extensions
515 * Called by LinkImage(), not directly.
516 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
517 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
518 * $alt may be an alternate img
519 * TODO: Need to unify with WikiPluginCached::embedObject()
521 * Note that Safari 1.0 will crash with <object>, so use only <embed>
522 * http://www.alleged.org.uk/pdc/2002/svg-object.html
524 * Allowed object tags:
525 * DATA=URI (object data)
526 * CLASSID=URI (location of implementation)
527 * ARCHIVE=CDATA (archive files)
528 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
529 * WIDTH=Length (object width)
530 * HEIGHT=Length (object height)
531 * NAME=CDATA (name for form submission)
532 * USEMAP=URI (client-side image map)
533 * TYPE=ContentType (content-type of object)
534 * CODETYPE=ContentType (content-type of code)
535 * STANDBY=Text (message to show while loading)
536 * TABINDEX=NUMBER (position in tabbing order)
537 * DECLARE (do not instantiate object)
538 * The rest is added as <param name="" value="" /> tags
540 function ImgObject($img, $url) {
541 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
542 $args = split(' ', $url);
544 if (count($args) >= 1) {
545 $url = array_shift($args);
547 foreach ($args as $attr) {
548 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
549 "codetype,standby,tabindex,declare") as $param)
551 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
552 $img->setAttr($param, $m[1]);
558 // now all remaing args are added as <param> to the object
559 foreach ($args as $attr) {
560 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
561 $params[] = HTML::param(array('name' => $m[1],
566 $type = $img->getAttr('type');
568 // TODO: map extension to mime-types if type is not given and php < 4.3
569 if (function_exists('mime_content_type'))
570 $type = mime_content_type($url);
572 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
574 $object->setAttr('class', 'inlineobject');
576 foreach ($params as $param) $object->pushContent($param);
578 if (isBrowserSafari()) {
579 return HTML::embed($object->_attr, $object->_content);
581 $object->pushContent(HTML::embed($object->_attr));
588 // var in php5 deprecated
590 $this->items = array();
593 function push($item) {
594 $this->items[$this->size] = $item;
600 if ($this->size == 0) {
601 return false; // stack is empty
604 return $this->items[$this->size];
613 return $this->items[$this->size - 1];
619 // end class definition
621 function SplitQueryArgs ($query_args = '')
623 // FIXME: use the arg-seperator which might not be &
624 $split_args = split('&', $query_args);
626 while (list($key, $val) = each($split_args))
627 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
628 $args[$m[1]] = $m[2];
632 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
635 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
636 return HTML::strong(array('class' => 'rawurl'),
637 HTML::u(array('class' => 'baduri'),
638 _("BAD phpwiki: URL")));
642 $pagename = urldecode($m[1]);
645 if (empty($pagename) &&
646 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
647 // Convert old style links (to not break diff links in
649 $pagename = urldecode($m[2]);
650 $args = array("action" => $m[1]);
653 $args = SplitQueryArgs($qargs);
656 if (empty($pagename))
657 $pagename = $GLOBALS['request']->getArg('pagename');
659 if (isset($args['action']) && $args['action'] == 'browse')
660 unset($args['action']);
663 if (empty($args['action']))
665 else if (is_safe_action($args['action']))
666 $class = 'wikiaction';
668 if (empty($args['action']) || is_safe_action($args['action']))
669 $class = 'wikiaction';
671 // Don't allow administrative links on unlocked pages.
672 $dbi = $GLOBALS['request']->getDbh();
673 $page = $dbi->getPage($basepage ? $basepage : $pagename);
674 if (!$page->get('locked'))
675 return HTML::span(array('class' => 'wikiunsafe'),
676 HTML::u(_("Lock page to enable link")));
677 $class = 'wikiadmin';
681 $text = HTML::span(array('class' => 'rawurl'), $url);
683 $wikipage = new WikiPageName($pagename);
684 if (!$wikipage->isValid()) {
686 return $WikiTheme->linkBadWikiWord($wikipage, $url);
689 return HTML::a(array('href' => WikiURL($pagename, $args),
695 * A class to assist in parsing wiki pagenames.
697 * Now with subpages and anchors, parsing and passing around
698 * pagenames is more complicated. This should help.
702 /** Short name for page.
704 * This is the value of $name passed to the constructor.
705 * (For use, e.g. as a default label for links to the page.)
709 /** The full page name.
711 * This is the full name of the page (without anchor).
717 * This is the referenced anchor within the page, or the empty string.
723 * @param mixed $name Page name.
724 * WikiDB_Page, WikiDB_PageRevision, or string.
725 * This can be a relative subpage name (like '/SubPage'),
726 * or can be the empty string to refer to the $basename.
728 * @param string $anchor For links to anchors in page.
730 * @param mixed $basename Page name from which to interpret
731 * relative or other non-fully-specified page names.
733 function WikiPageName($name, $basename=false, $anchor=false) {
734 if (is_string($name)) {
735 $this->shortName = $name;
736 if (strstr($name, ':')) {
737 list($moniker, $shortName) = split (":", $name, 2);
738 $map = getInterwikiMap(); // allow overrides to custom maps
739 if (isset($map->_map[$moniker])) {
740 $url = $map->_map[$moniker];
741 if (strstr($url, '%s'))
742 $url = sprintf($url, $shortName);
746 // expand Talk or User, but not to absolute urls!
747 if (strstr($url, '//')) {
748 if ($moniker == 'Talk')
749 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
750 elseif ($moniker == 'User')
755 if (strstr($shortName, '?')) {
756 list($shortName, $dummy) = split("\?", $shortName, 2);
758 $this->shortName = $shortName;
761 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
762 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
764 $name = $this->_pagename($basename) . $name;
766 $name = $this->_normalize_bad_pagename($name);
767 $this->shortName = $name;
772 $name = $this->_pagename($name);
773 $this->shortName = $name;
776 $this->name = $this->_check($name);
777 $this->anchor = (string)$anchor;
784 function getParent() {
786 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
788 return substr($name, 0, -strlen($tail));
791 function isValid($strict = false) {
793 return !isset($this->_errors);
794 return (is_string($this->name) and $this->name != '');
797 function getWarnings() {
799 if (isset($this->_warnings))
800 $warnings = array_merge($warnings, $this->_warnings);
801 if (isset($this->_errors))
802 $warnings = array_merge($warnings, $this->_errors);
806 return sprintf(_("'%s': Bad page name: %s"),
807 $this->shortName, join(', ', $warnings));
810 function _pagename($page) {
811 if (isa($page, 'WikiDB_Page'))
812 return $page->getName();
813 elseif (isa($page, 'WikiDB_PageRevision'))
814 return $page->getPageName();
815 elseif (isa($page, 'WikiPageName'))
817 // '0' or e.g. '1984' should be allowed though
818 if (!is_string($page) and !is_integer($page)) {
819 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
820 $page, gettype($page), get_class($page)),
823 //assert(is_string($page));
827 function _normalize_bad_pagename($name) {
828 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
830 // Punt... You really shouldn't get here.
833 return $request->getArg('pagename');
835 assert($name[0] == SUBPAGE_SEPARATOR);
836 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
837 return substr($name, 1);
841 * Compress internal white-space to single space character.
843 * This leads to problems with loading a foreign charset pagename,
844 * which cannot be deleted anymore, because unknown chars are compressed.
845 * So BEFORE importing a file _check must be done !!!
847 function _check($pagename) {
848 // Compress internal white-space to single space character.
849 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
850 if ($pagename != $orig)
851 $this->_warnings[] = _("White space converted to single space");
853 // Delete any control characters.
854 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
855 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
856 if ($pagename != $orig)
857 $this->_errors[] = _("Control characters not allowed");
860 // Strip leading and trailing white-space.
861 $pagename = trim($pagename);
864 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
865 $pagename = substr($pagename, 1);
866 if ($pagename != $orig)
867 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
869 // ";" is urlencoded, so safe from php arg-delim problems
870 /*if (strstr($pagename, ';')) {
871 $this->_warnings[] = _("';' is deprecated");
872 $pagename = str_replace(';', '', $pagename);
875 // not only for SQL, also to restrict url length
876 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
877 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
878 $this->_errors[] = _("too long");
881 // disallow some chars only on file and cvs
882 if ((DATABASE_TYPE == 'cvs'
883 or DATABASE_TYPE == 'file'
884 or DATABASE_TYPE == 'flatfile')
885 and preg_match('/(:|\.\.)/', $pagename, $m))
887 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
888 $pagename = str_replace('..', '', $pagename);
889 $pagename = str_replace(':', '', $pagename);
897 * Convert old page markup to new-style markup.
899 * @param string $text Old-style wiki markup.
901 * @param string $markup_type
903 * <dt><code>"block"</code> <dd>Convert all markup.
904 * <dt><code>"inline"</code> <dd>Convert only inline markup.
905 * <dt><code>"links"</code> <dd>Convert only link markup.
908 * @return string New-style wiki markup.
910 * @bugs Footnotes don't work quite as before (esp if there are
911 * multiple references to the same footnote. But close enough,
912 * probably for now....
913 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
914 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
915 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
916 * also known to crash, even with Apache1.
918 function ConvertOldMarkup ($text, $markup_type = "block") {
924 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
925 // AnciennesR%E8glesDeFormatage crashes.
926 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
927 // also known to crash, even with Apache1.
929 // I suspect this only to crash with Apache2 and IIS.
930 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
931 and preg_match("/plugin CreateToc/", $text))
933 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
934 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
935 ._("Skipped."), E_USER_WARNING);
937 //if (!DEBUG) return $text;
942 /*****************************************************************
943 * Conversions for inline markup:
950 // escape escaped brackets
954 // change ! escapes to ~'s.
955 global $WikiNameRegexp, $request;
956 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
957 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
958 if (check_php_version(4,3,9)) {
959 $map = getInterwikiMap();
960 if ($map_regex = $map->getRegexp())
961 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
963 $bang_esc[] = $WikiNameRegexp;
964 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
967 $subs["links"] = array($orig, $repl);
969 // Temporarily URL-encode pairs of underscores in links to hide
970 // them from the re for bold markup.
971 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
972 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
975 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
978 // Convert footnote references.
979 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
980 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
982 // Convert old style emphases to HTML style emphasis.
983 $orig[] = '/__(.*?)__/';
984 $repl[] = '<strong>\\1</strong>';
985 $orig[] = "/''(.*?)''/";
986 $repl[] = '<em>\\1</em>';
988 // Escape nestled markup.
989 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
992 // in old markup headings only allowed at beginning of line
996 // Convert URL-encoded pairs of underscores in links back to
997 // real underscores after bold markup has been converted.
998 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
999 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1001 $subs["inline"] = array($orig, $repl);
1003 /*****************************************************************
1004 * Patterns which match block markup constructs which take
1005 * special handling...
1009 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1011 $blockpats[] = '\|(?:.*\n\|)*';
1014 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1016 // Footnote definitions
1017 $blockpats[] = '\[\s*(\d+)\s*\]';
1021 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1025 $blockpats[] = '!{1,3}[^!]';
1027 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1028 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1030 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1031 . join("|", $blockpats)
1036 if ($markup_type != "block") {
1037 list ($orig, $repl) = $subs[$markup_type];
1038 return preg_replace($orig, $repl, $text);
1041 list ($orig, $repl) = $subs['inline'];
1044 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1045 // AnciennesR%E8glesDeFormatage and more
1046 // See http://www.pcre.org/pcre.txt LIMITATIONS
1047 while (preg_match($block_re, $text, $m)) {
1048 $text = substr($text, strlen($m[0]));
1049 list (,$leading_text, $block) = $m;
1052 if (strchr(" \t", $block[0])) {
1054 $prefix = "<pre>\n";
1055 $suffix = "\n</pre>\n";
1057 elseif ($block[0] == '|') {
1059 $prefix = "<?plugin OldStyleTable\n";
1062 elseif (strchr("#*;", $block[0])) {
1063 // Old-style list item
1064 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1065 list (,$ind,$bullet) = $m;
1066 $block = substr($block, strlen($m[0]));
1068 $indent = str_repeat(' ', strlen($ind));
1069 if ($bullet[0] == ';') {
1070 //$term = ltrim(substr($bullet, 1));
1071 //return $indent . $term . "\n" . $indent . ' ';
1072 $prefix = $ind . $bullet;
1075 $prefix = $indent . $bullet . ' ';
1077 elseif ($block[0] == '[') {
1078 // Footnote definition
1079 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1081 $block = substr($block, strlen($m[0]));
1082 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1084 elseif ($block[0] == '<') {
1086 // HACK: no inline markup...
1090 elseif ($block[0] == '!') {
1092 preg_match('/^!{1,3}/', $block, $m);
1094 $block = substr($block, strlen($m[0]));
1100 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1101 if ($block) $block = preg_replace($orig, $repl, $block);
1102 $out .= $leading_text;
1107 return $out . preg_replace($orig, $repl, $text);
1113 * Expand tabs in string.
1115 * Converts all tabs to (the appropriate number of) spaces.
1117 * @param string $str
1118 * @param integer $tab_width
1121 function expand_tabs($str, $tab_width = 8) {
1122 $split = split("\t", $str);
1123 $tail = array_pop($split);
1125 foreach ($split as $hunk) {
1127 $pos = strlen(strrchr($expanded, "\n")) - 1;
1128 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1130 return substr($expanded, 1) . $tail;
1134 * Split WikiWords in page names.
1136 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1137 * places like page titles. This is rumored to help search engines
1140 * @param $page string The page name.
1142 * @return string The split name.
1144 function SplitPagename ($page) {
1146 if (preg_match("/\s/", $page))
1147 return $page; // Already split --- don't split any more.
1149 // This algorithm is specialized for several languages.
1150 // (Thanks to Pierrick MEIGNEN)
1151 // Improvements for other languages welcome.
1154 // This mess splits between a lower-case letter followed by
1155 // either an upper-case or a numeral; except that it wont
1156 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1157 switch ($GLOBALS['LANG']) {
1162 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1165 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1168 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1169 // This the single-letter words 'I' and 'A' from any following
1170 // capitalized words.
1171 switch ($GLOBALS['LANG']) {
1173 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1176 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1179 // Split numerals from following letters.
1180 $RE[] = '/(\d)([[:alpha:]])/';
1181 // Split at subpage seperators. TBD in Theme.php
1182 $RE[] = "/([^${sep}]+)(${sep})/";
1183 $RE[] = "/(${sep})([^${sep}]+)/";
1185 foreach ($RE as $key)
1186 $RE[$key] = pcre_fix_posix_classes($key);
1189 foreach ($RE as $regexp) {
1190 $page = preg_replace($regexp, '\\1 \\2', $page);
1195 function NoSuchRevision (&$request, $page, $version) {
1196 $html = HTML(HTML::h2(_("Revision Not Found")),
1197 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1198 $version, WikiLink($page, 'auto'))));
1199 include_once('lib/Template.php');
1200 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1206 * Get time offset for local time zone.
1208 * @param $time time_t Get offset for this time. Default: now.
1209 * @param $no_colon boolean Don't put colon between hours and minutes.
1210 * @return string Offset as a string in the format +HH:MM.
1212 function TimezoneOffset ($time = false, $no_colon = false) {
1213 if ($time === false)
1215 $secs = date('Z', $time);
1224 $colon = $no_colon ? '' : ':';
1225 $mins = intval(($secs + 30) / 60);
1226 return sprintf("%s%02d%s%02d",
1227 $sign, $mins / 60, $colon, $mins % 60);
1232 * Format time in ISO-8601 format.
1234 * @param $time time_t Time. Default: now.
1235 * @return string Date and time in ISO-8601 format.
1237 function Iso8601DateTime ($time = false) {
1238 if ($time === false)
1240 $tzoff = TimezoneOffset($time);
1241 $date = date('Y-m-d', $time);
1242 $time = date('H:i:s', $time);
1243 return $date . 'T' . $time . $tzoff;
1247 * Format time in RFC-2822 format.
1249 * @param $time time_t Time. Default: now.
1250 * @return string Date and time in RFC-2822 format.
1252 function Rfc2822DateTime ($time = false) {
1253 if ($time === false)
1255 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1259 * Format time in RFC-1123 format.
1261 * @param $time time_t Time. Default: now.
1262 * @return string Date and time in RFC-1123 format.
1264 function Rfc1123DateTime ($time = false) {
1265 if ($time === false)
1267 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1270 /** Parse date in RFC-1123 format.
1272 * According to RFC 1123 we must accept dates in the following
1275 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1276 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1277 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1279 * (Though we're only allowed to generate dates in the first format.)
1281 function ParseRfc1123DateTime ($timestr) {
1282 $timestr = trim($timestr);
1283 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1284 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1286 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1288 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1289 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1291 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1292 if ($year < 70) $year += 2000;
1293 elseif ($year < 100) $year += 1900;
1295 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1296 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1298 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1305 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1307 return false; // failed
1312 * Format time to standard 'ctime' format.
1314 * @param $time time_t Time. Default: now.
1315 * @return string Date and time.
1317 function CTime ($time = false)
1319 if ($time === false)
1321 return date("D M j H:i:s Y", $time);
1326 * Format number as kilobytes or bytes.
1327 * Short format is used for PageList
1328 * Long format is used in PageInfo
1330 * @param $bytes int. Default: 0.
1331 * @param $longformat bool. Default: false.
1332 * @return class FormattedText (XmlElement.php).
1334 function ByteFormatter ($bytes = 0, $longformat = false) {
1337 if ($bytes < 1024) {
1339 $size = fmt("%s b", $bytes);
1341 $size = fmt("%s bytes", $bytes);
1344 $kb = round($bytes / 1024, 1);
1346 $size = fmt("%s k", $kb);
1348 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1354 * Internationalized printf.
1356 * This is essentially the same as PHP's built-in printf
1357 * with the following exceptions:
1359 * <li> It passes the format string through gettext().
1360 * <li> It supports the argument reordering extensions.
1367 * __printf("Differences between versions %s and %s of %s",
1368 * $new_link, $old_link, $page_link);
1371 * Then in locale/po/de.po, one can reorder the printf arguments:
1374 * msgid "Differences between %s and %s of %s."
1375 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1378 * (Note that while PHP tries to expand $vars within double-quotes,
1379 * the values in msgstr undergo no such expansion, so the '$'s
1382 * One shouldn't use reordered arguments in the default format string.
1383 * Backslashes in the default string would be necessary to escape the
1384 * '$'s, and they'll cause all kinds of trouble....
1386 function __printf ($fmt) {
1387 $args = func_get_args();
1389 echo __vsprintf($fmt, $args);
1393 * Internationalized sprintf.
1395 * This is essentially the same as PHP's built-in printf with the
1396 * following exceptions:
1399 * <li> It passes the format string through gettext().
1400 * <li> It supports the argument reordering extensions.
1405 function __sprintf ($fmt) {
1406 $args = func_get_args();
1408 return __vsprintf($fmt, $args);
1412 * Internationalized vsprintf.
1414 * This is essentially the same as PHP's built-in printf with the
1415 * following exceptions:
1418 * <li> It passes the format string through gettext().
1419 * <li> It supports the argument reordering extensions.
1424 function __vsprintf ($fmt, $args) {
1425 $fmt = gettext($fmt);
1426 // PHP's sprintf doesn't support variable with specifiers,
1427 // like sprintf("%*s", 10, "x"); --- so we won't either.
1429 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1430 // Format string has '%2$s' style argument reordering.
1431 // PHP doesn't support this.
1432 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1433 // literal variable name substitution only to keep locale
1434 // strings uncluttered
1435 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1436 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1438 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1441 // Reorder arguments appropriately.
1442 foreach($m[1] as $argnum) {
1443 if ($argnum < 1 || $argnum > count($args))
1444 trigger_error(sprintf(_("%s: argument index out of range"),
1445 $argnum), E_USER_WARNING);
1446 $newargs[] = $args[$argnum - 1];
1451 // Not all PHP's have vsprintf, so...
1452 array_unshift($args, $fmt);
1453 return call_user_func_array('sprintf', $args);
1456 function file_mtime ($filename) {
1457 if ($stat = @stat($filename))
1463 function sort_file_mtime ($a, $b) {
1464 $ma = file_mtime($a);
1465 $mb = file_mtime($b);
1466 if (!$ma or !$mb or $ma == $mb) return 0;
1467 return ($ma > $mb) ? -1 : 1;
1472 * Build an array in $this->_fileList of files from $dirname.
1473 * Subdirectories are not traversed.
1475 * (This was a function LoadDir in lib/loadsave.php)
1476 * See also http://www.php.net/manual/en/function.readdir.php
1478 function getFiles($exclude='', $sortby='', $limit='') {
1479 $list = $this->_fileList;
1482 require_once('lib/PageList.php');
1483 switch (Pagelist::sortby($sortby, 'db')) {
1484 case 'pagename ASC': break;
1485 case 'pagename DESC':
1486 $list = array_reverse($list);
1489 usort($list,'sort_file_mtime');
1492 usort($list,'sort_file_mtime');
1493 $list = array_reverse($list);
1498 return array_splice($list, 0, $limit);
1502 function _filenameSelector($filename) {
1503 if (! $this->_pattern )
1506 if (! $this->_pcre_pattern )
1507 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1508 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1513 function fileSet($directory, $filepattern = false) {
1514 $this->_fileList = array();
1515 $this->_pattern = $filepattern;
1517 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1519 $this->_case = !isWindows();
1520 $this->_pathsep = '/';
1522 if (empty($directory)) {
1523 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1525 return; // early return
1528 @ $dir_handle = opendir($dir=$directory);
1529 if (empty($dir_handle)) {
1530 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1531 $dir), E_USER_NOTICE);
1532 return; // early return
1535 while ($filename = readdir($dir_handle)) {
1536 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1538 if ($this->_filenameSelector($filename)) {
1539 array_push($this->_fileList, "$filename");
1540 //trigger_error(sprintf(_("found file %s"), $filename),
1541 // E_USER_NOTICE); //debugging
1544 closedir($dir_handle);
1550 // expands a list containing regex's to its matching entries
1551 class ListRegexExpand {
1552 //var $match, $list, $index, $case_sensitive;
1553 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1554 $this->match = $match;
1555 $this->list = &$list;
1556 $this->case_sensitive = $case_sensitive;
1557 //$this->index = false;
1559 function listMatchCallback ($item, $key) {
1560 $quoted = str_replace('/','\/',$item);
1561 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1563 unset($this->list[$this->index]);
1564 $this->list[] = $item;
1567 function expandRegex ($index, &$pages) {
1568 $this->index = $index;
1569 array_walk($pages, array($this, 'listMatchCallback'));
1574 // Convert fileglob to regex style:
1575 // Convert some wildcards to pcre style, escape the rest
1576 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1577 // Fixed bug #994994: "/" in $glob.
1578 function glob_to_pcre ($glob) {
1579 // check simple case: no need to escape
1580 $escape = '\[](){}=!<>|:/';
1581 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1583 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1584 $glob = strtr($glob, "\\", "\xff");
1585 $glob = str_replace("/", "\\/", $glob);
1586 // first convert some unescaped expressions to pcre style: . => \.
1588 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1589 "\\1\xff\\2", $glob);
1592 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1593 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1594 if (!preg_match('/^[\?\*]/', $glob))
1596 if (!preg_match('/[\?\*]$/', $glob))
1599 // Fixes Bug 1182997
1600 // .*? handled above, now escape the rest
1601 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1602 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1604 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1606 $re = preg_replace('/\xff/', '', $re);
1610 function glob_match ($glob, $against, $case_sensitive = true) {
1611 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1615 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1616 $list = explode(',',$input);
1617 // expand wildcards from list of $allnames
1618 if (preg_match('/[\?\*]/',$input)) {
1619 // Optimizing loop invariants:
1620 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1621 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1623 if (preg_match('/[\?\*]/',$f)) {
1625 $expand = new ListRegexExpand($list,
1626 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1627 $expand->expandRegex($i, $allnames);
1634 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1635 function explodePageList($input, $include_empty=false, $sortby='pagename',
1636 $limit='', $exclude='') {
1637 include_once("lib/PageList.php");
1638 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1641 // Class introspections
1644 * Determine whether object is of a specified type.
1645 * In PHP builtin since 4.2.0 as is_a()
1646 * is_a() deprecated in PHP 5, in favor of instanceof operator
1648 * @param $object object An object.
1649 * @param $class string Class name.
1650 * @return bool True iff $object is a $class
1651 * or a sub-type of $class.
1653 function isa ($object, $class) {
1654 //if (check_php_version(5))
1655 // return $object instanceof $class;
1656 if (check_php_version(4,2) and !check_php_version(5))
1657 return is_a($object, $class);
1659 $lclass = check_php_version(5) ? $class : strtolower($class);
1660 return is_object($object)
1661 && ( strtolower(get_class($object)) == strtolower($class)
1662 || is_subclass_of($object, $lclass) );
1665 /** Determine whether (possible) object has method.
1667 * @param $object mixed Object
1668 * @param $method string Method name
1669 * @return bool True iff $object is an object with has method $method.
1671 function can ($object, $method) {
1672 return is_object($object) && method_exists($object, strtolower($method));
1675 /** Determine whether a function is okay to use.
1677 * Some providers (e.g. Lycos) disable some of PHP functions for
1678 * "security reasons." This makes those functions, of course,
1679 * unusable, despite the fact the function_exists() says they
1682 * This function test to see if a function exists and is not
1683 * disallowed by PHP's disable_functions config setting.
1685 * @param string $function_name Function name
1686 * @return bool True iff function can be used.
1688 function function_usable($function_name) {
1690 if (!is_array($disabled)) {
1691 $disabled = array();
1692 // Use get_cfg_var since ini_get() is one of the disabled functions
1693 // (on Lycos, at least.)
1694 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1695 foreach ($split as $f)
1696 $disabled[strtolower($f)] = true;
1699 return ( function_exists($function_name)
1700 and ! isset($disabled[strtolower($function_name)])
1707 * This is used for generating ETags.
1709 function wikihash ($x) {
1710 if (is_scalar($x)) {
1713 elseif (is_array($x)) {
1715 return md5(serialize($x));
1717 elseif (is_object($x)) {
1720 trigger_error("Can't hash $x", E_USER_ERROR);
1725 * Seed the random number generator.
1727 * better_srand() ensures the randomizer is seeded only once.
1729 * How random do you want it? See:
1730 * http://www.php.net/manual/en/function.srand.php
1731 * http://www.php.net/manual/en/function.mt-srand.php
1733 function better_srand($seed = '') {
1734 static $wascalled = FALSE;
1736 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1737 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1739 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1743 function rand_ascii($length = 1) {
1746 for ($i = 1; $i <= $length; $i++) {
1747 // return only typeable 7 bit ascii, avoid quotes
1748 if (function_exists('mt_rand'))
1749 $s .= chr(mt_rand(40, 126));
1751 // the usually bad glibc srand()
1752 $s .= chr(rand(40, 126));
1757 /* by Dan Frankowski.
1759 function rand_ascii_readable ($length = 6) {
1760 // Pick a few random letters or numbers
1763 // Don't use 1lI0O, because they're hard to read
1764 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1765 $letter_len = strlen($letters);
1766 for ($i=0; $i < $length; $i++) {
1767 if (function_exists('mt_rand'))
1768 $word .= $letters[mt_rand(0, $letter_len-1)];
1770 $word .= $letters[rand(0, $letter_len-1)];
1776 * Recursively count all non-empty elements
1777 * in array of any dimension or mixed - i.e.
1778 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1779 * See http://www.php.net/manual/en/function.count.php
1781 function count_all($arg) {
1782 // skip if argument is empty
1784 //print_r($arg); //debugging
1786 // not an array, return 1 (base case)
1789 // else call recursively for all elements $arg
1790 foreach($arg as $key => $val)
1791 $count += count_all($val);
1796 function isSubPage($pagename) {
1797 return (strstr($pagename, SUBPAGE_SEPARATOR));
1800 function subPageSlice($pagename, $pos) {
1801 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1802 $pages = array_slice($pages,$pos,1);
1809 * Class for "popping up" and alert box. (Except that right now, it doesn't
1813 * This is a hackish and needs to be refactored. However it would be nice to
1814 * unify all the different methods we use for showing Alerts and Dialogs.
1815 * (E.g. "Page deleted", login form, ...)
1820 * @param object $request
1821 * @param mixed $head Header ("title") for alert box.
1822 * @param mixed $body The text in the alert box.
1823 * @param hash $buttons An array mapping button labels to URLs.
1824 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1826 function Alert($head, $body, $buttons=false) {
1827 if ($buttons === false)
1830 if (is_array($body)) {
1832 foreach ($body as $li) {
1833 $html->pushContent(HTML::li($li));
1837 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1838 $this->_buttons = $buttons;
1842 * Show the alert box.
1847 $tokens = $this->_tokens;
1848 $tokens['BUTTONS'] = $this->_getButtons();
1850 $request->discardOutput();
1851 $tmpl = new Template('dialog', $request, $tokens);
1857 function _getButtons() {
1860 $buttons = $this->_buttons;
1862 $buttons = array(_("Okay") => $request->getURLtoSelf());
1865 foreach ($buttons as $label => $url)
1866 print "$label $url\n";
1867 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1868 return new XmlContent($out);
1873 // 1.3.9-p1 => 1030.091
1874 // 1.3.10pre => 1030.099
1875 // 1.3.11pre-20041120 => 1030.1120041120
1876 // 1.3.12-rc1 => 1030.119
1877 function phpwiki_version() {
1878 static $PHPWIKI_VERSION;
1879 if (!isset($PHPWIKI_VERSION)) {
1880 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1881 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1882 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1883 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1884 $PHPWIKI_VERSION -= 0.01;
1886 return $PHPWIKI_VERSION;
1889 function phpwiki_gzhandler($ob) {
1890 if (function_exists('gzencode'))
1891 $ob = gzencode($ob);
1892 $GLOBALS['request']->_ob_get_length = strlen($ob);
1893 if (!headers_sent()) {
1894 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1899 function isWikiWord($word) {
1900 global $WikiNameRegexp;
1901 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1902 return preg_match("/^$WikiNameRegexp\$/",$word);
1905 // needed to store serialized objects-values only (perm, pref)
1906 function obj2hash ($obj, $exclude = false, $fields = false) {
1908 if (! $fields ) $fields = get_object_vars($obj);
1909 foreach ($fields as $key => $val) {
1910 if (is_array($exclude)) {
1911 if (in_array($key, $exclude)) continue;
1919 * isUtf8String($string) - cheap utf-8 detection
1921 * segfaults for strings longer than 10kb!
1922 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1923 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1925 function isUtf8String( $s ) {
1926 $ptrASCII = '[\x00-\x7F]';
1927 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1928 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1929 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1930 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1931 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1932 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1936 * Check for UTF-8 URLs; Internet Explorer produces these if you
1937 * type non-ASCII chars in the URL bar or follow unescaped links.
1938 * Requires urldecoded pagename.
1939 * Fixes sf.net bug #953949
1941 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1943 function fixTitleEncoding( $s ) {
1948 if (empty($s)) return $s;
1950 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1952 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1953 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1955 $isutf = ($ishigh ? isUtf8String($s) : true);
1956 $locharset = strtolower($charset);
1958 if( $locharset != "utf-8" and $ishigh and $isutf )
1959 $s = charset_convert('UTF-8', $locharset, $s);
1960 if ($locharset == "utf-8" and $ishigh and !$isutf )
1961 return utf8_encode( $s );
1963 // Other languages can safely leave this function, or replace
1964 // it with one to detect and convert another legacy encoding.
1969 * MySQL fulltext index doesn't grok utf-8, so we
1970 * need to fold cases and convert to hex.
1971 * src: languages/Language.php:stripForSearch() from mediawiki
1974 function stripForSearch( $string ) {
1975 global $wikiLowerChars;
1976 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1977 return preg_replace(
1978 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1979 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1985 * Workaround for allow_url_fopen, to get the content of an external URI.
1986 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1987 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1989 function url_get_contents( $uri ) {
1990 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1991 return @file_get_contents($uri);
1993 require_once("lib/HttpClient.php");
1994 $bits = parse_url($uri);
1995 $host = $bits['host'];
1996 $port = isset($bits['port']) ? $bits['port'] : 80;
1997 $path = isset($bits['path']) ? $bits['path'] : '/';
1998 if (isset($bits['query'])) {
1999 $path .= '?'.$bits['query'];
2001 $client = new HttpClient($host, $port);
2002 $client->use_gzip = false;
2003 if (!$client->get($path)) {
2006 return $client->getContent();
2012 * Generate consecutively named strings:
2013 * Name, Name2, Name3, ...
2015 function GenerateId($name) {
2016 static $ids = array();
2017 if (empty($ids[$name])) {
2022 return $name . $ids[$name];
2026 // from IncludePage. To be of general use.
2027 // content: string or array of strings
2028 function firstNWordsOfContent( $n, $content ) {
2029 if ($content and $n > 0) {
2030 if (is_array($content)) {
2031 // fixme: return a list of lines then?
2032 //$content = join("\n", $content);
2033 //$return_array = true;
2035 foreach ($content as $line) {
2036 $words = explode(' ', $line);
2037 if ($wordcount + count($words) > $n) {
2038 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2039 . sprintf(_("... (first %s words)"), $n);
2042 $wordcount += count($words);
2048 // fixme: use better whitespace/word seperators
2049 $words = explode(' ', $content);
2050 if (count($words) > $n) {
2051 return join(' ', array_slice($words, 0, $n))
2052 . sprintf(_("... (first %s words)"), $n);
2062 // moved from lib/plugin/IncludePage.php
2063 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2064 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2066 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
2067 . " \\s*$\\n?" // possible blank lines
2068 . " ( (?: ^.*\\n? )*? )" // some lines
2069 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2070 implode("\n", $content),
2072 // Strip trailing blanks lines and ---- <hr>s
2073 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2075 $text = $match[1] . $section ."\n". $text;
2076 return explode("\n", $text);
2079 $mesg = $page ." ". $section;
2082 return array(sprintf(_("<%s: no such section>"), $mesg));
2085 // use this faster version: only load ExternalReferrer if we came from an external referrer
2086 function isExternalReferrer(&$request) {
2087 if ($referrer = $request->get('HTTP_REFERER')) {
2088 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2089 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2090 require_once("lib/ExternalReferrer.php");
2091 $se = new SearchEngines();
2092 return $se->parseSearchQuery($referrer);
2094 //if (DEBUG) return array('query' => 'wiki');
2099 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2101 function loadPhpExtension($extension) {
2102 if (!extension_loaded($extension)) {
2103 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2104 $soname = ($isWindows ? 'php_' : '')
2106 . ($isWindows ? '.dll' : '.so');
2110 return extension_loaded($extension);
2113 function charset_convert($from, $to, $data) {
2115 //$wikicharset = strtolower($CHARSET);
2116 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2117 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2118 return utf8_decode($data);
2119 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2120 return utf8_encode($data);
2122 if (loadPhpExtension("iconv")) {
2123 $tmpdata = iconv($from, $to, $data);
2125 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2129 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2134 function string_starts_with($string, $prefix) {
2135 return (substr($string, 0, strlen($prefix)) == $prefix);
2137 function string_ends_with($string, $suffix) {
2138 return (substr($string, -strlen($suffix)) == $suffix);
2140 function array_remove($arr,$value) {
2141 return array_values(array_diff($arr,array($value)));
2145 * Ensure that the script will have another $secs time left.
2146 * Works only if safe_mode is off.
2147 * For example not to timeout on waiting socket connections.
2148 * Use the socket timeout as arg.
2150 function longer_timeout($secs = 30) {
2151 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2152 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2153 if ($timeleft < $secs)
2154 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2157 function printSimpleTrace($bt) {
2159 echo "\nTraceback:\n";
2160 if (function_exists('debug_print_backtrace')) { // >= 5
2161 debug_print_backtrace();
2163 foreach ($bt as $i => $elem) {
2164 if (!array_key_exists('file', $elem)) {
2167 //echo join(" ",array_values($elem)),"\n";
2168 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2174 * Return the used process memory, in bytes.
2175 * Enable the section which will work for you. They are very slow.
2176 * Special quirks for Windows: Requires cygwin.
2178 function getMemoryUsage() {
2179 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2180 if (function_exists('memory_get_usage') and memory_get_usage()) {
2181 return memory_get_usage();
2182 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2183 $mem = $u['ru_maxrss'];
2184 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2185 // what we want is the process memory only: apache or php (if CGI)
2188 // win32_ps_stat_proc, win32_ps_stat_mem
2189 if (function_exists('win32_ps_list_procs')) {
2190 $info = win32_ps_stat_proc($pid);
2191 $memstr = $info['mem']['working_set_size'];
2193 // This works only if it's a cygwin process (apache or php).
2194 // Requires a newer cygwin
2195 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2197 // if it's native windows use something like this:
2198 // (requires pslist from sysinternals.com, grep, sed and perl)
2199 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2201 return (integer) trim($memstr);
2204 //%MEM: Percentage of total memory in use by this process
2205 //VSZ: Total virtual memory size, in 1K blocks.
2206 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2207 //CPU time used by process since it started.
2208 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2209 $memstr = exec("ps -orss -p $pid|sed 1d");
2210 return (integer) trim($memstr);
2215 * @param var $needle
2216 * @param array $haystack one-dimensional numeric array only, no hash
2218 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2219 It will return false if not found or the index where it was found.
2220 From dennis.decoene@moveit.be http://www.php.net/array_search
2222 function binary_search($needle, $haystack) {
2223 $high = count($haystack);
2226 while (($high - $low) > 1) {
2227 $probe = floor(($high + $low) / 2);
2228 if ($haystack[$probe] < $needle) {
2230 } elseif ($haystack[$probe] == $needle) {
2231 $high = $low = $probe;
2237 if ($high == count($haystack) || $haystack[$high] != $needle) {
2244 function is_localhost($url = false) {
2246 global $HTTP_SERVER_VARS;
2247 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2252 * Take a string and quote it sufficiently to be passed as a Javascript
2253 * string between ''s
2255 function javascript_quote_string($s) {
2256 return str_replace("'", "\'", $s);
2259 function isSerialized($s) {
2260 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2263 // $Log: not supported by cvs2svn $
2264 // Revision 1.273 2008/03/22 21:43:21 rurban
2265 // Fix syntax error from r1.272
2267 // Revision 1.272 2008/03/21 20:35:52 rurban
2268 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
2269 // Object tags now render as label correctly and param tags are also added.
2271 // Revision 1.271 2008/03/17 19:11:06 rurban
2272 // adedd isSerialized: get rid of @ error protection in unserialize
2273 // revert & links
2274 // protect $WikiTheme->VALID_LINKS
2275 // replace strtr by preg_replace; document problem (still exists?
2276 // Todo: glob pattern test)
2278 // Revision 1.270 2008/01/31 20:21:12 vargenau
2279 // Valid HTML: escape ampersand
2281 // Revision 1.269 2008/01/24 19:17:03 rurban
2282 // add javascript_quote_string for Theme
2284 // Revision 1.268 2007/09/15 12:28:46 rurban
2285 // Improve multi-page format handling: abstract _DumpHtmlToDir. get rid of non-external pdf, non-global VALID_LINKS
2287 // Revision 1.267 2007/09/12 19:32:29 rurban
2288 // link only VALID_LINKS with pagelist HTML_DUMP
2290 // Revision 1.266 2007/09/01 13:24:23 rurban
2291 // add INSECURE_ACTIONS_LOCALHOST_ONLY. advanced security settings
2293 // Revision 1.265 2007/08/08 18:47:14 rurban
2294 // * Fix EmailNotify for Subpages: Unknown modifier ? at any page save.
2295 // Quoting error on glob_match.
2296 // * Fix binary_search
2298 // Revision 1.264 2007/07/15 17:39:42 rurban
2299 // add binary_search. enable memory ps calls
2301 // Revision 1.263 2007/07/14 12:05:29 rurban
2302 // add url field to WikiPageName for interwiki expansion
2304 // Revision 1.262 2007/06/07 17:02:01 rurban
2305 // fix display of pagenames containing ":" in certain lists
2307 // Revision 1.261 2007/06/01 06:37:53 rurban
2308 // use native debug_print_backtrace
2310 // Revision 1.260 2007/02/17 14:15:21 rurban
2311 // fix ImgLink params: $ori_url
2313 // Revision 1.259 2007/01/20 11:41:38 rurban
2314 // WikiPagename::_check: add flatfile support
2316 // Revision 1.258 2007/01/07 18:43:51 rurban
2317 // Remove FileFinder dependency for loadPhpExtension()
2319 // Revision 1.257 2007/01/03 21:24:56 rurban
2320 // Disable noisy ps subprocess on DEBUG. Turn it on explicitly on memory debugging. Add convert_charset helper. Use convert_charset().
2322 // Revision 1.256 2007/01/02 13:23:49 rurban
2323 // ftnt_${footnum}: do not confuse old php string definition parsers. Clarify API: sortby,limit and exclude are strings.
2325 // Revision 1.255 2006/12/22 16:53:38 rurban
2326 // Try to dl() load the iconv extension, if not already loaded
2328 // Revision 1.254 2006/12/02 19:53:05 rurban
2329 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2330 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2333 // Revision 1.253 2006/08/25 22:20:52 rurban
2334 // better split subpages at sep
2336 // Revision 1.252 2006/06/18 11:03:36 rurban
2337 // support rc version
2339 // Revision 1.251 2006/03/19 15:01:00 rurban
2340 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2342 // Revision 1.250 2006/03/07 20:45:44 rurban
2343 // wikihash for php-5.1
2345 // Revision 1.249 2005/10/30 14:24:33 rurban
2346 // move rand_ascii_readable from Captcha to stdlib
2348 // Revision 1.248 2005/10/29 14:18:30 uckelman
2349 // Added is_a() deprecation note.
2351 // Revision 1.247 2005/10/10 20:31:21 rurban
2354 // Revision 1.246 2005/10/10 19:38:48 rurban
2357 // Revision 1.245 2005/09/18 16:01:09 rurban
2358 // trick to send the correct gzipped Content-Length
2360 // Revision 1.244 2005/09/11 13:24:33 rurban
2361 // fix shortname, dont quote twice in ListRegexExpand
2363 // Revision 1.243 2005/08/06 15:01:38 rurban
2364 // workaround php VBASIC alike limitation: allow integer pagenames
2366 // Revision 1.242 2005/08/06 13:07:04 rurban
2367 // quote paths correctly (not the best method though)
2369 // Revision 1.241 2005/05/06 16:54:19 rurban
2370 // support optional EXTERNAL_LINK_TARGET, default: _blank
2372 // Revision 1.240 2005/04/23 11:15:49 rurban
2373 // handle allowed inlined objects within INLINE_IMAGES
2375 // Revision 1.239 2005/04/01 16:11:42 rurban
2378 // Revision 1.238 2005/03/04 16:29:14 rurban
2379 // Fixed bug #994994 (escape / in glob)
2380 // Optimized glob_to_pcre within fileSet() matching.
2382 // Revision 1.237 2005/02/12 17:22:18 rurban
2383 // locale update: missing . : fixed. unified strings
2384 // proper linebreaks
2386 // Revision 1.236 2005/02/08 13:41:32 rurban
2389 // Revision 1.235 2005/02/04 11:54:48 rurban
2392 // Revision 1.234 2005/02/03 05:09:25 rurban
2393 // Talk: + User: fix
2395 // Revision 1.233 2005/02/02 20:40:12 rurban
2396 // fix Talk: and User: names and links
2398 // Revision 1.232 2005/02/02 19:34:09 rurban
2399 // more maps: Talk, User
2401 // Revision 1.231 2005/01/30 19:48:52 rurban
2402 // enable ps memory on unix
2404 // Revision 1.230 2005/01/25 07:10:51 rurban
2405 // add getMemoryUsage to stdlib
2407 // Revision 1.229 2005/01/21 11:51:22 rurban
2410 // Revision 1.228 2005/01/17 20:28:30 rurban
2411 // Allow more pagename chars: Limit only on certain backends.
2412 // Re-Allow : and ; and control chars on non-file backends.
2414 // Revision 1.227 2005/01/14 18:32:08 uckelman
2415 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2416 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2417 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2418 // conversion of '__' into '<strong>', and then unhidden afterwards.
2420 // Revision 1.226 2004/12/26 17:12:06 rurban
2421 // avoid stdargs in url, php5 fixes
2423 // Revision 1.225 2004/12/22 19:02:29 rurban
2424 // fix glob for starting * or ?
2426 // Revision 1.224 2004/12/20 12:11:50 rurban
2427 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2428 // not reproducable other than on sf.net, but this seems to fix it.
2430 // Revision 1.223 2004/12/18 16:49:29 rurban
2431 // fix RPC for !USE_PATH_INFO, add debugging helper
2433 // Revision 1.222 2004/12/17 16:40:45 rurban
2434 // add not yet used url helper
2436 // Revision 1.221 2004/12/06 19:49:58 rurban
2437 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2438 // renamed delete_page to purge_page.
2439 // enable action=edit&version=-1 to force creation of a new version.
2440 // added BABYCART_PATH config
2441 // fixed magiqc in adodb.inc.php
2442 // and some more docs
2444 // Revision 1.220 2004/11/30 17:47:41 rurban
2445 // added mt_srand, check for native isa
2447 // Revision 1.219 2004/11/26 18:39:02 rurban
2448 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2450 // Revision 1.218 2004/11/25 08:28:48 rurban
2453 // Revision 1.217 2004/11/16 17:31:03 rurban
2454 // re-enable old block markup conversion
2456 // Revision 1.216 2004/11/11 18:31:26 rurban
2457 // add simple backtrace on such general failures to get at least an idea where
2459 // Revision 1.215 2004/11/11 14:34:12 rurban
2460 // minor clarifications
2462 // Revision 1.214 2004/11/11 11:01:20 rurban
2463 // fix loadPhpExtension
2465 // Revision 1.213 2004/11/01 10:43:57 rurban
2466 // seperate PassUser methods into seperate dir (memory usage)
2467 // fix WikiUser (old) overlarge data session
2468 // remove wikidb arg from various page class methods, use global ->_dbi instead
2471 // Revision 1.212 2004/10/22 09:15:39 rurban
2472 // Alert::show has no arg anymore
2474 // Revision 1.211 2004/10/22 09:05:11 rurban
2475 // added longer_timeout (HttpClient)
2478 // Revision 1.210 2004/10/14 21:06:02 rurban
2479 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2481 // Revision 1.209 2004/10/14 19:19:34 rurban
2482 // loadsave: check if the dumped file will be accessible from outside.
2483 // and some other minor fixes. (cvsclient native not yet ready)
2485 // Revision 1.208 2004/10/12 13:13:20 rurban
2486 // php5 compatibility (5.0.1 ok)
2488 // Revision 1.207 2004/09/26 12:21:40 rurban
2489 // removed old log entries.
2490 // added persistent start_debug on internal links and DEBUG
2491 // added isExternalReferrer (not yet used)
2493 // Revision 1.206 2004/09/25 16:28:36 rurban
2494 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2496 // Revision 1.205 2004/09/23 13:59:35 rurban
2497 // Before removing a page display a sample of 100 words.
2499 // Revision 1.204 2004/09/17 13:19:15 rurban
2500 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2503 // Revision 1.203 2004/09/16 08:00:52 rurban
2504 // just some comments
2506 // Revision 1.202 2004/09/14 10:11:44 rurban
2507 // start 2nd Id with ...Plugin2
2509 // Revision 1.201 2004/09/14 10:06:42 rurban
2510 // generate iterated plugin ids, set plugin span id also
2512 // Revision 1.200 2004/08/05 17:34:26 rurban
2513 // move require to sortby branch
2515 // Revision 1.199 2004/08/05 10:38:15 rurban
2516 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
2519 // Revision 1.198 2004/07/02 10:30:36 rurban
2520 // always disable getimagesize for < php-4.3 with external png's
2522 // Revision 1.197 2004/07/02 09:55:58 rurban
2523 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2525 // Revision 1.196 2004/07/01 08:51:22 rurban
2526 // dumphtml: added exclude, print pagename before processing
2528 // Revision 1.195 2004/06/29 08:52:22 rurban
2529 // Use ...version() $need_content argument in WikiDB also:
2530 // To reduce the memory footprint for larger sets of pagelists,
2531 // we don't cache the content (only true or false) and
2532 // we purge the pagedata (_cached_html) also.
2533 // _cached_html is only cached for the current pagename.
2534 // => Vastly improved page existance check, ACL check, ...
2536 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2538 // Revision 1.194 2004/06/29 06:48:04 rurban
2539 // Improve LDAP auth and GROUP_LDAP membership:
2540 // no error message on false password,
2541 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2542 // fixed two group queries (this -> user)
2543 // stdlib: ConvertOldMarkup still flawed
2545 // Revision 1.193 2004/06/28 13:27:03 rurban
2546 // CreateToc disabled for old markup and Apache2 only
2548 // Revision 1.192 2004/06/28 12:47:43 rurban
2549 // skip if non-DEBUG and old markup with CreateToc
2551 // Revision 1.191 2004/06/25 14:31:56 rurban
2552 // avoid debug_skip warning
2554 // Revision 1.190 2004/06/25 14:29:20 rurban
2555 // WikiGroup refactoring:
2556 // global group attached to user, code for not_current user.
2557 // improved helpers for special groups (avoid double invocations)
2558 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2559 // fixed a XHTML validation error on userprefs.tmpl
2561 // Revision 1.189 2004/06/20 09:45:35 rurban
2562 // php5 isa fix (wrong strtolower)
2564 // Revision 1.188 2004/06/16 10:38:58 rurban
2565 // Disallow refernces in calls if the declaration is a reference
2566 // ("allow_call_time_pass_reference clean").
2567 // PhpWiki is now allow_call_time_pass_reference = Off clean,
2568 // but several external libraries may not.
2569 // In detail these libs look to be affected (not tested):
2573 // Revision 1.187 2004/06/14 11:31:37 rurban
2574 // renamed global $Theme to $WikiTheme (gforge nameclash)
2575 // inherit PageList default options from PageList
2576 // default sortby=pagename
2577 // use options in PageList_Selectable (limit, sortby, ...)
2578 // added action revert, with button at action=diff
2579 // added option regex to WikiAdminSearchReplace
2581 // Revision 1.186 2004/06/13 13:54:25 rurban
2582 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2583 // FoafViewer: Check against external requirements, instead of fatal.
2584 // Change output for xhtmldumps: using file:// urls to the local fs.
2585 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2586 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2588 // Revision 1.185 2004/06/11 09:07:30 rurban
2589 // support theme-specific LinkIconAttr: front or after or none
2591 // Revision 1.184 2004/06/04 20:32:53 rurban
2592 // Several locale related improvements suggested by Pierrick Meignen
2593 // LDAP fix by John Cole
2594 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2596 // Revision 1.183 2004/06/01 10:22:56 rurban
2597 // added url_get_contents() used in XmlParser and elsewhere
2599 // Revision 1.182 2004/05/25 12:40:48 rurban
2600 // trim the pagename
2602 // Revision 1.181 2004/05/25 10:18:44 rurban
2603 // Check for UTF-8 URLs; Internet Explorer produces these if you
2604 // type non-ASCII chars in the URL bar or follow unescaped links.
2605 // Fixes sf.net bug #953949
2606 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2608 // Revision 1.180 2004/05/18 16:23:39 rurban
2609 // rename split_pagename to SplitPagename
2611 // Revision 1.179 2004/05/18 16:18:37 rurban
2612 // AutoSplit at subpage seperators
2613 // RssFeed stability fix for empty feeds or broken connections
2615 // Revision 1.178 2004/05/12 10:49:55 rurban
2616 // require_once fix for those libs which are loaded before FileFinder and
2617 // its automatic include_path fix, and where require_once doesn't grok
2618 // dirname(__FILE__) != './lib'
2619 // upgrade fix with PearDB
2620 // navbar.tmpl: remove spaces for IE button alignment
2622 // Revision 1.177 2004/05/08 14:06:12 rurban
2623 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2624 // minor stability and portability fixes
2626 // Revision 1.176 2004/05/08 11:25:15 rurban
2629 // Revision 1.175 2004/05/06 17:30:38 rurban
2630 // CategoryGroup: oops, dos2unix eol
2631 // improved phpwiki_version:
2632 // pre -= .0001 (1.3.10pre: 1030.099)
2633 // -p1 += .001 (1.3.9-p1: 1030.091)
2634 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2635 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2636 // backend->backendType(), backend->database(),
2637 // backend->listOfFields(),
2638 // backend->listOfTables(),
2640 // Revision 1.174 2004/05/06 12:02:05 rurban
2641 // fix sf.net bug#949002: [ Link | ] assertion
2643 // Revision 1.173 2004/05/03 15:00:31 rurban
2644 // added more database upgrading: session.sess_ip, page.id autp_increment
2646 // Revision 1.172 2004/04/26 20:44:34 rurban
2647 // locking table specific for better databases
2649 // Revision 1.171 2004/04/19 23:13:03 zorloc
2650 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
2652 // Revision 1.170 2004/04/19 18:27:45 rurban
2653 // Prevent from some PHP5 warnings (ref args, no :: object init)
2654 // php5 runs now through, just one wrong XmlElement object init missing
2655 // Removed unneccesary UpgradeUser lines
2656 // Changed WikiLink to omit version if current (RecentChanges)
2658 // Revision 1.169 2004/04/15 21:29:48 rurban
2659 // allow [0] with new markup: link to page "0"
2661 // Revision 1.168 2004/04/10 02:30:49 rurban
2662 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2663 // Fixed "cannot setlocale..." (sf.net problem)
2665 // Revision 1.167 2004/04/02 15:06:55 rurban
2666 // fixed a nasty ADODB_mysql session update bug
2667 // improved UserPreferences layout (tabled hints)
2668 // fixed UserPreferences auth handling
2669 // improved auth stability
2670 // improved old cookie handling: fixed deletion of old cookies with paths
2672 // Revision 1.166 2004/04/01 15:57:10 rurban
2673 // simplified Sidebar theme: table, not absolute css positioning
2674 // added the new box methods.
2675 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2677 // Revision 1.165 2004/03/24 19:39:03 rurban
2678 // php5 workaround code (plus some interim debugging code in XmlElement)
2679 // php5 doesn't work yet with the current XmlElement class constructors,
2680 // WikiUserNew does work better than php4.
2681 // rewrote WikiUserNew user upgrading to ease php5 update
2682 // fixed pref handling in WikiUserNew
2683 // added Email Notification
2684 // added simple Email verification
2685 // removed emailVerify userpref subclass: just a email property
2686 // changed pref binary storage layout: numarray => hash of non default values
2687 // print optimize message only if really done.
2688 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2689 // prefs should be stored in db or homepage, besides the current session.
2691 // Revision 1.164 2004/03/18 21:41:09 rurban
2692 // fixed sqlite support
2693 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2695 // Revision 1.163 2004/03/17 18:41:49 rurban
2696 // just reformatting
2698 // Revision 1.162 2004/03/16 15:43:08 rurban
2699 // make fileSet sortable to please PageList
2701 // Revision 1.161 2004/03/12 15:48:07 rurban
2702 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2703 // simplified lib/stdlib.php:explodePageList
2705 // Revision 1.160 2004/02/28 21:14:08 rurban
2706 // generally more PHPDOC docs
2707 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2708 // fxied WikiUserNew pref handling: empty theme not stored, save only
2709 // changed prefs, sql prefs improved, fixed password update,
2710 // removed REPLACE sql (dangerous)
2711 // moved gettext init after the locale was guessed
2712 // + some minor changes
2715 // (c-file-style: "gnu")
2719 // c-basic-offset: 4
2720 // c-hanging-comment-ender-p: nil
2721 // indent-tabs-mode: nil