1 <?php //rcs_id('$Id: stdlib.php,v 1.275 2008-05-21 04:30:59 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)
31 ImgObject ($img, $url)
33 SplitQueryArgs ($query_args)
34 LinkPhpwikiURL ($url, $text, $basepage)
35 ConvertOldMarkup ($content, $markup_type = "block")
36 MangleXmlIdentifier($str)
37 UnMangleXmlIdentifier($str)
39 class Stack { push($item), pop(), cnt(), top() }
40 class Alert { show() }
41 class WikiPageName {getParent(),isValid(),getWarnings() }
43 expand_tabs($str, $tab_width = 8)
45 NoSuchRevision ($request, $page, $version)
46 TimezoneOffset ($time, $no_colon)
47 Iso8601DateTime ($time)
48 Rfc2822DateTime ($time)
49 ParseRfc1123DateTime ($timestr)
51 ByteFormatter ($bytes = 0, $longformat = false)
54 __vsprintf ($fmt, $args)
56 file_mtime ($filename)
57 sort_file_mtime ($a, $b)
58 class fileSet {fileSet($directory, $filepattern = false),
59 getFiles($exclude='', $sortby='', $limit='') }
60 class ListRegexExpand { listMatchCallback($item, $key),
61 expandRegex ($index, &$pages) }
64 glob_match ($glob, $against, $case_sensitive = true)
65 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
66 explodePageList ($input, $perm = false)
68 can ($object, $method)
69 function_usable ($function_name)
71 better_srand ($seed = '')
74 subPageSlice ($pagename, $pos)
78 obj2hash ($obj, $exclude = false, $fields = false)
81 url_get_contents ($uri)
83 firstNWordsOfContent ($n, $content)
84 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
87 charset_convert($from, $to, $data)
89 function: LinkInterWikiLink($link, $linktext)
90 moved to: lib/interwiki.php
91 function: linkExistingWikiWord($wikiword, $linktext, $version)
92 moved to: lib/Theme.php
93 function: LinkUnknownWikiWord($wikiword, $linktext)
94 moved to: lib/Theme.php
95 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
96 gone see: lib/plugin/RecentChanges.php
98 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
99 else define('_PHPWIKI_STDLIB_LOADED', true);
101 define('MAX_PAGENAME_LENGTH', 100);
104 * Convert string to a valid XML identifier.
106 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
108 * We would like to have, e.g. named anchors within wiki pages
109 * names like "Table of Contents" --- clearly not a valid XML
110 * fragment identifier.
112 * This function implements a one-to-one map from {any string}
113 * to {valid XML identifiers}.
116 * converting all bytes not in [A-Za-z0-9:_-],
117 * and any leading byte not in [A-Za-z] to 'xbb.',
118 * where 'bb' is the hexadecimal representation of the
121 * As a special case, the empty string is converted to 'empty.'
126 function MangleXmlIdentifier($str) {
130 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
131 "'x' . sprintf('%02x', ord('\\0')) . '.'",
135 function UnMangleXmlIdentifier($str) {
136 if ($str == 'empty.')
138 return preg_replace('/x(\w\w)\./e',
139 "sprintf('%c', hex('\\0'))",
144 * Returns a name for the WIKI_ID cookie that should be unique on the host.
145 * But for it to be unique you must have set a unique WIKI_NAME in your
146 * configuration file.
147 * @return string The name of the WIKI_ID cookie to use for this wiki.
149 function GetCookieName() {
150 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
154 * Generates a valid URL for a given Wiki pagename.
155 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
156 * If a WikiDB_Page object function will extract the name to link to.
157 * If a WikiDB_PageRevision object function will extract the name to link to.
159 * @param boolean $get_abs_url Default value is false.
160 * @return string The absolute URL to the page passed as $pagename.
162 function WikiURL($pagename, $args = '', $get_abs_url = false) {
163 global $request, $WikiTheme;
166 if (is_object($pagename)) {
167 if (isa($pagename, 'WikiDB_Page')) {
168 $pagename = $pagename->getName();
170 elseif (isa($pagename, 'WikiDB_PageRevision')) {
171 $page = $pagename->getPage();
172 $args['version'] = $pagename->getVersion();
173 $pagename = $page->getName();
175 elseif (isa($pagename, 'WikiPageName')) {
176 $anchor = $pagename->anchor;
177 $pagename = $pagename->name;
179 $anchor = $pagename->anchor;
180 $pagename = $pagename->name;
183 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
185 $args = 'start_debug=' . $request->getArg('start_debug');
186 elseif (is_array($args))
187 $args['start_debug'] = $request->getArg('start_debug');
189 $args .= '&start_debug=' . $request->getArg('start_debug');
191 if (is_array($args)) {
193 foreach ($args as $key => $val) {
194 // avoid default args
195 if (USE_PATH_INFO and $key == 'pagename')
197 elseif ($key == 'action' and $val == 'browse')
199 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
200 $enc_args[] = urlencode($key) . '=' . urlencode($val);
202 $args = join('&', $enc_args);
205 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
206 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
207 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
209 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
210 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
211 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
214 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
216 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
226 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
227 $url .= "?pagename=" . rawurlencode($pagename);
232 $url .= "#" . MangleXmlIdentifier($anchor);
236 /** Convert relative URL to absolute URL.
238 * This converts a relative URL to one of PhpWiki's support files
239 * to an absolute one.
242 * @return string Absolute URL
244 function AbsoluteURL ($url) {
245 if (preg_match('/^https?:/', $url))
247 if ($url[0] != '/') {
248 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
249 while ($base != '/' and substr($url, 0, 3) == "../") {
250 $url = substr($url, 3);
251 $base = dirname($base);
257 return SERVER_URL . $url;
260 function DataURL ($url) {
261 if (preg_match('/^https?:/', $url))
263 $url = NormalizeWebFileName($url);
264 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
265 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
266 return AbsoluteURL($url);
270 * Generates icon in front of links.
272 * @param string $protocol_or_url URL or protocol to determine which icon to use.
274 * @return HtmlElement HtmlElement object that contains data to create img link to
275 * icon for use with url or protocol passed to the function. False if no img to be
278 function IconForLink($protocol_or_url) {
280 if (0 and $filename_suffix == false) {
281 // display apache style icon for file type instead of protocol icon
282 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
283 // - document: html, htm, text, txt, rtf, pdf, doc
284 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
285 // - audio: mp3,mp2,aiff,aif,au
286 // - multimedia: mpeg,mpg,mov,qt
288 list ($proto) = explode(':', $protocol_or_url, 2);
289 $src = $WikiTheme->getLinkIconURL($proto);
291 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
298 * Glue icon in front of or after text.
299 * Pref: 'noLinkIcons' - ignore icon if set
300 * Theme: 'LinkIcons' - 'yes' at front
301 * - 'no' display no icon
302 * - 'front' display at left
303 * - 'after' display at right
305 * @param string $protocol_or_url Protocol or URL. Used to determine the
307 * @param string $text The text.
308 * @return XmlContent.
310 function PossiblyGlueIconToText($proto_or_url, $text) {
311 global $request, $WikiTheme;
312 if ($request->getPref('noLinkIcons'))
314 $icon = IconForLink($proto_or_url);
317 if ($where = $WikiTheme->getLinkIconAttr()) {
318 if ($where == 'no') return $text;
319 if ($where != 'after') $where = 'front';
323 if ($where == 'after') {
324 // span the icon only to the last word (tie them together),
325 // to let the previous words wrap on line breaks.
326 if (!is_object($text)) {
327 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
328 list (, $prefix, $last_word) = $m;
334 $text = HTML::span(array('style' => 'white-space: nowrap'),
335 $last_word, HTML::Raw(' '), $icon);
337 $text = HTML($prefix, $text);
340 // span the icon only to the first word (tie them together),
341 // to let the next words wrap on line breaks
342 if (!is_object($text)) {
343 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
344 list (, $first_word, $tail) = $m;
350 $text = HTML::span(array('style' => 'white-space: nowrap'),
353 $text = HTML($text, $tail);
358 * Determines if the url passed to function is safe, by detecting if the characters
359 * '<', '>', or '"' are present.
360 * Check against their urlencoded values also.
362 * @param string $url URL to check for unsafe characters.
363 * @return boolean True if same, false else.
365 function IsSafeURL($url) {
366 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
370 * Generates an HtmlElement object to store data for a link.
372 * @param string $url URL that the link will point to.
373 * @param string $linktext Text to be displayed as link.
374 * @return HtmlElement HtmlElement object that contains data to construct an html link.
376 function LinkURL($url, $linktext = '') {
377 // FIXME: Is this needed (or sufficient?)
378 if(! IsSafeURL($url)) {
379 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
380 _("BAD URL -- remove all of <, >, \"")));
384 $linktext = preg_replace("/mailto:/A", "", $url);
385 $args = array('href' => $url);
386 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
387 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
388 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
390 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
397 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
398 * Disallows sizes which are too small.
399 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
401 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
403 function LinkImage($url, $alt = false) {
404 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
405 // Disallow tags in img src urls. Typical CSS attacks.
406 // FIXME: Is this needed (or sufficient?)
407 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
409 if(! IsSafeURL($url)) {
410 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
411 _("BAD URL -- remove all of <, >, \"")));
414 // support new syntax: [prefix/image.jpg size=50% border=n]
415 //if (!preg_match("/\.(".$force_img.")/i", $url))
416 if (empty($alt)) $alt = basename($url);
417 $arr = split(' ',$url);
418 $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
419 if (count($arr) > 1) {
422 foreach ($arr as $attr) {
423 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
424 $link->setAttr('width',$m[1]);
425 $link->setAttr('height',$m[1]);
427 elseif (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
428 $link->setAttr('width',$m[1]);
429 $link->setAttr('height',$m[2]);
431 elseif (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
432 $link->setAttr('width',$m[1]);
433 elseif (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
434 $link->setAttr('height',$m[1]);
435 elseif (preg_match('/^border=(\d+)$/',$attr,$m))
436 $link->setAttr('border',$m[1]);
437 elseif (preg_match('/^align=(\w+)$/',$attr,$m))
438 $link->setAttr('align',$m[1]);
439 elseif (preg_match('/^hspace=(\d+)$/',$attr,$m))
440 $link->setAttr('hspace',$m[1]);
441 elseif (preg_match('/^vspace=(\d+)$/',$attr,$m))
442 $link->setAttr('vspace',$m[1]);
445 if(! IsSafeURL($url)) {
446 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
447 _("BAD URL -- remove all of <, >, \"")));
450 $link->setAttr('src', $url);
455 // Check width and height as spam countermeasure
456 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
457 //$width = (int) $width; // px or % or other suffix
458 //$height = (int) $height;
459 if (($width < 3 and $height < 10) or
460 ($height < 3 and $width < 20) or
461 ($height < 7 and $width < 7))
463 trigger_error(_("Invalid image size"), E_USER_WARNING);
468 // Prepare for getimagesize($url)
469 // $url only valid for external urls, otherwise local path
470 // Older php versions crash here with certain png's:
471 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
472 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
473 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
474 if (DISABLE_GETIMAGESIZE)
476 elseif (! preg_match("/\.$force_img$/i", $url))
477 ; // only valid image extensions or scripts assumed to generate images
478 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
479 ; // it's safe to assume that this will fail.
480 elseif (preg_match("/^http/",$url)) { // external url
481 $size = @getimagesize($url);
482 } else { // local file
483 if (file_exists($file = NormalizeLocalFileName($url))) { // here
484 $size = @getimagesize($file);
485 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
486 $size = @getimagesize($file);
487 $link->setAttr('src', rawurldecode($url));
488 } elseif (string_starts_with($url, getUploadDataPath())) { // there
489 $file = substr($file, strlen(getUploadDataPath()));
490 $size = @getimagesize(getUploadFilePath().rawurldecode($file));
491 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
492 } else { // elsewhere
493 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
499 if (($width < 3 and $height < 10)
500 or ($height < 3 and $width < 20)
501 or ($height < 7 and $width < 7))
503 trigger_error(_("Invalid image size"), E_USER_WARNING);
509 $link->setAttr('class', 'inlineimage');
511 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
512 * png|jpg|gif|jpeg|bmp|pl|cgi
513 * Note: Allow cgi's (pl,cgi) returning images.
515 if (!preg_match("/\.(".$force_img.")/i", $url)) {
516 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
517 // => HTML::object(array('src' => $url)) ...;
518 return ImgObject($link, $ori_url);
524 * <object> / <embed> tags instead of <img> for all non-image extensions
526 * Called by LinkImage(), not directly.
527 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
528 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
529 * $alt may be an alternate img
530 * TODO: Need to unify with WikiPluginCached::embedObject()
532 * Note that Safari 1.0 will crash with <object>, so use only <embed>
533 * http://www.alleged.org.uk/pdc/2002/svg-object.html
535 * Allowed object tags:
536 * DATA=URI (object data)
537 * CLASSID=URI (location of implementation)
538 * ARCHIVE=CDATA (archive files)
539 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
540 * WIDTH=Length (object width)
541 * HEIGHT=Length (object height)
542 * NAME=CDATA (name for form submission)
543 * USEMAP=URI (client-side image map)
544 * TYPE=ContentType (content-type of object)
545 * CODETYPE=ContentType (content-type of code)
546 * STANDBY=Text (message to show while loading)
547 * TABINDEX=NUMBER (position in tabbing order)
548 * DECLARE (do not instantiate object)
549 * The rest is added as <param name="" value="" /> tags
551 function ImgObject($img, $url) {
552 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
553 $args = split(' ', $url);
555 if (count($args) >= 1) {
556 $url = array_shift($args);
558 foreach ($args as $attr) {
559 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
560 "codetype,standby,tabindex,declare") as $param)
562 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
563 $img->setAttr($param, $m[1]);
569 // now all remaing args are added as <param> to the object
570 foreach ($args as $attr) {
571 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
572 $params[] = HTML::param(array('name' => $m[1],
577 $type = $img->getAttr('type');
579 // TODO: map extension to mime-types if type is not given and php < 4.3
580 if (function_exists('mime_content_type'))
581 $type = mime_content_type($url);
583 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
585 $object->setAttr('class', 'inlineobject');
587 foreach ($params as $param) $object->pushContent($param);
589 if (isBrowserSafari()) {
590 return HTML::embed($object->_attr, $object->_content);
592 $object->pushContent(HTML::embed($object->_attr));
599 // var in php5 deprecated
601 $this->items = array();
604 function push($item) {
605 $this->items[$this->size] = $item;
611 if ($this->size == 0) {
612 return false; // stack is empty
615 return $this->items[$this->size];
624 return $this->items[$this->size - 1];
630 // end class definition
632 function SplitQueryArgs ($query_args = '')
634 // FIXME: use the arg-seperator which might not be &
635 $split_args = split('&', $query_args);
637 while (list($key, $val) = each($split_args))
638 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
639 $args[$m[1]] = $m[2];
643 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
646 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
647 return HTML::strong(array('class' => 'rawurl'),
648 HTML::u(array('class' => 'baduri'),
649 _("BAD phpwiki: URL")));
653 $pagename = urldecode($m[1]);
656 if (empty($pagename) &&
657 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
658 // Convert old style links (to not break diff links in
660 $pagename = urldecode($m[2]);
661 $args = array("action" => $m[1]);
664 $args = SplitQueryArgs($qargs);
667 if (empty($pagename))
668 $pagename = $GLOBALS['request']->getArg('pagename');
670 if (isset($args['action']) && $args['action'] == 'browse')
671 unset($args['action']);
674 if (empty($args['action']))
676 else if (is_safe_action($args['action']))
677 $class = 'wikiaction';
679 if (empty($args['action']) || is_safe_action($args['action']))
680 $class = 'wikiaction';
682 // Don't allow administrative links on unlocked pages.
683 $dbi = $GLOBALS['request']->getDbh();
684 $page = $dbi->getPage($basepage ? $basepage : $pagename);
685 if (!$page->get('locked'))
686 return HTML::span(array('class' => 'wikiunsafe'),
687 HTML::u(_("Lock page to enable link")));
688 $class = 'wikiadmin';
692 $text = HTML::span(array('class' => 'rawurl'), $url);
694 $wikipage = new WikiPageName($pagename);
695 if (!$wikipage->isValid()) {
697 return $WikiTheme->linkBadWikiWord($wikipage, $url);
700 return HTML::a(array('href' => WikiURL($pagename, $args),
706 * A class to assist in parsing wiki pagenames.
708 * Now with subpages and anchors, parsing and passing around
709 * pagenames is more complicated. This should help.
713 /** Short name for page.
715 * This is the value of $name passed to the constructor.
716 * (For use, e.g. as a default label for links to the page.)
720 /** The full page name.
722 * This is the full name of the page (without anchor).
728 * This is the referenced anchor within the page, or the empty string.
734 * @param mixed $name Page name.
735 * WikiDB_Page, WikiDB_PageRevision, or string.
736 * This can be a relative subpage name (like '/SubPage'),
737 * or can be the empty string to refer to the $basename.
739 * @param string $anchor For links to anchors in page.
741 * @param mixed $basename Page name from which to interpret
742 * relative or other non-fully-specified page names.
744 function WikiPageName($name, $basename=false, $anchor=false) {
745 if (is_string($name)) {
746 $this->shortName = $name;
747 if (strstr($name, ':')) {
748 list($moniker, $shortName) = split (":", $name, 2);
749 $map = getInterwikiMap(); // allow overrides to custom maps
750 if (isset($map->_map[$moniker])) {
751 $url = $map->_map[$moniker];
752 if (strstr($url, '%s'))
753 $url = sprintf($url, $shortName);
757 // expand Talk or User, but not to absolute urls!
758 if (strstr($url, '//')) {
759 if ($moniker == 'Talk')
760 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
761 elseif ($moniker == 'User')
766 if (strstr($shortName, '?')) {
767 list($shortName, $dummy) = split("\?", $shortName, 2);
769 $this->shortName = $shortName;
772 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
773 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
775 $name = $this->_pagename($basename) . $name;
777 $name = $this->_normalize_bad_pagename($name);
778 $this->shortName = $name;
783 $name = $this->_pagename($name);
784 $this->shortName = $name;
787 $this->name = $this->_check($name);
788 $this->anchor = (string)$anchor;
795 function getParent() {
797 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
799 return substr($name, 0, -strlen($tail));
802 function isValid($strict = false) {
804 return !isset($this->_errors);
805 return (is_string($this->name) and $this->name != '');
808 function getWarnings() {
810 if (isset($this->_warnings))
811 $warnings = array_merge($warnings, $this->_warnings);
812 if (isset($this->_errors))
813 $warnings = array_merge($warnings, $this->_errors);
817 return sprintf(_("'%s': Bad page name: %s"),
818 $this->shortName, join(', ', $warnings));
821 function _pagename($page) {
822 if (isa($page, 'WikiDB_Page'))
823 return $page->getName();
824 elseif (isa($page, 'WikiDB_PageRevision'))
825 return $page->getPageName();
826 elseif (isa($page, 'WikiPageName'))
828 // '0' or e.g. '1984' should be allowed though
829 if (!is_string($page) and !is_integer($page)) {
830 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
831 $page, gettype($page), get_class($page)),
834 //assert(is_string($page));
838 function _normalize_bad_pagename($name) {
839 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
841 // Punt... You really shouldn't get here.
844 return $request->getArg('pagename');
846 assert($name[0] == SUBPAGE_SEPARATOR);
847 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
848 return substr($name, 1);
852 * Compress internal white-space to single space character.
854 * This leads to problems with loading a foreign charset pagename,
855 * which cannot be deleted anymore, because unknown chars are compressed.
856 * So BEFORE importing a file _check must be done !!!
858 function _check($pagename) {
859 // Compress internal white-space to single space character.
860 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
861 if ($pagename != $orig)
862 $this->_warnings[] = _("White space converted to single space");
864 // Delete any control characters.
865 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
866 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
867 if ($pagename != $orig)
868 $this->_errors[] = _("Control characters not allowed");
871 // Strip leading and trailing white-space.
872 $pagename = trim($pagename);
875 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
876 $pagename = substr($pagename, 1);
877 if ($pagename != $orig)
878 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
880 // ";" is urlencoded, so safe from php arg-delim problems
881 /*if (strstr($pagename, ';')) {
882 $this->_warnings[] = _("';' is deprecated");
883 $pagename = str_replace(';', '', $pagename);
886 // not only for SQL, also to restrict url length
887 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
888 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
889 $this->_errors[] = _("too long");
892 // disallow some chars only on file and cvs
893 if ((DATABASE_TYPE == 'cvs'
894 or DATABASE_TYPE == 'file'
895 or DATABASE_TYPE == 'flatfile')
896 and preg_match('/(:|\.\.)/', $pagename, $m))
898 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
899 $pagename = str_replace('..', '', $pagename);
900 $pagename = str_replace(':', '', $pagename);
908 * Convert old page markup to new-style markup.
910 * @param string $text Old-style wiki markup.
912 * @param string $markup_type
914 * <dt><code>"block"</code> <dd>Convert all markup.
915 * <dt><code>"inline"</code> <dd>Convert only inline markup.
916 * <dt><code>"links"</code> <dd>Convert only link markup.
919 * @return string New-style wiki markup.
921 * @bugs Footnotes don't work quite as before (esp if there are
922 * multiple references to the same footnote. But close enough,
923 * probably for now....
924 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
925 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
926 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
927 * also known to crash, even with Apache1.
929 function ConvertOldMarkup ($text, $markup_type = "block") {
935 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
936 // AnciennesR%E8glesDeFormatage crashes.
937 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
938 // also known to crash, even with Apache1.
940 // I suspect this only to crash with Apache2 and IIS.
941 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
942 and preg_match("/plugin CreateToc/", $text))
944 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
945 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
946 ._("Skipped."), E_USER_WARNING);
948 //if (!DEBUG) return $text;
953 /*****************************************************************
954 * Conversions for inline markup:
961 // escape escaped brackets
965 // change ! escapes to ~'s.
966 global $WikiNameRegexp, $request;
967 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
968 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
969 if (check_php_version(4,3,9)) {
970 $map = getInterwikiMap();
971 if ($map_regex = $map->getRegexp())
972 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
974 $bang_esc[] = $WikiNameRegexp;
975 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
978 $subs["links"] = array($orig, $repl);
980 // Temporarily URL-encode pairs of underscores in links to hide
981 // them from the re for bold markup.
982 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
983 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
986 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
989 // Convert footnote references.
990 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
991 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
993 // Convert old style emphases to HTML style emphasis.
994 $orig[] = '/__(.*?)__/';
995 $repl[] = '<strong>\\1</strong>';
996 $orig[] = "/''(.*?)''/";
997 $repl[] = '<em>\\1</em>';
999 // Escape nestled markup.
1000 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1003 // in old markup headings only allowed at beginning of line
1007 // Convert URL-encoded pairs of underscores in links back to
1008 // real underscores after bold markup has been converted.
1009 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1010 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1012 $subs["inline"] = array($orig, $repl);
1014 /*****************************************************************
1015 * Patterns which match block markup constructs which take
1016 * special handling...
1020 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1022 $blockpats[] = '\|(?:.*\n\|)*';
1025 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1027 // Footnote definitions
1028 $blockpats[] = '\[\s*(\d+)\s*\]';
1032 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1036 $blockpats[] = '!{1,3}[^!]';
1038 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1039 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1041 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1042 . join("|", $blockpats)
1047 if ($markup_type != "block") {
1048 list ($orig, $repl) = $subs[$markup_type];
1049 return preg_replace($orig, $repl, $text);
1052 list ($orig, $repl) = $subs['inline'];
1055 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1056 // AnciennesR%E8glesDeFormatage and more
1057 // See http://www.pcre.org/pcre.txt LIMITATIONS
1058 while (preg_match($block_re, $text, $m)) {
1059 $text = substr($text, strlen($m[0]));
1060 list (,$leading_text, $block) = $m;
1063 if (strchr(" \t", $block[0])) {
1065 $prefix = "<pre>\n";
1066 $suffix = "\n</pre>\n";
1068 elseif ($block[0] == '|') {
1070 $prefix = "<?plugin OldStyleTable\n";
1073 elseif (strchr("#*;", $block[0])) {
1074 // Old-style list item
1075 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1076 list (,$ind,$bullet) = $m;
1077 $block = substr($block, strlen($m[0]));
1079 $indent = str_repeat(' ', strlen($ind));
1080 if ($bullet[0] == ';') {
1081 //$term = ltrim(substr($bullet, 1));
1082 //return $indent . $term . "\n" . $indent . ' ';
1083 $prefix = $ind . $bullet;
1086 $prefix = $indent . $bullet . ' ';
1088 elseif ($block[0] == '[') {
1089 // Footnote definition
1090 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1092 $block = substr($block, strlen($m[0]));
1093 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1095 elseif ($block[0] == '<') {
1097 // HACK: no inline markup...
1101 elseif ($block[0] == '!') {
1103 preg_match('/^!{1,3}/', $block, $m);
1105 $block = substr($block, strlen($m[0]));
1111 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1112 if ($block) $block = preg_replace($orig, $repl, $block);
1113 $out .= $leading_text;
1118 return $out . preg_replace($orig, $repl, $text);
1124 * Expand tabs in string.
1126 * Converts all tabs to (the appropriate number of) spaces.
1128 * @param string $str
1129 * @param integer $tab_width
1132 function expand_tabs($str, $tab_width = 8) {
1133 $split = split("\t", $str);
1134 $tail = array_pop($split);
1136 foreach ($split as $hunk) {
1138 $pos = strlen(strrchr($expanded, "\n")) - 1;
1139 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1141 return substr($expanded, 1) . $tail;
1145 * Split WikiWords in page names.
1147 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1148 * places like page titles. This is rumored to help search engines
1151 * @param $page string The page name.
1153 * @return string The split name.
1155 function SplitPagename ($page) {
1157 if (preg_match("/\s/", $page))
1158 return $page; // Already split --- don't split any more.
1160 // This algorithm is specialized for several languages.
1161 // (Thanks to Pierrick MEIGNEN)
1162 // Improvements for other languages welcome.
1165 // This mess splits between a lower-case letter followed by
1166 // either an upper-case or a numeral; except that it wont
1167 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1168 switch ($GLOBALS['LANG']) {
1173 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1176 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1179 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1180 // This the single-letter words 'I' and 'A' from any following
1181 // capitalized words.
1182 switch ($GLOBALS['LANG']) {
1184 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1187 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1190 // Split numerals from following letters.
1191 $RE[] = '/(\d)([[:alpha:]])/';
1192 // Split at subpage seperators. TBD in Theme.php
1193 $RE[] = "/([^${sep}]+)(${sep})/";
1194 $RE[] = "/(${sep})([^${sep}]+)/";
1196 foreach ($RE as $key)
1197 $RE[$key] = pcre_fix_posix_classes($key);
1200 foreach ($RE as $regexp) {
1201 $page = preg_replace($regexp, '\\1 \\2', $page);
1206 function NoSuchRevision (&$request, $page, $version) {
1207 $html = HTML(HTML::h2(_("Revision Not Found")),
1208 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1209 $version, WikiLink($page, 'auto'))));
1210 include_once('lib/Template.php');
1211 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1217 * Get time offset for local time zone.
1219 * @param $time time_t Get offset for this time. Default: now.
1220 * @param $no_colon boolean Don't put colon between hours and minutes.
1221 * @return string Offset as a string in the format +HH:MM.
1223 function TimezoneOffset ($time = false, $no_colon = false) {
1224 if ($time === false)
1226 $secs = date('Z', $time);
1235 $colon = $no_colon ? '' : ':';
1236 $mins = intval(($secs + 30) / 60);
1237 return sprintf("%s%02d%s%02d",
1238 $sign, $mins / 60, $colon, $mins % 60);
1243 * Format time in ISO-8601 format.
1245 * @param $time time_t Time. Default: now.
1246 * @return string Date and time in ISO-8601 format.
1248 function Iso8601DateTime ($time = false) {
1249 if ($time === false)
1251 $tzoff = TimezoneOffset($time);
1252 $date = date('Y-m-d', $time);
1253 $time = date('H:i:s', $time);
1254 return $date . 'T' . $time . $tzoff;
1258 * Format time in RFC-2822 format.
1260 * @param $time time_t Time. Default: now.
1261 * @return string Date and time in RFC-2822 format.
1263 function Rfc2822DateTime ($time = false) {
1264 if ($time === false)
1266 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1270 * Format time in RFC-1123 format.
1272 * @param $time time_t Time. Default: now.
1273 * @return string Date and time in RFC-1123 format.
1275 function Rfc1123DateTime ($time = false) {
1276 if ($time === false)
1278 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1281 /** Parse date in RFC-1123 format.
1283 * According to RFC 1123 we must accept dates in the following
1286 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1287 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1288 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1290 * (Though we're only allowed to generate dates in the first format.)
1292 function ParseRfc1123DateTime ($timestr) {
1293 $timestr = trim($timestr);
1294 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1295 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1297 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1299 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1300 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1302 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1303 if ($year < 70) $year += 2000;
1304 elseif ($year < 100) $year += 1900;
1306 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1307 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1309 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1316 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1318 return false; // failed
1323 * Format time to standard 'ctime' format.
1325 * @param $time time_t Time. Default: now.
1326 * @return string Date and time.
1328 function CTime ($time = false)
1330 if ($time === false)
1332 return date("D M j H:i:s Y", $time);
1337 * Format number as kilobytes or bytes.
1338 * Short format is used for PageList
1339 * Long format is used in PageInfo
1341 * @param $bytes int. Default: 0.
1342 * @param $longformat bool. Default: false.
1343 * @return class FormattedText (XmlElement.php).
1345 function ByteFormatter ($bytes = 0, $longformat = false) {
1348 if ($bytes < 1024) {
1350 $size = fmt("%s b", $bytes);
1352 $size = fmt("%s bytes", $bytes);
1355 $kb = round($bytes / 1024, 1);
1357 $size = fmt("%s k", $kb);
1359 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1365 * Internationalized printf.
1367 * This is essentially the same as PHP's built-in printf
1368 * with the following exceptions:
1370 * <li> It passes the format string through gettext().
1371 * <li> It supports the argument reordering extensions.
1378 * __printf("Differences between versions %s and %s of %s",
1379 * $new_link, $old_link, $page_link);
1382 * Then in locale/po/de.po, one can reorder the printf arguments:
1385 * msgid "Differences between %s and %s of %s."
1386 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1389 * (Note that while PHP tries to expand $vars within double-quotes,
1390 * the values in msgstr undergo no such expansion, so the '$'s
1393 * One shouldn't use reordered arguments in the default format string.
1394 * Backslashes in the default string would be necessary to escape the
1395 * '$'s, and they'll cause all kinds of trouble....
1397 function __printf ($fmt) {
1398 $args = func_get_args();
1400 echo __vsprintf($fmt, $args);
1404 * Internationalized sprintf.
1406 * This is essentially the same as PHP's built-in printf with the
1407 * following exceptions:
1410 * <li> It passes the format string through gettext().
1411 * <li> It supports the argument reordering extensions.
1416 function __sprintf ($fmt) {
1417 $args = func_get_args();
1419 return __vsprintf($fmt, $args);
1423 * Internationalized vsprintf.
1425 * This is essentially the same as PHP's built-in printf with the
1426 * following exceptions:
1429 * <li> It passes the format string through gettext().
1430 * <li> It supports the argument reordering extensions.
1435 function __vsprintf ($fmt, $args) {
1436 $fmt = gettext($fmt);
1437 // PHP's sprintf doesn't support variable with specifiers,
1438 // like sprintf("%*s", 10, "x"); --- so we won't either.
1440 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1441 // Format string has '%2$s' style argument reordering.
1442 // PHP doesn't support this.
1443 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1444 // literal variable name substitution only to keep locale
1445 // strings uncluttered
1446 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1447 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1449 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1452 // Reorder arguments appropriately.
1453 foreach($m[1] as $argnum) {
1454 if ($argnum < 1 || $argnum > count($args))
1455 trigger_error(sprintf(_("%s: argument index out of range"),
1456 $argnum), E_USER_WARNING);
1457 $newargs[] = $args[$argnum - 1];
1462 // Not all PHP's have vsprintf, so...
1463 array_unshift($args, $fmt);
1464 return call_user_func_array('sprintf', $args);
1467 function file_mtime ($filename) {
1468 if ($stat = @stat($filename))
1474 function sort_file_mtime ($a, $b) {
1475 $ma = file_mtime($a);
1476 $mb = file_mtime($b);
1477 if (!$ma or !$mb or $ma == $mb) return 0;
1478 return ($ma > $mb) ? -1 : 1;
1483 * Build an array in $this->_fileList of files from $dirname.
1484 * Subdirectories are not traversed.
1486 * (This was a function LoadDir in lib/loadsave.php)
1487 * See also http://www.php.net/manual/en/function.readdir.php
1489 function getFiles($exclude='', $sortby='', $limit='') {
1490 $list = $this->_fileList;
1493 require_once('lib/PageList.php');
1494 switch (Pagelist::sortby($sortby, 'db')) {
1495 case 'pagename ASC': break;
1496 case 'pagename DESC':
1497 $list = array_reverse($list);
1500 usort($list,'sort_file_mtime');
1503 usort($list,'sort_file_mtime');
1504 $list = array_reverse($list);
1509 return array_splice($list, 0, $limit);
1513 function _filenameSelector($filename) {
1514 if (! $this->_pattern )
1517 if (! $this->_pcre_pattern )
1518 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1519 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1524 function fileSet($directory, $filepattern = false) {
1525 $this->_fileList = array();
1526 $this->_pattern = $filepattern;
1528 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1530 $this->_case = !isWindows();
1531 $this->_pathsep = '/';
1533 if (empty($directory)) {
1534 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1536 return; // early return
1539 @ $dir_handle = opendir($dir=$directory);
1540 if (empty($dir_handle)) {
1541 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1542 $dir), E_USER_NOTICE);
1543 return; // early return
1546 while ($filename = readdir($dir_handle)) {
1547 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1549 if ($this->_filenameSelector($filename)) {
1550 array_push($this->_fileList, "$filename");
1551 //trigger_error(sprintf(_("found file %s"), $filename),
1552 // E_USER_NOTICE); //debugging
1555 closedir($dir_handle);
1561 // expands a list containing regex's to its matching entries
1562 class ListRegexExpand {
1563 //var $match, $list, $index, $case_sensitive;
1564 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1565 $this->match = $match;
1566 $this->list = &$list;
1567 $this->case_sensitive = $case_sensitive;
1568 //$this->index = false;
1570 function listMatchCallback ($item, $key) {
1571 $quoted = str_replace('/','\/',$item);
1572 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1574 unset($this->list[$this->index]);
1575 $this->list[] = $item;
1578 function expandRegex ($index, &$pages) {
1579 $this->index = $index;
1580 array_walk($pages, array($this, 'listMatchCallback'));
1585 // Convert fileglob to regex style:
1586 // Convert some wildcards to pcre style, escape the rest
1587 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1588 // Fixed bug #994994: "/" in $glob.
1589 function glob_to_pcre ($glob) {
1590 // check simple case: no need to escape
1591 $escape = '\[](){}=!<>|:/';
1592 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1594 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1595 $glob = strtr($glob, "\\", "\xff");
1596 $glob = str_replace("/", "\\/", $glob);
1597 // first convert some unescaped expressions to pcre style: . => \.
1599 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1600 "\\1\xff\\2", $glob);
1603 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1604 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1605 if (!preg_match('/^[\?\*]/', $glob))
1607 if (!preg_match('/[\?\*]$/', $glob))
1610 // Fixes Bug 1182997
1611 // .*? handled above, now escape the rest
1612 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1613 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1615 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1617 $re = preg_replace('/\xff/', '', $re);
1621 function glob_match ($glob, $against, $case_sensitive = true) {
1622 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1626 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1627 $list = explode(',',$input);
1628 // expand wildcards from list of $allnames
1629 if (preg_match('/[\?\*]/',$input)) {
1630 // Optimizing loop invariants:
1631 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1632 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1634 if (preg_match('/[\?\*]/',$f)) {
1636 $expand = new ListRegexExpand($list,
1637 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1638 $expand->expandRegex($i, $allnames);
1645 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1646 function explodePageList($input, $include_empty=false, $sortby='pagename',
1647 $limit='', $exclude='') {
1648 include_once("lib/PageList.php");
1649 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1652 // Class introspections
1655 * Determine whether object is of a specified type.
1656 * In PHP builtin since 4.2.0 as is_a()
1657 * is_a() deprecated in PHP 5, in favor of instanceof operator
1659 * @param $object object An object.
1660 * @param $class string Class name.
1661 * @return bool True iff $object is a $class
1662 * or a sub-type of $class.
1664 function isa ($object, $class) {
1665 //if (check_php_version(5))
1666 // return $object instanceof $class;
1667 if (check_php_version(4,2) and !check_php_version(5))
1668 return is_a($object, $class);
1670 $lclass = check_php_version(5) ? $class : strtolower($class);
1671 return is_object($object)
1672 && ( strtolower(get_class($object)) == strtolower($class)
1673 || is_subclass_of($object, $lclass) );
1676 /** Determine whether (possible) object has method.
1678 * @param $object mixed Object
1679 * @param $method string Method name
1680 * @return bool True iff $object is an object with has method $method.
1682 function can ($object, $method) {
1683 return is_object($object) && method_exists($object, strtolower($method));
1686 /** Determine whether a function is okay to use.
1688 * Some providers (e.g. Lycos) disable some of PHP functions for
1689 * "security reasons." This makes those functions, of course,
1690 * unusable, despite the fact the function_exists() says they
1693 * This function test to see if a function exists and is not
1694 * disallowed by PHP's disable_functions config setting.
1696 * @param string $function_name Function name
1697 * @return bool True iff function can be used.
1699 function function_usable($function_name) {
1701 if (!is_array($disabled)) {
1702 $disabled = array();
1703 // Use get_cfg_var since ini_get() is one of the disabled functions
1704 // (on Lycos, at least.)
1705 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1706 foreach ($split as $f)
1707 $disabled[strtolower($f)] = true;
1710 return ( function_exists($function_name)
1711 and ! isset($disabled[strtolower($function_name)])
1718 * This is used for generating ETags.
1720 function wikihash ($x) {
1721 if (is_scalar($x)) {
1724 elseif (is_array($x)) {
1726 return md5(serialize($x));
1728 elseif (is_object($x)) {
1731 trigger_error("Can't hash $x", E_USER_ERROR);
1736 * Seed the random number generator.
1738 * better_srand() ensures the randomizer is seeded only once.
1740 * How random do you want it? See:
1741 * http://www.php.net/manual/en/function.srand.php
1742 * http://www.php.net/manual/en/function.mt-srand.php
1744 function better_srand($seed = '') {
1745 static $wascalled = FALSE;
1747 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1748 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1750 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1754 function rand_ascii($length = 1) {
1757 for ($i = 1; $i <= $length; $i++) {
1758 // return only typeable 7 bit ascii, avoid quotes
1759 if (function_exists('mt_rand'))
1760 $s .= chr(mt_rand(40, 126));
1762 // the usually bad glibc srand()
1763 $s .= chr(rand(40, 126));
1768 /* by Dan Frankowski.
1770 function rand_ascii_readable ($length = 6) {
1771 // Pick a few random letters or numbers
1774 // Don't use 1lI0O, because they're hard to read
1775 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1776 $letter_len = strlen($letters);
1777 for ($i=0; $i < $length; $i++) {
1778 if (function_exists('mt_rand'))
1779 $word .= $letters[mt_rand(0, $letter_len-1)];
1781 $word .= $letters[rand(0, $letter_len-1)];
1787 * Recursively count all non-empty elements
1788 * in array of any dimension or mixed - i.e.
1789 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1790 * See http://www.php.net/manual/en/function.count.php
1792 function count_all($arg) {
1793 // skip if argument is empty
1795 //print_r($arg); //debugging
1797 // not an array, return 1 (base case)
1800 // else call recursively for all elements $arg
1801 foreach($arg as $key => $val)
1802 $count += count_all($val);
1807 function isSubPage($pagename) {
1808 return (strstr($pagename, SUBPAGE_SEPARATOR));
1811 function subPageSlice($pagename, $pos) {
1812 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1813 $pages = array_slice($pages,$pos,1);
1820 * Class for "popping up" and alert box. (Except that right now, it doesn't
1824 * This is a hackish and needs to be refactored. However it would be nice to
1825 * unify all the different methods we use for showing Alerts and Dialogs.
1826 * (E.g. "Page deleted", login form, ...)
1831 * @param object $request
1832 * @param mixed $head Header ("title") for alert box.
1833 * @param mixed $body The text in the alert box.
1834 * @param hash $buttons An array mapping button labels to URLs.
1835 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1837 function Alert($head, $body, $buttons=false) {
1838 if ($buttons === false)
1841 if (is_array($body)) {
1843 foreach ($body as $li) {
1844 $html->pushContent(HTML::li($li));
1848 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1849 $this->_buttons = $buttons;
1853 * Show the alert box.
1858 $tokens = $this->_tokens;
1859 $tokens['BUTTONS'] = $this->_getButtons();
1861 $request->discardOutput();
1862 $tmpl = new Template('dialog', $request, $tokens);
1868 function _getButtons() {
1871 $buttons = $this->_buttons;
1873 $buttons = array(_("Okay") => $request->getURLtoSelf());
1876 foreach ($buttons as $label => $url)
1877 print "$label $url\n";
1878 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1879 return new XmlContent($out);
1884 // 1.3.9-p1 => 1030.091
1885 // 1.3.10pre => 1030.099
1886 // 1.3.11pre-20041120 => 1030.1120041120
1887 // 1.3.12-rc1 => 1030.119
1888 function phpwiki_version() {
1889 static $PHPWIKI_VERSION;
1890 if (!isset($PHPWIKI_VERSION)) {
1891 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1892 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1893 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1894 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1895 $PHPWIKI_VERSION -= 0.01;
1897 return $PHPWIKI_VERSION;
1900 function phpwiki_gzhandler($ob) {
1901 if (function_exists('gzencode'))
1902 $ob = gzencode($ob);
1903 $GLOBALS['request']->_ob_get_length = strlen($ob);
1904 if (!headers_sent()) {
1905 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1910 function isWikiWord($word) {
1911 global $WikiNameRegexp;
1912 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1913 return preg_match("/^$WikiNameRegexp\$/",$word);
1916 // needed to store serialized objects-values only (perm, pref)
1917 function obj2hash ($obj, $exclude = false, $fields = false) {
1919 if (! $fields ) $fields = get_object_vars($obj);
1920 foreach ($fields as $key => $val) {
1921 if (is_array($exclude)) {
1922 if (in_array($key, $exclude)) continue;
1930 * isUtf8String($string) - cheap utf-8 detection
1932 * segfaults for strings longer than 10kb!
1933 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1934 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1936 function isUtf8String( $s ) {
1937 $ptrASCII = '[\x00-\x7F]';
1938 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1939 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1940 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1941 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1942 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1943 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1947 * Check for UTF-8 URLs; Internet Explorer produces these if you
1948 * type non-ASCII chars in the URL bar or follow unescaped links.
1949 * Requires urldecoded pagename.
1950 * Fixes sf.net bug #953949
1952 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1954 function fixTitleEncoding( $s ) {
1959 if (empty($s)) return $s;
1961 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1963 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1964 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1966 $isutf = ($ishigh ? isUtf8String($s) : true);
1967 $locharset = strtolower($charset);
1969 if( $locharset != "utf-8" and $ishigh and $isutf )
1970 $s = charset_convert('UTF-8', $locharset, $s);
1971 if ($locharset == "utf-8" and $ishigh and !$isutf )
1972 return utf8_encode( $s );
1974 // Other languages can safely leave this function, or replace
1975 // it with one to detect and convert another legacy encoding.
1980 * MySQL fulltext index doesn't grok utf-8, so we
1981 * need to fold cases and convert to hex.
1982 * src: languages/Language.php:stripForSearch() from mediawiki
1985 function stripForSearch( $string ) {
1986 global $wikiLowerChars;
1987 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1988 return preg_replace(
1989 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1990 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1996 * Workaround for allow_url_fopen, to get the content of an external URI.
1997 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1998 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2000 function url_get_contents( $uri ) {
2001 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2002 return @file_get_contents($uri);
2004 require_once("lib/HttpClient.php");
2005 $bits = parse_url($uri);
2006 $host = $bits['host'];
2007 $port = isset($bits['port']) ? $bits['port'] : 80;
2008 $path = isset($bits['path']) ? $bits['path'] : '/';
2009 if (isset($bits['query'])) {
2010 $path .= '?'.$bits['query'];
2012 $client = new HttpClient($host, $port);
2013 $client->use_gzip = false;
2014 if (!$client->get($path)) {
2017 return $client->getContent();
2023 * Generate consecutively named strings:
2024 * Name, Name2, Name3, ...
2026 function GenerateId($name) {
2027 static $ids = array();
2028 if (empty($ids[$name])) {
2033 return $name . $ids[$name];
2037 // from IncludePage. To be of general use.
2038 // content: string or array of strings
2039 function firstNWordsOfContent( $n, $content ) {
2040 if ($content and $n > 0) {
2041 if (is_array($content)) {
2042 // fixme: return a list of lines then?
2043 //$content = join("\n", $content);
2044 //$return_array = true;
2046 foreach ($content as $line) {
2047 $words = explode(' ', $line);
2048 if ($wordcount + count($words) > $n) {
2049 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2050 . sprintf(_("... (first %s words)"), $n);
2053 $wordcount += count($words);
2059 // fixme: use better whitespace/word seperators
2060 $words = explode(' ', $content);
2061 if (count($words) > $n) {
2062 return join(' ', array_slice($words, 0, $n))
2063 . sprintf(_("... (first %s words)"), $n);
2073 // moved from lib/plugin/IncludePage.php
2074 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2075 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2077 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
2078 . " \\s*$\\n?" // possible blank lines
2079 . " ( (?: ^.*\\n? )*? )" // some lines
2080 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2081 implode("\n", $content),
2083 // Strip trailing blanks lines and ---- <hr>s
2084 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2086 $text = $match[1] . $section ."\n". $text;
2087 return explode("\n", $text);
2090 $mesg = $page ." ". $section;
2093 return array(sprintf(_("<%s: no such section>"), $mesg));
2096 // use this faster version: only load ExternalReferrer if we came from an external referrer
2097 function isExternalReferrer(&$request) {
2098 if ($referrer = $request->get('HTTP_REFERER')) {
2099 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2100 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2101 require_once("lib/ExternalReferrer.php");
2102 $se = new SearchEngines();
2103 return $se->parseSearchQuery($referrer);
2105 //if (DEBUG) return array('query' => 'wiki');
2110 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2112 function loadPhpExtension($extension) {
2113 if (!extension_loaded($extension)) {
2114 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2115 $soname = ($isWindows ? 'php_' : '')
2117 . ($isWindows ? '.dll' : '.so');
2121 return extension_loaded($extension);
2124 function charset_convert($from, $to, $data) {
2126 //$wikicharset = strtolower($CHARSET);
2127 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2128 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2129 return utf8_decode($data);
2130 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2131 return utf8_encode($data);
2133 if (loadPhpExtension("iconv")) {
2134 $tmpdata = iconv($from, $to, $data);
2136 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2140 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2145 function string_starts_with($string, $prefix) {
2146 return (substr($string, 0, strlen($prefix)) == $prefix);
2148 function string_ends_with($string, $suffix) {
2149 return (substr($string, -strlen($suffix)) == $suffix);
2151 function array_remove($arr,$value) {
2152 return array_values(array_diff($arr,array($value)));
2156 * Ensure that the script will have another $secs time left.
2157 * Works only if safe_mode is off.
2158 * For example not to timeout on waiting socket connections.
2159 * Use the socket timeout as arg.
2161 function longer_timeout($secs = 30) {
2162 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2163 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2164 if ($timeleft < $secs)
2165 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2168 function printSimpleTrace($bt) {
2170 echo "\nTraceback:\n";
2171 if (function_exists('debug_print_backtrace')) { // >= 5
2172 debug_print_backtrace();
2174 foreach ($bt as $i => $elem) {
2175 if (!array_key_exists('file', $elem)) {
2178 //echo join(" ",array_values($elem)),"\n";
2179 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2185 * Return the used process memory, in bytes.
2186 * Enable the section which will work for you. They are very slow.
2187 * Special quirks for Windows: Requires cygwin.
2189 function getMemoryUsage() {
2190 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2191 if (function_exists('memory_get_usage') and memory_get_usage()) {
2192 return memory_get_usage();
2193 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2194 $mem = $u['ru_maxrss'];
2195 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2196 // what we want is the process memory only: apache or php (if CGI)
2199 // win32_ps_stat_proc, win32_ps_stat_mem
2200 if (function_exists('win32_ps_list_procs')) {
2201 $info = win32_ps_stat_proc($pid);
2202 $memstr = $info['mem']['working_set_size'];
2204 // This works only if it's a cygwin process (apache or php).
2205 // Requires a newer cygwin
2206 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2208 // if it's native windows use something like this:
2209 // (requires pslist from sysinternals.com, grep, sed and perl)
2210 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2212 return (integer) trim($memstr);
2215 //%MEM: Percentage of total memory in use by this process
2216 //VSZ: Total virtual memory size, in 1K blocks.
2217 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2218 //CPU time used by process since it started.
2219 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2220 $memstr = exec("ps -orss -p $pid|sed 1d");
2221 return (integer) trim($memstr);
2226 * @param var $needle
2227 * @param array $haystack one-dimensional numeric array only, no hash
2229 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2230 It will return false if not found or the index where it was found.
2231 From dennis.decoene@moveit.be http://www.php.net/array_search
2233 function binary_search($needle, $haystack) {
2234 $high = count($haystack);
2237 while (($high - $low) > 1) {
2238 $probe = floor(($high + $low) / 2);
2239 if ($haystack[$probe] < $needle) {
2241 } elseif ($haystack[$probe] == $needle) {
2242 $high = $low = $probe;
2248 if ($high == count($haystack) || $haystack[$high] != $needle) {
2255 function is_localhost($url = false) {
2257 global $HTTP_SERVER_VARS;
2258 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2263 * Take a string and quote it sufficiently to be passed as a Javascript
2264 * string between ''s
2266 function javascript_quote_string($s) {
2267 return str_replace("'", "\'", $s);
2270 function isSerialized($s) {
2271 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2274 // $Log: not supported by cvs2svn $
2275 // Revision 1.274 2008/05/06 19:29:06 rurban
2276 // support Upload:image_with_foreign_chars: do urldecode links to such files
2278 // Revision 1.273 2008/03/22 21:43:21 rurban
2279 // Fix syntax error from r1.272
2281 // Revision 1.272 2008/03/21 20:35:52 rurban
2282 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
2283 // Object tags now render as label correctly and param tags are also added.
2285 // Revision 1.271 2008/03/17 19:11:06 rurban
2286 // adedd isSerialized: get rid of @ error protection in unserialize
2287 // revert & links
2288 // protect $WikiTheme->VALID_LINKS
2289 // replace strtr by preg_replace; document problem (still exists?
2290 // Todo: glob pattern test)
2292 // Revision 1.270 2008/01/31 20:21:12 vargenau
2293 // Valid HTML: escape ampersand
2295 // Revision 1.269 2008/01/24 19:17:03 rurban
2296 // add javascript_quote_string for Theme
2298 // Revision 1.268 2007/09/15 12:28:46 rurban
2299 // Improve multi-page format handling: abstract _DumpHtmlToDir. get rid of non-external pdf, non-global VALID_LINKS
2301 // Revision 1.267 2007/09/12 19:32:29 rurban
2302 // link only VALID_LINKS with pagelist HTML_DUMP
2304 // Revision 1.266 2007/09/01 13:24:23 rurban
2305 // add INSECURE_ACTIONS_LOCALHOST_ONLY. advanced security settings
2307 // Revision 1.265 2007/08/08 18:47:14 rurban
2308 // * Fix EmailNotify for Subpages: Unknown modifier ? at any page save.
2309 // Quoting error on glob_match.
2310 // * Fix binary_search
2312 // Revision 1.264 2007/07/15 17:39:42 rurban
2313 // add binary_search. enable memory ps calls
2315 // Revision 1.263 2007/07/14 12:05:29 rurban
2316 // add url field to WikiPageName for interwiki expansion
2318 // Revision 1.262 2007/06/07 17:02:01 rurban
2319 // fix display of pagenames containing ":" in certain lists
2321 // Revision 1.261 2007/06/01 06:37:53 rurban
2322 // use native debug_print_backtrace
2324 // Revision 1.260 2007/02/17 14:15:21 rurban
2325 // fix ImgLink params: $ori_url
2327 // Revision 1.259 2007/01/20 11:41:38 rurban
2328 // WikiPagename::_check: add flatfile support
2330 // Revision 1.258 2007/01/07 18:43:51 rurban
2331 // Remove FileFinder dependency for loadPhpExtension()
2333 // Revision 1.257 2007/01/03 21:24:56 rurban
2334 // Disable noisy ps subprocess on DEBUG. Turn it on explicitly on memory debugging. Add convert_charset helper. Use convert_charset().
2336 // Revision 1.256 2007/01/02 13:23:49 rurban
2337 // ftnt_${footnum}: do not confuse old php string definition parsers. Clarify API: sortby,limit and exclude are strings.
2339 // Revision 1.255 2006/12/22 16:53:38 rurban
2340 // Try to dl() load the iconv extension, if not already loaded
2342 // Revision 1.254 2006/12/02 19:53:05 rurban
2343 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2344 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2347 // Revision 1.253 2006/08/25 22:20:52 rurban
2348 // better split subpages at sep
2350 // Revision 1.252 2006/06/18 11:03:36 rurban
2351 // support rc version
2353 // Revision 1.251 2006/03/19 15:01:00 rurban
2354 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2356 // Revision 1.250 2006/03/07 20:45:44 rurban
2357 // wikihash for php-5.1
2359 // Revision 1.249 2005/10/30 14:24:33 rurban
2360 // move rand_ascii_readable from Captcha to stdlib
2362 // Revision 1.248 2005/10/29 14:18:30 uckelman
2363 // Added is_a() deprecation note.
2365 // Revision 1.247 2005/10/10 20:31:21 rurban
2368 // Revision 1.246 2005/10/10 19:38:48 rurban
2371 // Revision 1.245 2005/09/18 16:01:09 rurban
2372 // trick to send the correct gzipped Content-Length
2374 // Revision 1.244 2005/09/11 13:24:33 rurban
2375 // fix shortname, dont quote twice in ListRegexExpand
2377 // Revision 1.243 2005/08/06 15:01:38 rurban
2378 // workaround php VBASIC alike limitation: allow integer pagenames
2380 // Revision 1.242 2005/08/06 13:07:04 rurban
2381 // quote paths correctly (not the best method though)
2383 // Revision 1.241 2005/05/06 16:54:19 rurban
2384 // support optional EXTERNAL_LINK_TARGET, default: _blank
2386 // Revision 1.240 2005/04/23 11:15:49 rurban
2387 // handle allowed inlined objects within INLINE_IMAGES
2389 // Revision 1.239 2005/04/01 16:11:42 rurban
2392 // Revision 1.238 2005/03/04 16:29:14 rurban
2393 // Fixed bug #994994 (escape / in glob)
2394 // Optimized glob_to_pcre within fileSet() matching.
2396 // Revision 1.237 2005/02/12 17:22:18 rurban
2397 // locale update: missing . : fixed. unified strings
2398 // proper linebreaks
2400 // Revision 1.236 2005/02/08 13:41:32 rurban
2403 // Revision 1.235 2005/02/04 11:54:48 rurban
2406 // Revision 1.234 2005/02/03 05:09:25 rurban
2407 // Talk: + User: fix
2409 // Revision 1.233 2005/02/02 20:40:12 rurban
2410 // fix Talk: and User: names and links
2412 // Revision 1.232 2005/02/02 19:34:09 rurban
2413 // more maps: Talk, User
2415 // Revision 1.231 2005/01/30 19:48:52 rurban
2416 // enable ps memory on unix
2418 // Revision 1.230 2005/01/25 07:10:51 rurban
2419 // add getMemoryUsage to stdlib
2421 // Revision 1.229 2005/01/21 11:51:22 rurban
2424 // Revision 1.228 2005/01/17 20:28:30 rurban
2425 // Allow more pagename chars: Limit only on certain backends.
2426 // Re-Allow : and ; and control chars on non-file backends.
2428 // Revision 1.227 2005/01/14 18:32:08 uckelman
2429 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2430 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2431 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2432 // conversion of '__' into '<strong>', and then unhidden afterwards.
2434 // Revision 1.226 2004/12/26 17:12:06 rurban
2435 // avoid stdargs in url, php5 fixes
2437 // Revision 1.225 2004/12/22 19:02:29 rurban
2438 // fix glob for starting * or ?
2440 // Revision 1.224 2004/12/20 12:11:50 rurban
2441 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2442 // not reproducable other than on sf.net, but this seems to fix it.
2444 // Revision 1.223 2004/12/18 16:49:29 rurban
2445 // fix RPC for !USE_PATH_INFO, add debugging helper
2447 // Revision 1.222 2004/12/17 16:40:45 rurban
2448 // add not yet used url helper
2450 // Revision 1.221 2004/12/06 19:49:58 rurban
2451 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2452 // renamed delete_page to purge_page.
2453 // enable action=edit&version=-1 to force creation of a new version.
2454 // added BABYCART_PATH config
2455 // fixed magiqc in adodb.inc.php
2456 // and some more docs
2458 // Revision 1.220 2004/11/30 17:47:41 rurban
2459 // added mt_srand, check for native isa
2461 // Revision 1.219 2004/11/26 18:39:02 rurban
2462 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2464 // Revision 1.218 2004/11/25 08:28:48 rurban
2467 // Revision 1.217 2004/11/16 17:31:03 rurban
2468 // re-enable old block markup conversion
2470 // Revision 1.216 2004/11/11 18:31:26 rurban
2471 // add simple backtrace on such general failures to get at least an idea where
2473 // Revision 1.215 2004/11/11 14:34:12 rurban
2474 // minor clarifications
2476 // Revision 1.214 2004/11/11 11:01:20 rurban
2477 // fix loadPhpExtension
2479 // Revision 1.213 2004/11/01 10:43:57 rurban
2480 // seperate PassUser methods into seperate dir (memory usage)
2481 // fix WikiUser (old) overlarge data session
2482 // remove wikidb arg from various page class methods, use global ->_dbi instead
2485 // Revision 1.212 2004/10/22 09:15:39 rurban
2486 // Alert::show has no arg anymore
2488 // Revision 1.211 2004/10/22 09:05:11 rurban
2489 // added longer_timeout (HttpClient)
2492 // Revision 1.210 2004/10/14 21:06:02 rurban
2493 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2495 // Revision 1.209 2004/10/14 19:19:34 rurban
2496 // loadsave: check if the dumped file will be accessible from outside.
2497 // and some other minor fixes. (cvsclient native not yet ready)
2499 // Revision 1.208 2004/10/12 13:13:20 rurban
2500 // php5 compatibility (5.0.1 ok)
2502 // Revision 1.207 2004/09/26 12:21:40 rurban
2503 // removed old log entries.
2504 // added persistent start_debug on internal links and DEBUG
2505 // added isExternalReferrer (not yet used)
2507 // Revision 1.206 2004/09/25 16:28:36 rurban
2508 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2510 // Revision 1.205 2004/09/23 13:59:35 rurban
2511 // Before removing a page display a sample of 100 words.
2513 // Revision 1.204 2004/09/17 13:19:15 rurban
2514 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2517 // Revision 1.203 2004/09/16 08:00:52 rurban
2518 // just some comments
2520 // Revision 1.202 2004/09/14 10:11:44 rurban
2521 // start 2nd Id with ...Plugin2
2523 // Revision 1.201 2004/09/14 10:06:42 rurban
2524 // generate iterated plugin ids, set plugin span id also
2526 // Revision 1.200 2004/08/05 17:34:26 rurban
2527 // move require to sortby branch
2529 // Revision 1.199 2004/08/05 10:38:15 rurban
2530 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
2533 // Revision 1.198 2004/07/02 10:30:36 rurban
2534 // always disable getimagesize for < php-4.3 with external png's
2536 // Revision 1.197 2004/07/02 09:55:58 rurban
2537 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2539 // Revision 1.196 2004/07/01 08:51:22 rurban
2540 // dumphtml: added exclude, print pagename before processing
2542 // Revision 1.195 2004/06/29 08:52:22 rurban
2543 // Use ...version() $need_content argument in WikiDB also:
2544 // To reduce the memory footprint for larger sets of pagelists,
2545 // we don't cache the content (only true or false) and
2546 // we purge the pagedata (_cached_html) also.
2547 // _cached_html is only cached for the current pagename.
2548 // => Vastly improved page existance check, ACL check, ...
2550 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2552 // Revision 1.194 2004/06/29 06:48:04 rurban
2553 // Improve LDAP auth and GROUP_LDAP membership:
2554 // no error message on false password,
2555 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2556 // fixed two group queries (this -> user)
2557 // stdlib: ConvertOldMarkup still flawed
2559 // Revision 1.193 2004/06/28 13:27:03 rurban
2560 // CreateToc disabled for old markup and Apache2 only
2562 // Revision 1.192 2004/06/28 12:47:43 rurban
2563 // skip if non-DEBUG and old markup with CreateToc
2565 // Revision 1.191 2004/06/25 14:31:56 rurban
2566 // avoid debug_skip warning
2568 // Revision 1.190 2004/06/25 14:29:20 rurban
2569 // WikiGroup refactoring:
2570 // global group attached to user, code for not_current user.
2571 // improved helpers for special groups (avoid double invocations)
2572 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2573 // fixed a XHTML validation error on userprefs.tmpl
2575 // Revision 1.189 2004/06/20 09:45:35 rurban
2576 // php5 isa fix (wrong strtolower)
2578 // Revision 1.188 2004/06/16 10:38:58 rurban
2579 // Disallow refernces in calls if the declaration is a reference
2580 // ("allow_call_time_pass_reference clean").
2581 // PhpWiki is now allow_call_time_pass_reference = Off clean,
2582 // but several external libraries may not.
2583 // In detail these libs look to be affected (not tested):
2587 // Revision 1.187 2004/06/14 11:31:37 rurban
2588 // renamed global $Theme to $WikiTheme (gforge nameclash)
2589 // inherit PageList default options from PageList
2590 // default sortby=pagename
2591 // use options in PageList_Selectable (limit, sortby, ...)
2592 // added action revert, with button at action=diff
2593 // added option regex to WikiAdminSearchReplace
2595 // Revision 1.186 2004/06/13 13:54:25 rurban
2596 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2597 // FoafViewer: Check against external requirements, instead of fatal.
2598 // Change output for xhtmldumps: using file:// urls to the local fs.
2599 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2600 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2602 // Revision 1.185 2004/06/11 09:07:30 rurban
2603 // support theme-specific LinkIconAttr: front or after or none
2605 // Revision 1.184 2004/06/04 20:32:53 rurban
2606 // Several locale related improvements suggested by Pierrick Meignen
2607 // LDAP fix by John Cole
2608 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2610 // Revision 1.183 2004/06/01 10:22:56 rurban
2611 // added url_get_contents() used in XmlParser and elsewhere
2613 // Revision 1.182 2004/05/25 12:40:48 rurban
2614 // trim the pagename
2616 // Revision 1.181 2004/05/25 10:18:44 rurban
2617 // Check for UTF-8 URLs; Internet Explorer produces these if you
2618 // type non-ASCII chars in the URL bar or follow unescaped links.
2619 // Fixes sf.net bug #953949
2620 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2622 // Revision 1.180 2004/05/18 16:23:39 rurban
2623 // rename split_pagename to SplitPagename
2625 // Revision 1.179 2004/05/18 16:18:37 rurban
2626 // AutoSplit at subpage seperators
2627 // RssFeed stability fix for empty feeds or broken connections
2629 // Revision 1.178 2004/05/12 10:49:55 rurban
2630 // require_once fix for those libs which are loaded before FileFinder and
2631 // its automatic include_path fix, and where require_once doesn't grok
2632 // dirname(__FILE__) != './lib'
2633 // upgrade fix with PearDB
2634 // navbar.tmpl: remove spaces for IE button alignment
2636 // Revision 1.177 2004/05/08 14:06:12 rurban
2637 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2638 // minor stability and portability fixes
2640 // Revision 1.176 2004/05/08 11:25:15 rurban
2643 // Revision 1.175 2004/05/06 17:30:38 rurban
2644 // CategoryGroup: oops, dos2unix eol
2645 // improved phpwiki_version:
2646 // pre -= .0001 (1.3.10pre: 1030.099)
2647 // -p1 += .001 (1.3.9-p1: 1030.091)
2648 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2649 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2650 // backend->backendType(), backend->database(),
2651 // backend->listOfFields(),
2652 // backend->listOfTables(),
2654 // Revision 1.174 2004/05/06 12:02:05 rurban
2655 // fix sf.net bug#949002: [ Link | ] assertion
2657 // Revision 1.173 2004/05/03 15:00:31 rurban
2658 // added more database upgrading: session.sess_ip, page.id autp_increment
2660 // Revision 1.172 2004/04/26 20:44:34 rurban
2661 // locking table specific for better databases
2663 // Revision 1.171 2004/04/19 23:13:03 zorloc
2664 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
2666 // Revision 1.170 2004/04/19 18:27:45 rurban
2667 // Prevent from some PHP5 warnings (ref args, no :: object init)
2668 // php5 runs now through, just one wrong XmlElement object init missing
2669 // Removed unneccesary UpgradeUser lines
2670 // Changed WikiLink to omit version if current (RecentChanges)
2672 // Revision 1.169 2004/04/15 21:29:48 rurban
2673 // allow [0] with new markup: link to page "0"
2675 // Revision 1.168 2004/04/10 02:30:49 rurban
2676 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2677 // Fixed "cannot setlocale..." (sf.net problem)
2679 // Revision 1.167 2004/04/02 15:06:55 rurban
2680 // fixed a nasty ADODB_mysql session update bug
2681 // improved UserPreferences layout (tabled hints)
2682 // fixed UserPreferences auth handling
2683 // improved auth stability
2684 // improved old cookie handling: fixed deletion of old cookies with paths
2686 // Revision 1.166 2004/04/01 15:57:10 rurban
2687 // simplified Sidebar theme: table, not absolute css positioning
2688 // added the new box methods.
2689 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2691 // Revision 1.165 2004/03/24 19:39:03 rurban
2692 // php5 workaround code (plus some interim debugging code in XmlElement)
2693 // php5 doesn't work yet with the current XmlElement class constructors,
2694 // WikiUserNew does work better than php4.
2695 // rewrote WikiUserNew user upgrading to ease php5 update
2696 // fixed pref handling in WikiUserNew
2697 // added Email Notification
2698 // added simple Email verification
2699 // removed emailVerify userpref subclass: just a email property
2700 // changed pref binary storage layout: numarray => hash of non default values
2701 // print optimize message only if really done.
2702 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2703 // prefs should be stored in db or homepage, besides the current session.
2705 // Revision 1.164 2004/03/18 21:41:09 rurban
2706 // fixed sqlite support
2707 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2709 // Revision 1.163 2004/03/17 18:41:49 rurban
2710 // just reformatting
2712 // Revision 1.162 2004/03/16 15:43:08 rurban
2713 // make fileSet sortable to please PageList
2715 // Revision 1.161 2004/03/12 15:48:07 rurban
2716 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2717 // simplified lib/stdlib.php:explodePageList
2719 // Revision 1.160 2004/02/28 21:14:08 rurban
2720 // generally more PHPDOC docs
2721 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2722 // fxied WikiUserNew pref handling: empty theme not stored, save only
2723 // changed prefs, sql prefs improved, fixed password update,
2724 // removed REPLACE sql (dangerous)
2725 // moved gettext init after the locale was guessed
2726 // + some minor changes
2729 // (c-file-style: "gnu")
2733 // c-basic-offset: 4
2734 // c-hanging-comment-ender-p: nil
2735 // indent-tabs-mode: nil