1 <?php //rcs_id('$Id: stdlib.php,v 1.265 2007-08-08 18:47:14 rurban Exp $');
3 Copyright 1999,2000,2001,2002,2004,2005 $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) {
164 if (is_object($pagename)) {
165 if (isa($pagename, 'WikiDB_Page')) {
166 $pagename = $pagename->getName();
168 elseif (isa($pagename, 'WikiDB_PageRevision')) {
169 $page = $pagename->getPage();
170 $args['version'] = $pagename->getVersion();
171 $pagename = $page->getName();
173 elseif (isa($pagename, 'WikiPageName')) {
174 $anchor = $pagename->anchor;
175 $pagename = $pagename->name;
177 $anchor = $pagename->anchor;
178 $pagename = $pagename->name;
181 if (!$get_abs_url and DEBUG and $GLOBALS['request']->getArg('start_debug')) {
183 $args = 'start_debug=' . $GLOBALS['request']->getArg('start_debug');
184 elseif (is_array($args))
185 $args['start_debug'] = $GLOBALS['request']->getArg('start_debug');
187 $args .= '&start_debug=' . $GLOBALS['request']->getArg('start_debug');
189 if (is_array($args)) {
191 foreach ($args as $key => $val) {
192 // avoid default args
193 if (USE_PATH_INFO and $key == 'pagename')
195 elseif ($key == 'action' and $val == 'browse')
197 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
198 $enc_args[] = urlencode($key) . '=' . urlencode($val);
200 $args = join('&', $enc_args);
203 if (USE_PATH_INFO or !empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX)) {
204 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
205 $url = $url . preg_replace('/%2f/i', '/', rawurlencode($pagename));
206 if (!empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX))
207 $url .= $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
212 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
213 $url .= "?pagename=" . rawurlencode($pagename);
218 $url .= "#" . MangleXmlIdentifier($anchor);
222 /** Convert relative URL to absolute URL.
224 * This converts a relative URL to one of PhpWiki's support files
225 * to an absolute one.
228 * @return string Absolute URL
230 function AbsoluteURL ($url) {
231 if (preg_match('/^https?:/', $url))
233 if ($url[0] != '/') {
234 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
235 while ($base != '/' and substr($url, 0, 3) == "../") {
236 $url = substr($url, 3);
237 $base = dirname($base);
243 return SERVER_URL . $url;
246 function DataURL ($url) {
247 if (preg_match('/^https?:/', $url))
249 $url = NormalizeWebFileName($url);
250 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
251 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
252 return AbsoluteURL($url);
256 * Generates icon in front of links.
258 * @param string $protocol_or_url URL or protocol to determine which icon to use.
260 * @return HtmlElement HtmlElement object that contains data to create img link to
261 * icon for use with url or protocol passed to the function. False if no img to be
264 function IconForLink($protocol_or_url) {
266 if (0 and $filename_suffix == false) {
267 // display apache style icon for file type instead of protocol icon
268 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
269 // - document: html, htm, text, txt, rtf, pdf, doc
270 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
271 // - audio: mp3,mp2,aiff,aif,au
272 // - multimedia: mpeg,mpg,mov,qt
274 list ($proto) = explode(':', $protocol_or_url, 2);
275 $src = $WikiTheme->getLinkIconURL($proto);
277 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
284 * Glue icon in front of or after text.
285 * Pref: 'noLinkIcons' - ignore icon if set
286 * Theme: 'LinkIcons' - 'yes' at front
287 * - 'no' display no icon
288 * - 'front' display at left
289 * - 'after' display at right
291 * @param string $protocol_or_url Protocol or URL. Used to determine the
293 * @param string $text The text.
294 * @return XmlContent.
296 function PossiblyGlueIconToText($proto_or_url, $text) {
297 global $request, $WikiTheme;
298 if ($request->getPref('noLinkIcons'))
300 $icon = IconForLink($proto_or_url);
303 if ($where = $WikiTheme->getLinkIconAttr()) {
304 if ($where == 'no') return $text;
305 if ($where != 'after') $where = 'front';
309 if ($where == 'after') {
310 // span the icon only to the last word (tie them together),
311 // to let the previous words wrap on line breaks.
312 if (!is_object($text)) {
313 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
314 list (, $prefix, $last_word) = $m;
320 $text = HTML::span(array('style' => 'white-space: nowrap'),
321 $last_word, HTML::Raw(' '), $icon);
323 $text = HTML($prefix, $text);
326 // span the icon only to the first word (tie them together),
327 // to let the next words wrap on line breaks
328 if (!is_object($text)) {
329 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
330 list (, $first_word, $tail) = $m;
336 $text = HTML::span(array('style' => 'white-space: nowrap'),
339 $text = HTML($text, $tail);
344 * Determines if the url passed to function is safe, by detecting if the characters
345 * '<', '>', or '"' are present.
346 * Check against their urlencoded values also.
348 * @param string $url URL to check for unsafe characters.
349 * @return boolean True if same, false else.
351 function IsSafeURL($url) {
352 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
356 * Generates an HtmlElement object to store data for a link.
358 * @param string $url URL that the link will point to.
359 * @param string $linktext Text to be displayed as link.
360 * @return HtmlElement HtmlElement object that contains data to construct an html link.
362 function LinkURL($url, $linktext = '') {
363 // FIXME: Is this needed (or sufficient?)
364 if(! IsSafeURL($url)) {
365 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
366 _("BAD URL -- remove all of <, >, \"")));
370 $linktext = preg_replace("/mailto:/A", "", $url);
371 $args = array('href' => $url);
372 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
373 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
374 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
376 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
383 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
384 * Disallows sizes which are too small.
385 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
387 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
389 function LinkImage($url, $alt = false) {
390 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
391 // Disallow tags in img src urls. Typical CSS attacks.
392 // FIXME: Is this needed (or sufficient?)
393 if(! IsSafeURL($url)) {
394 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
395 _("BAD URL -- remove all of <, >, \"")));
397 // support new syntax: [image.jpg size=50% border=n]
398 //if (!preg_match("/\.(".$force_img.")/i", $url))
400 $arr = split(' ',$url);
401 if (count($arr) > 1) {
404 if (empty($alt)) $alt = basename($url);
405 $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
406 if (count($arr) > 1) {
408 foreach ($arr as $attr) {
409 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
410 $link->setAttr('width',$m[1]);
411 $link->setAttr('height',$m[1]);
413 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
414 $link->setAttr('width',$m[1]);
415 $link->setAttr('height',$m[2]);
417 if (preg_match('/^border=(\d+)$/',$attr,$m))
418 $link->setAttr('border',$m[1]);
419 if (preg_match('/^align=(\w+)$/',$attr,$m))
420 $link->setAttr('align',$m[1]);
421 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
422 $link->setAttr('hspace',$m[1]);
423 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
424 $link->setAttr('vspace',$m[1]);
427 // Check width and height as spam countermeasure
428 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
429 //$width = (int) $width; // px or % or other suffix
430 //$height = (int) $height;
431 if (($width < 3 and $height < 10) or
432 ($height < 3 and $width < 20) or
433 ($height < 7 and $width < 7))
435 trigger_error(_("Invalid image size"), E_USER_WARNING);
439 // Older php versions crash here with certain png's:
440 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
441 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
442 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
443 if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
444 ; // it's safe to assume that this will fail.
445 elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
448 if (($width < 3 and $height < 10)
449 or ($height < 3 and $width < 20)
450 or ($height < 7 and $width < 7))
452 trigger_error(_("Invalid image size"), E_USER_WARNING);
458 $link->setAttr('class', 'inlineimage');
460 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
461 * png|jpg|gif|jpeg|bmp|pl|cgi
462 * Note: Allow cgi's (pl,cgi) returning images.
464 if (!preg_match("/\.(".$force_img.")/i", $url)) {
465 //HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
466 // => HTML::object(array('src' => $url)) ...;
467 return ImgObject($link, $ori_url);
473 * <object> / <embed> tags instead of <img> for all non-image extensions allowed via INLINE_IMAGES
474 * Called by LinkImage(), not directly.
475 * Syntax: [image.svg size=50% border=n align= hspace= vspace= width= height=]
476 * $alt may be an alternate img
477 * TODO: Need to unify with WikiPluginCached::embedObject()
479 * Note that Safari 1.0 will crash with <object>, so use only <embed>
480 * http://www.alleged.org.uk/pdc/2002/svg-object.html
482 function ImgObject($img, $url) {
483 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
484 $args = split(' ', $url);
485 if (count($args) >= 1) {
486 $url = array_shift($args);
487 foreach ($args as $attr) {
488 if (preg_match('/^type=(\S+)$/',$attr,$m))
489 $img->setAttr('type', $m[1]);
490 if (preg_match('/^data=(\S+)$/',$attr,$m))
491 $img->setAttr('data', $m[1]);
494 $type = $img->getAttr('type');
496 // TODO: map extension to mime-types if type is not given and php < 4.3
497 if (function_exists('mime_content_type'))
498 $type = mime_content_type($url);
500 $link = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)));
501 $link->setAttr('class', 'inlineobject');
502 if (isBrowserSafari()) {
503 return HTML::embed($link->_attr);
505 $link->pushContent(HTML::embed($link->_attr));
512 // var in php5 deprecated
514 $this->items = array();
517 function push($item) {
518 $this->items[$this->size] = $item;
524 if ($this->size == 0) {
525 return false; // stack is empty
528 return $this->items[$this->size];
537 return $this->items[$this->size - 1];
543 // end class definition
545 function SplitQueryArgs ($query_args = '')
547 // FIXME: use the arg-seperator which might not be &
548 $split_args = split('&', $query_args);
550 while (list($key, $val) = each($split_args))
551 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
552 $args[$m[1]] = $m[2];
556 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
559 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
560 return HTML::strong(array('class' => 'rawurl'),
561 HTML::u(array('class' => 'baduri'),
562 _("BAD phpwiki: URL")));
566 $pagename = urldecode($m[1]);
569 if (empty($pagename) &&
570 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
571 // Convert old style links (to not break diff links in
573 $pagename = urldecode($m[2]);
574 $args = array("action" => $m[1]);
577 $args = SplitQueryArgs($qargs);
580 if (empty($pagename))
581 $pagename = $GLOBALS['request']->getArg('pagename');
583 if (isset($args['action']) && $args['action'] == 'browse')
584 unset($args['action']);
587 if (empty($args['action']))
589 else if (is_safe_action($args['action']))
590 $class = 'wikiaction';
592 if (empty($args['action']) || is_safe_action($args['action']))
593 $class = 'wikiaction';
595 // Don't allow administrative links on unlocked pages.
596 $dbi = $GLOBALS['request']->getDbh();
597 $page = $dbi->getPage($basepage ? $basepage : $pagename);
598 if (!$page->get('locked'))
599 return HTML::span(array('class' => 'wikiunsafe'),
600 HTML::u(_("Lock page to enable link")));
601 $class = 'wikiadmin';
605 $text = HTML::span(array('class' => 'rawurl'), $url);
607 $wikipage = new WikiPageName($pagename);
608 if (!$wikipage->isValid()) {
610 return $WikiTheme->linkBadWikiWord($wikipage, $url);
613 return HTML::a(array('href' => WikiURL($pagename, $args),
619 * A class to assist in parsing wiki pagenames.
621 * Now with subpages and anchors, parsing and passing around
622 * pagenames is more complicated. This should help.
626 /** Short name for page.
628 * This is the value of $name passed to the constructor.
629 * (For use, e.g. as a default label for links to the page.)
633 /** The full page name.
635 * This is the full name of the page (without anchor).
641 * This is the referenced anchor within the page, or the empty string.
647 * @param mixed $name Page name.
648 * WikiDB_Page, WikiDB_PageRevision, or string.
649 * This can be a relative subpage name (like '/SubPage'),
650 * or can be the empty string to refer to the $basename.
652 * @param string $anchor For links to anchors in page.
654 * @param mixed $basename Page name from which to interpret
655 * relative or other non-fully-specified page names.
657 function WikiPageName($name, $basename=false, $anchor=false) {
658 if (is_string($name)) {
659 $this->shortName = $name;
660 if (strstr($name, ':')) {
661 list($moniker, $shortName) = split (":", $name, 2);
662 $map = getInterwikiMap(); // allow overrides to custom maps
663 if (isset($map->_map[$moniker])) {
664 $url = $map->_map[$moniker];
665 if (strstr($url, '%s'))
666 $url = sprintf($url, $shortName);
669 $this->shortName = $shortName;
671 // expand Talk or User, but not to absolute urls!
672 if (strstr($url, '//')) {
673 if ($moniker == 'Talk')
674 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
675 elseif ($moniker == 'User')
680 if (strstr($name, '?'))
681 list($name, $dummy) = split("?", $name, 2);
684 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
685 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
687 $name = $this->_pagename($basename) . $name;
689 $name = $this->_normalize_bad_pagename($name);
690 $this->shortName = $name;
695 $name = $this->_pagename($name);
696 $this->shortName = $name;
699 $this->name = $this->_check($name);
700 $this->anchor = (string)$anchor;
707 function getParent() {
709 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
711 return substr($name, 0, -strlen($tail));
714 function isValid($strict = false) {
716 return !isset($this->_errors);
717 return (is_string($this->name) and $this->name != '');
720 function getWarnings() {
722 if (isset($this->_warnings))
723 $warnings = array_merge($warnings, $this->_warnings);
724 if (isset($this->_errors))
725 $warnings = array_merge($warnings, $this->_errors);
729 return sprintf(_("'%s': Bad page name: %s"),
730 $this->shortName, join(', ', $warnings));
733 function _pagename($page) {
734 if (isa($page, 'WikiDB_Page'))
735 return $page->getName();
736 elseif (isa($page, 'WikiDB_PageRevision'))
737 return $page->getPageName();
738 elseif (isa($page, 'WikiPageName'))
740 // '0' or e.g. '1984' should be allowed though
741 if (!is_string($page) and !is_integer($page)) {
742 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
743 $page, gettype($page), get_class($page)),
746 //assert(is_string($page));
750 function _normalize_bad_pagename($name) {
751 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
753 // Punt... You really shouldn't get here.
756 return $request->getArg('pagename');
758 assert($name[0] == SUBPAGE_SEPARATOR);
759 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
760 return substr($name, 1);
764 * Compress internal white-space to single space character.
766 * This leads to problems with loading a foreign charset pagename,
767 * which cannot be deleted anymore, because unknown chars are compressed.
768 * So BEFORE importing a file _check must be done !!!
770 function _check($pagename) {
771 // Compress internal white-space to single space character.
772 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
773 if ($pagename != $orig)
774 $this->_warnings[] = _("White space converted to single space");
776 // Delete any control characters.
777 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
778 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
779 if ($pagename != $orig)
780 $this->_errors[] = _("Control characters not allowed");
783 // Strip leading and trailing white-space.
784 $pagename = trim($pagename);
787 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
788 $pagename = substr($pagename, 1);
789 if ($pagename != $orig)
790 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
792 // ";" is urlencoded, so safe from php arg-delim problems
793 /*if (strstr($pagename, ';')) {
794 $this->_warnings[] = _("';' is deprecated");
795 $pagename = str_replace(';', '', $pagename);
798 // not only for SQL, also to restrict url length
799 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
800 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
801 $this->_errors[] = _("too long");
804 // disallow some chars only on file and cvs
805 if ((DATABASE_TYPE == 'cvs'
806 or DATABASE_TYPE == 'file'
807 or DATABASE_TYPE == 'flatfile')
808 and preg_match('/(:|\.\.)/', $pagename, $m))
810 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
811 $pagename = str_replace('..', '', $pagename);
812 $pagename = str_replace(':', '', $pagename);
820 * Convert old page markup to new-style markup.
822 * @param string $text Old-style wiki markup.
824 * @param string $markup_type
826 * <dt><code>"block"</code> <dd>Convert all markup.
827 * <dt><code>"inline"</code> <dd>Convert only inline markup.
828 * <dt><code>"links"</code> <dd>Convert only link markup.
831 * @return string New-style wiki markup.
833 * @bugs Footnotes don't work quite as before (esp if there are
834 * multiple references to the same footnote. But close enough,
835 * probably for now....
836 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
837 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
838 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
839 * also known to crash, even with Apache1.
841 function ConvertOldMarkup ($text, $markup_type = "block") {
847 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
848 // AnciennesR%E8glesDeFormatage crashes.
849 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
850 // also known to crash, even with Apache1.
852 // I suspect this only to crash with Apache2 and IIS.
853 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
854 and preg_match("/plugin CreateToc/", $text))
856 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
857 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
858 ._("Skipped."), E_USER_WARNING);
860 //if (!DEBUG) return $text;
865 /*****************************************************************
866 * Conversions for inline markup:
873 // escape escaped brackets
877 // change ! escapes to ~'s.
878 global $WikiNameRegexp, $request;
879 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
880 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
881 if (check_php_version(4,3,9)) {
882 $map = getInterwikiMap();
883 if ($map_regex = $map->getRegexp())
884 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
886 $bang_esc[] = $WikiNameRegexp;
887 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
890 $subs["links"] = array($orig, $repl);
892 // Temporarily URL-encode pairs of underscores in links to hide
893 // them from the re for bold markup.
894 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
895 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
898 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
901 // Convert footnote references.
902 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
903 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
905 // Convert old style emphases to HTML style emphasis.
906 $orig[] = '/__(.*?)__/';
907 $repl[] = '<strong>\\1</strong>';
908 $orig[] = "/''(.*?)''/";
909 $repl[] = '<em>\\1</em>';
911 // Escape nestled markup.
912 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
915 // in old markup headings only allowed at beginning of line
919 // Convert URL-encoded pairs of underscores in links back to
920 // real underscores after bold markup has been converted.
921 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
922 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
924 $subs["inline"] = array($orig, $repl);
926 /*****************************************************************
927 * Patterns which match block markup constructs which take
928 * special handling...
932 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
934 $blockpats[] = '\|(?:.*\n\|)*';
937 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
939 // Footnote definitions
940 $blockpats[] = '\[\s*(\d+)\s*\]';
944 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
948 $blockpats[] = '!{1,3}[^!]';
950 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
951 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
953 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
954 . join("|", $blockpats)
959 if ($markup_type != "block") {
960 list ($orig, $repl) = $subs[$markup_type];
961 return preg_replace($orig, $repl, $text);
964 list ($orig, $repl) = $subs['inline'];
967 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
968 // AnciennesR%E8glesDeFormatage and more
969 // See http://www.pcre.org/pcre.txt LIMITATIONS
970 while (preg_match($block_re, $text, $m)) {
971 $text = substr($text, strlen($m[0]));
972 list (,$leading_text, $block) = $m;
975 if (strchr(" \t", $block[0])) {
978 $suffix = "\n</pre>\n";
980 elseif ($block[0] == '|') {
982 $prefix = "<?plugin OldStyleTable\n";
985 elseif (strchr("#*;", $block[0])) {
986 // Old-style list item
987 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
988 list (,$ind,$bullet) = $m;
989 $block = substr($block, strlen($m[0]));
991 $indent = str_repeat(' ', strlen($ind));
992 if ($bullet[0] == ';') {
993 //$term = ltrim(substr($bullet, 1));
994 //return $indent . $term . "\n" . $indent . ' ';
995 $prefix = $ind . $bullet;
998 $prefix = $indent . $bullet . ' ';
1000 elseif ($block[0] == '[') {
1001 // Footnote definition
1002 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1004 $block = substr($block, strlen($m[0]));
1005 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1007 elseif ($block[0] == '<') {
1009 // HACK: no inline markup...
1013 elseif ($block[0] == '!') {
1015 preg_match('/^!{1,3}/', $block, $m);
1017 $block = substr($block, strlen($m[0]));
1023 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1024 if ($block) $block = preg_replace($orig, $repl, $block);
1025 $out .= $leading_text;
1030 return $out . preg_replace($orig, $repl, $text);
1036 * Expand tabs in string.
1038 * Converts all tabs to (the appropriate number of) spaces.
1040 * @param string $str
1041 * @param integer $tab_width
1044 function expand_tabs($str, $tab_width = 8) {
1045 $split = split("\t", $str);
1046 $tail = array_pop($split);
1048 foreach ($split as $hunk) {
1050 $pos = strlen(strrchr($expanded, "\n")) - 1;
1051 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1053 return substr($expanded, 1) . $tail;
1057 * Split WikiWords in page names.
1059 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1060 * places like page titles. This is rumored to help search engines
1063 * @param $page string The page name.
1065 * @return string The split name.
1067 function SplitPagename ($page) {
1069 if (preg_match("/\s/", $page))
1070 return $page; // Already split --- don't split any more.
1072 // This algorithm is specialized for several languages.
1073 // (Thanks to Pierrick MEIGNEN)
1074 // Improvements for other languages welcome.
1077 // This mess splits between a lower-case letter followed by
1078 // either an upper-case or a numeral; except that it wont
1079 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1080 switch ($GLOBALS['LANG']) {
1085 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1088 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1091 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1092 // This the single-letter words 'I' and 'A' from any following
1093 // capitalized words.
1094 switch ($GLOBALS['LANG']) {
1096 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1099 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1102 // Split numerals from following letters.
1103 $RE[] = '/(\d)([[:alpha:]])/';
1104 // Split at subpage seperators. TBD in Theme.php
1105 $RE[] = "/([^${sep}]+)(${sep})/";
1106 $RE[] = "/(${sep})([^${sep}]+)/";
1108 foreach ($RE as $key)
1109 $RE[$key] = pcre_fix_posix_classes($key);
1112 foreach ($RE as $regexp) {
1113 $page = preg_replace($regexp, '\\1 \\2', $page);
1118 function NoSuchRevision (&$request, $page, $version) {
1119 $html = HTML(HTML::h2(_("Revision Not Found")),
1120 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1121 $version, WikiLink($page, 'auto'))));
1122 include_once('lib/Template.php');
1123 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1129 * Get time offset for local time zone.
1131 * @param $time time_t Get offset for this time. Default: now.
1132 * @param $no_colon boolean Don't put colon between hours and minutes.
1133 * @return string Offset as a string in the format +HH:MM.
1135 function TimezoneOffset ($time = false, $no_colon = false) {
1136 if ($time === false)
1138 $secs = date('Z', $time);
1147 $colon = $no_colon ? '' : ':';
1148 $mins = intval(($secs + 30) / 60);
1149 return sprintf("%s%02d%s%02d",
1150 $sign, $mins / 60, $colon, $mins % 60);
1155 * Format time in ISO-8601 format.
1157 * @param $time time_t Time. Default: now.
1158 * @return string Date and time in ISO-8601 format.
1160 function Iso8601DateTime ($time = false) {
1161 if ($time === false)
1163 $tzoff = TimezoneOffset($time);
1164 $date = date('Y-m-d', $time);
1165 $time = date('H:i:s', $time);
1166 return $date . 'T' . $time . $tzoff;
1170 * Format time in RFC-2822 format.
1172 * @param $time time_t Time. Default: now.
1173 * @return string Date and time in RFC-2822 format.
1175 function Rfc2822DateTime ($time = false) {
1176 if ($time === false)
1178 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1182 * Format time in RFC-1123 format.
1184 * @param $time time_t Time. Default: now.
1185 * @return string Date and time in RFC-1123 format.
1187 function Rfc1123DateTime ($time = false) {
1188 if ($time === false)
1190 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1193 /** Parse date in RFC-1123 format.
1195 * According to RFC 1123 we must accept dates in the following
1198 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1199 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1200 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1202 * (Though we're only allowed to generate dates in the first format.)
1204 function ParseRfc1123DateTime ($timestr) {
1205 $timestr = trim($timestr);
1206 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1207 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1209 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1211 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1212 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1214 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1215 if ($year < 70) $year += 2000;
1216 elseif ($year < 100) $year += 1900;
1218 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1219 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1221 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1228 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1230 return false; // failed
1235 * Format time to standard 'ctime' format.
1237 * @param $time time_t Time. Default: now.
1238 * @return string Date and time.
1240 function CTime ($time = false)
1242 if ($time === false)
1244 return date("D M j H:i:s Y", $time);
1249 * Format number as kilobytes or bytes.
1250 * Short format is used for PageList
1251 * Long format is used in PageInfo
1253 * @param $bytes int. Default: 0.
1254 * @param $longformat bool. Default: false.
1255 * @return class FormattedText (XmlElement.php).
1257 function ByteFormatter ($bytes = 0, $longformat = false) {
1260 if ($bytes < 1024) {
1262 $size = fmt("%s b", $bytes);
1264 $size = fmt("%s bytes", $bytes);
1267 $kb = round($bytes / 1024, 1);
1269 $size = fmt("%s k", $kb);
1271 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1277 * Internationalized printf.
1279 * This is essentially the same as PHP's built-in printf
1280 * with the following exceptions:
1282 * <li> It passes the format string through gettext().
1283 * <li> It supports the argument reordering extensions.
1290 * __printf("Differences between versions %s and %s of %s",
1291 * $new_link, $old_link, $page_link);
1294 * Then in locale/po/de.po, one can reorder the printf arguments:
1297 * msgid "Differences between %s and %s of %s."
1298 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1301 * (Note that while PHP tries to expand $vars within double-quotes,
1302 * the values in msgstr undergo no such expansion, so the '$'s
1305 * One shouldn't use reordered arguments in the default format string.
1306 * Backslashes in the default string would be necessary to escape the
1307 * '$'s, and they'll cause all kinds of trouble....
1309 function __printf ($fmt) {
1310 $args = func_get_args();
1312 echo __vsprintf($fmt, $args);
1316 * Internationalized sprintf.
1318 * This is essentially the same as PHP's built-in printf with the
1319 * following exceptions:
1322 * <li> It passes the format string through gettext().
1323 * <li> It supports the argument reordering extensions.
1328 function __sprintf ($fmt) {
1329 $args = func_get_args();
1331 return __vsprintf($fmt, $args);
1335 * Internationalized vsprintf.
1337 * This is essentially the same as PHP's built-in printf with the
1338 * following exceptions:
1341 * <li> It passes the format string through gettext().
1342 * <li> It supports the argument reordering extensions.
1347 function __vsprintf ($fmt, $args) {
1348 $fmt = gettext($fmt);
1349 // PHP's sprintf doesn't support variable with specifiers,
1350 // like sprintf("%*s", 10, "x"); --- so we won't either.
1352 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1353 // Format string has '%2$s' style argument reordering.
1354 // PHP doesn't support this.
1355 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1356 // literal variable name substitution only to keep locale
1357 // strings uncluttered
1358 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1359 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1361 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1364 // Reorder arguments appropriately.
1365 foreach($m[1] as $argnum) {
1366 if ($argnum < 1 || $argnum > count($args))
1367 trigger_error(sprintf(_("%s: argument index out of range"),
1368 $argnum), E_USER_WARNING);
1369 $newargs[] = $args[$argnum - 1];
1374 // Not all PHP's have vsprintf, so...
1375 array_unshift($args, $fmt);
1376 return call_user_func_array('sprintf', $args);
1379 function file_mtime ($filename) {
1380 if ($stat = @stat($filename))
1386 function sort_file_mtime ($a, $b) {
1387 $ma = file_mtime($a);
1388 $mb = file_mtime($b);
1389 if (!$ma or !$mb or $ma == $mb) return 0;
1390 return ($ma > $mb) ? -1 : 1;
1395 * Build an array in $this->_fileList of files from $dirname.
1396 * Subdirectories are not traversed.
1398 * (This was a function LoadDir in lib/loadsave.php)
1399 * See also http://www.php.net/manual/en/function.readdir.php
1401 function getFiles($exclude='', $sortby='', $limit='') {
1402 $list = $this->_fileList;
1405 require_once('lib/PageList.php');
1406 switch (Pagelist::sortby($sortby, 'db')) {
1407 case 'pagename ASC': break;
1408 case 'pagename DESC':
1409 $list = array_reverse($list);
1412 usort($list,'sort_file_mtime');
1415 usort($list,'sort_file_mtime');
1416 $list = array_reverse($list);
1421 return array_splice($list, 0, $limit);
1425 function _filenameSelector($filename) {
1426 if (! $this->_pattern )
1429 if (! $this->_pcre_pattern )
1430 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1431 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1436 function fileSet($directory, $filepattern = false) {
1437 $this->_fileList = array();
1438 $this->_pattern = $filepattern;
1440 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1441 $this->_case = !isWindows();
1442 $this->_pathsep = '/';
1444 if (empty($directory)) {
1445 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1447 return; // early return
1450 @ $dir_handle = opendir($dir=$directory);
1451 if (empty($dir_handle)) {
1452 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1453 $dir), E_USER_NOTICE);
1454 return; // early return
1457 while ($filename = readdir($dir_handle)) {
1458 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1460 if ($this->_filenameSelector($filename)) {
1461 array_push($this->_fileList, "$filename");
1462 //trigger_error(sprintf(_("found file %s"), $filename),
1463 // E_USER_NOTICE); //debugging
1466 closedir($dir_handle);
1472 // expands a list containing regex's to its matching entries
1473 class ListRegexExpand {
1474 //var $match, $list, $index, $case_sensitive;
1475 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1476 $this->match = $match;
1477 $this->list = &$list;
1478 $this->case_sensitive = $case_sensitive;
1479 //$this->index = false;
1481 function listMatchCallback ($item, $key) {
1482 $quoted = str_replace('/','\/',$item);
1483 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1485 unset($this->list[$this->index]);
1486 $this->list[] = $item;
1489 function expandRegex ($index, &$pages) {
1490 $this->index = $index;
1491 array_walk($pages, array($this, 'listMatchCallback'));
1496 // Convert fileglob to regex style:
1497 // Convert some wildcards to pcre style, escape the rest
1498 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1499 // Fixed bug #994994: "/" in $glob.
1500 function glob_to_pcre ($glob) {
1501 // check simple case: no need to escape
1502 $escape = '\[](){}=!<>|:/';
1503 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1505 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1506 $glob = strtr($glob, "\\", "\xff");
1507 $glob = str_replace("/", "\\/", $glob);
1508 // first convert some unescaped expressions to pcre style: . => \.
1510 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1511 "\\1\xff\\2", $glob);
1514 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1515 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1516 if (!preg_match('/^[\?\*]/', $glob))
1518 if (!preg_match('/[\?\*]$/', $glob))
1521 // .*? handled above, now escape the rest
1522 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1523 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1525 return strtr($re, "\xff", "");
1528 function glob_match ($glob, $against, $case_sensitive = true) {
1529 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1533 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1534 $list = explode(',',$input);
1535 // expand wildcards from list of $allnames
1536 if (preg_match('/[\?\*]/',$input)) {
1537 // Optimizing loop invariants:
1538 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1539 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1541 if (preg_match('/[\?\*]/',$f)) {
1543 $expand = new ListRegexExpand($list,
1544 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1545 $expand->expandRegex($i, $allnames);
1552 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1553 function explodePageList($input, $include_empty=false, $sortby='pagename',
1554 $limit='', $exclude='') {
1555 include_once("lib/PageList.php");
1556 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1559 // Class introspections
1562 * Determine whether object is of a specified type.
1563 * In PHP builtin since 4.2.0 as is_a()
1564 * is_a() deprecated in PHP 5, in favor of instanceof operator
1566 * @param $object object An object.
1567 * @param $class string Class name.
1568 * @return bool True iff $object is a $class
1569 * or a sub-type of $class.
1571 function isa ($object, $class) {
1572 //if (check_php_version(5))
1573 // return $object instanceof $class;
1574 if (check_php_version(4,2) and !check_php_version(5))
1575 return is_a($object, $class);
1577 $lclass = check_php_version(5) ? $class : strtolower($class);
1578 return is_object($object)
1579 && ( strtolower(get_class($object)) == strtolower($class)
1580 || is_subclass_of($object, $lclass) );
1583 /** Determine whether (possible) object has method.
1585 * @param $object mixed Object
1586 * @param $method string Method name
1587 * @return bool True iff $object is an object with has method $method.
1589 function can ($object, $method) {
1590 return is_object($object) && method_exists($object, strtolower($method));
1593 /** Determine whether a function is okay to use.
1595 * Some providers (e.g. Lycos) disable some of PHP functions for
1596 * "security reasons." This makes those functions, of course,
1597 * unusable, despite the fact the function_exists() says they
1600 * This function test to see if a function exists and is not
1601 * disallowed by PHP's disable_functions config setting.
1603 * @param string $function_name Function name
1604 * @return bool True iff function can be used.
1606 function function_usable($function_name) {
1608 if (!is_array($disabled)) {
1609 $disabled = array();
1610 // Use get_cfg_var since ini_get() is one of the disabled functions
1611 // (on Lycos, at least.)
1612 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1613 foreach ($split as $f)
1614 $disabled[strtolower($f)] = true;
1617 return ( function_exists($function_name)
1618 and ! isset($disabled[strtolower($function_name)])
1625 * This is used for generating ETags.
1627 function wikihash ($x) {
1628 if (is_scalar($x)) {
1631 elseif (is_array($x)) {
1633 return md5(serialize($x));
1635 elseif (is_object($x)) {
1638 trigger_error("Can't hash $x", E_USER_ERROR);
1643 * Seed the random number generator.
1645 * better_srand() ensures the randomizer is seeded only once.
1647 * How random do you want it? See:
1648 * http://www.php.net/manual/en/function.srand.php
1649 * http://www.php.net/manual/en/function.mt-srand.php
1651 function better_srand($seed = '') {
1652 static $wascalled = FALSE;
1654 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1655 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1657 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1661 function rand_ascii($length = 1) {
1664 for ($i = 1; $i <= $length; $i++) {
1665 // return only typeable 7 bit ascii, avoid quotes
1666 if (function_exists('mt_rand'))
1667 $s .= chr(mt_rand(40, 126));
1669 // the usually bad glibc srand()
1670 $s .= chr(rand(40, 126));
1675 /* by Dan Frankowski.
1677 function rand_ascii_readable ($length = 6) {
1678 // Pick a few random letters or numbers
1681 // Don't use 1lI0O, because they're hard to read
1682 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1683 $letter_len = strlen($letters);
1684 for ($i=0; $i < $length; $i++) {
1685 if (function_exists('mt_rand'))
1686 $word .= $letters[mt_rand(0, $letter_len-1)];
1688 $word .= $letters[rand(0, $letter_len-1)];
1694 * Recursively count all non-empty elements
1695 * in array of any dimension or mixed - i.e.
1696 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1697 * See http://www.php.net/manual/en/function.count.php
1699 function count_all($arg) {
1700 // skip if argument is empty
1702 //print_r($arg); //debugging
1704 // not an array, return 1 (base case)
1707 // else call recursively for all elements $arg
1708 foreach($arg as $key => $val)
1709 $count += count_all($val);
1714 function isSubPage($pagename) {
1715 return (strstr($pagename, SUBPAGE_SEPARATOR));
1718 function subPageSlice($pagename, $pos) {
1719 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1720 $pages = array_slice($pages,$pos,1);
1727 * Class for "popping up" and alert box. (Except that right now, it doesn't
1731 * This is a hackish and needs to be refactored. However it would be nice to
1732 * unify all the different methods we use for showing Alerts and Dialogs.
1733 * (E.g. "Page deleted", login form, ...)
1738 * @param object $request
1739 * @param mixed $head Header ("title") for alert box.
1740 * @param mixed $body The text in the alert box.
1741 * @param hash $buttons An array mapping button labels to URLs.
1742 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1744 function Alert($head, $body, $buttons=false) {
1745 if ($buttons === false)
1748 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1749 $this->_buttons = $buttons;
1753 * Show the alert box.
1758 $tokens = $this->_tokens;
1759 $tokens['BUTTONS'] = $this->_getButtons();
1761 $request->discardOutput();
1762 $tmpl = new Template('dialog', $request, $tokens);
1768 function _getButtons() {
1771 $buttons = $this->_buttons;
1773 $buttons = array(_("Okay") => $request->getURLtoSelf());
1776 foreach ($buttons as $label => $url)
1777 print "$label $url\n";
1778 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1779 return new XmlContent($out);
1784 // 1.3.9-p1 => 1030.091
1785 // 1.3.10pre => 1030.099
1786 // 1.3.11pre-20041120 => 1030.1120041120
1787 // 1.3.12-rc1 => 1030.119
1788 function phpwiki_version() {
1789 static $PHPWIKI_VERSION;
1790 if (!isset($PHPWIKI_VERSION)) {
1791 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1792 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1793 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1794 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1795 $PHPWIKI_VERSION -= 0.01;
1797 return $PHPWIKI_VERSION;
1800 function phpwiki_gzhandler($ob) {
1801 if (function_exists('gzencode'))
1802 $ob = gzencode($ob);
1803 $GLOBALS['request']->_ob_get_length = strlen($ob);
1804 if (!headers_sent()) {
1805 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1810 function isWikiWord($word) {
1811 global $WikiNameRegexp;
1812 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1813 return preg_match("/^$WikiNameRegexp\$/",$word);
1816 // needed to store serialized objects-values only (perm, pref)
1817 function obj2hash ($obj, $exclude = false, $fields = false) {
1819 if (! $fields ) $fields = get_object_vars($obj);
1820 foreach ($fields as $key => $val) {
1821 if (is_array($exclude)) {
1822 if (in_array($key, $exclude)) continue;
1830 * isUtf8String($string) - cheap utf-8 detection
1832 * segfaults for strings longer than 10kb!
1833 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1834 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1836 function isUtf8String( $s ) {
1837 $ptrASCII = '[\x00-\x7F]';
1838 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1839 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1840 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1841 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1842 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1843 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1847 * Check for UTF-8 URLs; Internet Explorer produces these if you
1848 * type non-ASCII chars in the URL bar or follow unescaped links.
1849 * Requires urldecoded pagename.
1850 * Fixes sf.net bug #953949
1852 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1854 function fixTitleEncoding( $s ) {
1859 if (empty($s)) return $s;
1861 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1863 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1864 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1866 $isutf = ($ishigh ? isUtf8String($s) : true);
1867 $locharset = strtolower($charset);
1869 if( $locharset != "utf-8" and $ishigh and $isutf )
1870 $s = charset_convert('UTF-8', $locharset, $s);
1871 if ($locharset == "utf-8" and $ishigh and !$isutf )
1872 return utf8_encode( $s );
1874 // Other languages can safely leave this function, or replace
1875 // it with one to detect and convert another legacy encoding.
1880 * MySQL fulltext index doesn't grok utf-8, so we
1881 * need to fold cases and convert to hex.
1882 * src: languages/Language.php:stripForSearch() from mediawiki
1885 function stripForSearch( $string ) {
1886 global $wikiLowerChars;
1887 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1888 return preg_replace(
1889 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1890 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1896 * Workaround for allow_url_fopen, to get the content of an external URI.
1897 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1898 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1900 function url_get_contents( $uri ) {
1901 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1902 return @file_get_contents($uri);
1904 require_once("lib/HttpClient.php");
1905 $bits = parse_url($uri);
1906 $host = $bits['host'];
1907 $port = isset($bits['port']) ? $bits['port'] : 80;
1908 $path = isset($bits['path']) ? $bits['path'] : '/';
1909 if (isset($bits['query'])) {
1910 $path .= '?'.$bits['query'];
1912 $client = new HttpClient($host, $port);
1913 $client->use_gzip = false;
1914 if (!$client->get($path)) {
1917 return $client->getContent();
1923 * Generate consecutively named strings:
1924 * Name, Name2, Name3, ...
1926 function GenerateId($name) {
1927 static $ids = array();
1928 if (empty($ids[$name])) {
1933 return $name . $ids[$name];
1937 // from IncludePage. To be of general use.
1938 // content: string or array of strings
1939 function firstNWordsOfContent( $n, $content ) {
1940 if ($content and $n > 0) {
1941 if (is_array($content)) {
1942 // fixme: return a list of lines then?
1943 //$content = join("\n", $content);
1944 //$return_array = true;
1946 foreach ($content as $line) {
1947 $words = explode(' ', $line);
1948 if ($wordcount + count($words) > $n) {
1949 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1950 . sprintf(_("... (first %s words)"), $n);
1953 $wordcount += count($words);
1959 // fixme: use better whitespace/word seperators
1960 $words = explode(' ', $content);
1961 if (count($words) > $n) {
1962 return join(' ', array_slice($words, 0, $n))
1963 . sprintf(_("... (first %s words)"), $n);
1973 // moved from lib/plugin/IncludePage.php
1974 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1975 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1977 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
1978 . " \\s*$\\n?" // possible blank lines
1979 . " ( (?: ^.*\\n? )*? )" // some lines
1980 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1981 implode("\n", $content),
1983 // Strip trailing blanks lines and ---- <hr>s
1984 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1986 $text = $match[1] . $section ."\n". $text;
1987 return explode("\n", $text);
1990 $mesg = $page ." ". $section;
1993 return array(sprintf(_("<%s: no such section>"), $mesg));
1996 // use this faster version: only load ExternalReferrer if we came from an external referrer
1997 function isExternalReferrer(&$request) {
1998 if ($referrer = $request->get('HTTP_REFERER')) {
1999 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2000 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2001 require_once("lib/ExternalReferrer.php");
2002 $se = new SearchEngines();
2003 return $se->parseSearchQuery($referrer);
2005 //if (DEBUG) return array('query' => 'wiki');
2010 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2012 function loadPhpExtension($extension) {
2013 if (!extension_loaded($extension)) {
2014 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2015 $soname = ($isWindows ? 'php_' : '')
2017 . ($isWindows ? '.dll' : '.so');
2021 return extension_loaded($extension);
2024 function charset_convert($from, $to, $data) {
2026 //$wikicharset = strtolower($CHARSET);
2027 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2028 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2029 return utf8_decode($data);
2030 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2031 return utf8_encode($data);
2033 if (loadPhpExtension("iconv")) {
2034 $tmpdata = iconv($from, $to, $data);
2036 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2040 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2045 function string_starts_with($string, $prefix) {
2046 return (substr($string, 0, strlen($prefix)) == $prefix);
2048 function string_ends_with($string, $suffix) {
2049 return (substr($string, -strlen($suffix)) == $suffix);
2051 function array_remove($arr,$value) {
2052 return array_values(array_diff($arr,array($value)));
2056 * Ensure that the script will have another $secs time left.
2057 * Works only if safe_mode is off.
2058 * For example not to timeout on waiting socket connections.
2059 * Use the socket timeout as arg.
2061 function longer_timeout($secs = 30) {
2062 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2063 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2064 if ($timeleft < $secs)
2065 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2068 function printSimpleTrace($bt) {
2070 echo "\nTraceback:\n";
2071 if (function_exists('debug_print_backtrace')) { // >= 5
2072 debug_print_backtrace();
2074 foreach ($bt as $i => $elem) {
2075 if (!array_key_exists('file', $elem)) {
2078 //echo join(" ",array_values($elem)),"\n";
2079 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2085 * Return the used process memory, in bytes.
2086 * Enable the section which will work for you. They are very slow.
2087 * Special quirks for Windows: Requires cygwin.
2089 function getMemoryUsage() {
2090 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2091 if (function_exists('memory_get_usage') and memory_get_usage()) {
2092 return memory_get_usage();
2093 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2094 $mem = $u['ru_maxrss'];
2095 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2096 // what we want is the process memory only: apache or php (if CGI)
2099 // win32_ps_stat_proc, win32_ps_stat_mem
2100 if (function_exists('win32_ps_list_procs')) {
2101 $info = win32_ps_stat_proc($pid);
2102 $memstr = $info['mem']['working_set_size'];
2104 // This works only if it's a cygwin process (apache or php).
2105 // Requires a newer cygwin
2106 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2108 // if it's native windows use something like this:
2109 // (requires pslist from sysinternals.com, grep, sed and perl)
2110 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2112 return (integer) trim($memstr);
2115 //%MEM: Percentage of total memory in use by this process
2116 //VSZ: Total virtual memory size, in 1K blocks.
2117 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2118 //CPU time used by process since it started.
2119 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2120 $memstr = exec("ps -orss -p $pid|sed 1d");
2121 return (integer) trim($memstr);
2126 * @param var $needle
2127 * @param array $haystack one-dimensional numeric array only, no hash
2129 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2130 It will return false if not found or the index where it was found.
2131 From dennis.decoene@moveit.be http://www.php.net/array_search
2133 function binary_search($needle, $haystack) {
2134 $high = count($haystack);
2137 while (($high - $low) > 1) {
2138 $probe = floor(($high + $low) / 2);
2139 if ($haystack[$probe] < $needle) {
2141 } elseif ($haystack[$probe] == $needle) {
2142 $high = $low = $probe;
2148 if ($high == count($haystack) || $haystack[$high] != $needle) {
2155 // $Log: not supported by cvs2svn $
2156 // Revision 1.264 2007/07/15 17:39:42 rurban
2157 // add binary_search. enable memory ps calls
2159 // Revision 1.263 2007/07/14 12:05:29 rurban
2160 // add url field to WikiPageName for interwiki expansion
2162 // Revision 1.262 2007/06/07 17:02:01 rurban
2163 // fix display of pagenames containing ":" in certain lists
2165 // Revision 1.261 2007/06/01 06:37:53 rurban
2166 // use native debug_print_backtrace
2168 // Revision 1.260 2007/02/17 14:15:21 rurban
2169 // fix ImgLink params: $ori_url
2171 // Revision 1.259 2007/01/20 11:41:38 rurban
2172 // WikiPagename::_check: add flatfile support
2174 // Revision 1.258 2007/01/07 18:43:51 rurban
2175 // Remove FileFinder dependency for loadPhpExtension()
2177 // Revision 1.257 2007/01/03 21:24:56 rurban
2178 // Disable noisy ps subprocess on DEBUG. Turn it on explicitly on memory debugging. Add convert_charset helper. Use convert_charset().
2180 // Revision 1.256 2007/01/02 13:23:49 rurban
2181 // ftnt_${footnum}: do not confuse old php string definition parsers. Clarify API: sortby,limit and exclude are strings.
2183 // Revision 1.255 2006/12/22 16:53:38 rurban
2184 // Try to dl() load the iconv extension, if not already loaded
2186 // Revision 1.254 2006/12/02 19:53:05 rurban
2187 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2188 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2191 // Revision 1.253 2006/08/25 22:20:52 rurban
2192 // better split subpages at sep
2194 // Revision 1.252 2006/06/18 11:03:36 rurban
2195 // support rc version
2197 // Revision 1.251 2006/03/19 15:01:00 rurban
2198 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2200 // Revision 1.250 2006/03/07 20:45:44 rurban
2201 // wikihash for php-5.1
2203 // Revision 1.249 2005/10/30 14:24:33 rurban
2204 // move rand_ascii_readable from Captcha to stdlib
2206 // Revision 1.248 2005/10/29 14:18:30 uckelman
2207 // Added is_a() deprecation note.
2209 // Revision 1.247 2005/10/10 20:31:21 rurban
2212 // Revision 1.246 2005/10/10 19:38:48 rurban
2215 // Revision 1.245 2005/09/18 16:01:09 rurban
2216 // trick to send the correct gzipped Content-Length
2218 // Revision 1.244 2005/09/11 13:24:33 rurban
2219 // fix shortname, dont quote twice in ListRegexExpand
2221 // Revision 1.243 2005/08/06 15:01:38 rurban
2222 // workaround php VBASIC alike limitation: allow integer pagenames
2224 // Revision 1.242 2005/08/06 13:07:04 rurban
2225 // quote paths correctly (not the best method though)
2227 // Revision 1.241 2005/05/06 16:54:19 rurban
2228 // support optional EXTERNAL_LINK_TARGET, default: _blank
2230 // Revision 1.240 2005/04/23 11:15:49 rurban
2231 // handle allowed inlined objects within INLINE_IMAGES
2233 // Revision 1.239 2005/04/01 16:11:42 rurban
2236 // Revision 1.238 2005/03/04 16:29:14 rurban
2237 // Fixed bug #994994 (escape / in glob)
2238 // Optimized glob_to_pcre within fileSet() matching.
2240 // Revision 1.237 2005/02/12 17:22:18 rurban
2241 // locale update: missing . : fixed. unified strings
2242 // proper linebreaks
2244 // Revision 1.236 2005/02/08 13:41:32 rurban
2247 // Revision 1.235 2005/02/04 11:54:48 rurban
2250 // Revision 1.234 2005/02/03 05:09:25 rurban
2251 // Talk: + User: fix
2253 // Revision 1.233 2005/02/02 20:40:12 rurban
2254 // fix Talk: and User: names and links
2256 // Revision 1.232 2005/02/02 19:34:09 rurban
2257 // more maps: Talk, User
2259 // Revision 1.231 2005/01/30 19:48:52 rurban
2260 // enable ps memory on unix
2262 // Revision 1.230 2005/01/25 07:10:51 rurban
2263 // add getMemoryUsage to stdlib
2265 // Revision 1.229 2005/01/21 11:51:22 rurban
2268 // Revision 1.228 2005/01/17 20:28:30 rurban
2269 // Allow more pagename chars: Limit only on certain backends.
2270 // Re-Allow : and ; and control chars on non-file backends.
2272 // Revision 1.227 2005/01/14 18:32:08 uckelman
2273 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2274 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2275 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2276 // conversion of '__' into '<strong>', and then unhidden afterwards.
2278 // Revision 1.226 2004/12/26 17:12:06 rurban
2279 // avoid stdargs in url, php5 fixes
2281 // Revision 1.225 2004/12/22 19:02:29 rurban
2282 // fix glob for starting * or ?
2284 // Revision 1.224 2004/12/20 12:11:50 rurban
2285 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2286 // not reproducable other than on sf.net, but this seems to fix it.
2288 // Revision 1.223 2004/12/18 16:49:29 rurban
2289 // fix RPC for !USE_PATH_INFO, add debugging helper
2291 // Revision 1.222 2004/12/17 16:40:45 rurban
2292 // add not yet used url helper
2294 // Revision 1.221 2004/12/06 19:49:58 rurban
2295 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2296 // renamed delete_page to purge_page.
2297 // enable action=edit&version=-1 to force creation of a new version.
2298 // added BABYCART_PATH config
2299 // fixed magiqc in adodb.inc.php
2300 // and some more docs
2302 // Revision 1.220 2004/11/30 17:47:41 rurban
2303 // added mt_srand, check for native isa
2305 // Revision 1.219 2004/11/26 18:39:02 rurban
2306 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2308 // Revision 1.218 2004/11/25 08:28:48 rurban
2311 // Revision 1.217 2004/11/16 17:31:03 rurban
2312 // re-enable old block markup conversion
2314 // Revision 1.216 2004/11/11 18:31:26 rurban
2315 // add simple backtrace on such general failures to get at least an idea where
2317 // Revision 1.215 2004/11/11 14:34:12 rurban
2318 // minor clarifications
2320 // Revision 1.214 2004/11/11 11:01:20 rurban
2321 // fix loadPhpExtension
2323 // Revision 1.213 2004/11/01 10:43:57 rurban
2324 // seperate PassUser methods into seperate dir (memory usage)
2325 // fix WikiUser (old) overlarge data session
2326 // remove wikidb arg from various page class methods, use global ->_dbi instead
2329 // Revision 1.212 2004/10/22 09:15:39 rurban
2330 // Alert::show has no arg anymore
2332 // Revision 1.211 2004/10/22 09:05:11 rurban
2333 // added longer_timeout (HttpClient)
2336 // Revision 1.210 2004/10/14 21:06:02 rurban
2337 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2339 // Revision 1.209 2004/10/14 19:19:34 rurban
2340 // loadsave: check if the dumped file will be accessible from outside.
2341 // and some other minor fixes. (cvsclient native not yet ready)
2343 // Revision 1.208 2004/10/12 13:13:20 rurban
2344 // php5 compatibility (5.0.1 ok)
2346 // Revision 1.207 2004/09/26 12:21:40 rurban
2347 // removed old log entries.
2348 // added persistent start_debug on internal links and DEBUG
2349 // added isExternalReferrer (not yet used)
2351 // Revision 1.206 2004/09/25 16:28:36 rurban
2352 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2354 // Revision 1.205 2004/09/23 13:59:35 rurban
2355 // Before removing a page display a sample of 100 words.
2357 // Revision 1.204 2004/09/17 13:19:15 rurban
2358 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2361 // Revision 1.203 2004/09/16 08:00:52 rurban
2362 // just some comments
2364 // Revision 1.202 2004/09/14 10:11:44 rurban
2365 // start 2nd Id with ...Plugin2
2367 // Revision 1.201 2004/09/14 10:06:42 rurban
2368 // generate iterated plugin ids, set plugin span id also
2370 // Revision 1.200 2004/08/05 17:34:26 rurban
2371 // move require to sortby branch
2373 // Revision 1.199 2004/08/05 10:38:15 rurban
2374 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
2377 // Revision 1.198 2004/07/02 10:30:36 rurban
2378 // always disable getimagesize for < php-4.3 with external png's
2380 // Revision 1.197 2004/07/02 09:55:58 rurban
2381 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2383 // Revision 1.196 2004/07/01 08:51:22 rurban
2384 // dumphtml: added exclude, print pagename before processing
2386 // Revision 1.195 2004/06/29 08:52:22 rurban
2387 // Use ...version() $need_content argument in WikiDB also:
2388 // To reduce the memory footprint for larger sets of pagelists,
2389 // we don't cache the content (only true or false) and
2390 // we purge the pagedata (_cached_html) also.
2391 // _cached_html is only cached for the current pagename.
2392 // => Vastly improved page existance check, ACL check, ...
2394 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2396 // Revision 1.194 2004/06/29 06:48:04 rurban
2397 // Improve LDAP auth and GROUP_LDAP membership:
2398 // no error message on false password,
2399 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2400 // fixed two group queries (this -> user)
2401 // stdlib: ConvertOldMarkup still flawed
2403 // Revision 1.193 2004/06/28 13:27:03 rurban
2404 // CreateToc disabled for old markup and Apache2 only
2406 // Revision 1.192 2004/06/28 12:47:43 rurban
2407 // skip if non-DEBUG and old markup with CreateToc
2409 // Revision 1.191 2004/06/25 14:31:56 rurban
2410 // avoid debug_skip warning
2412 // Revision 1.190 2004/06/25 14:29:20 rurban
2413 // WikiGroup refactoring:
2414 // global group attached to user, code for not_current user.
2415 // improved helpers for special groups (avoid double invocations)
2416 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2417 // fixed a XHTML validation error on userprefs.tmpl
2419 // Revision 1.189 2004/06/20 09:45:35 rurban
2420 // php5 isa fix (wrong strtolower)
2422 // Revision 1.188 2004/06/16 10:38:58 rurban
2423 // Disallow refernces in calls if the declaration is a reference
2424 // ("allow_call_time_pass_reference clean").
2425 // PhpWiki is now allow_call_time_pass_reference = Off clean,
2426 // but several external libraries may not.
2427 // In detail these libs look to be affected (not tested):
2431 // Revision 1.187 2004/06/14 11:31:37 rurban
2432 // renamed global $Theme to $WikiTheme (gforge nameclash)
2433 // inherit PageList default options from PageList
2434 // default sortby=pagename
2435 // use options in PageList_Selectable (limit, sortby, ...)
2436 // added action revert, with button at action=diff
2437 // added option regex to WikiAdminSearchReplace
2439 // Revision 1.186 2004/06/13 13:54:25 rurban
2440 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2441 // FoafViewer: Check against external requirements, instead of fatal.
2442 // Change output for xhtmldumps: using file:// urls to the local fs.
2443 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2444 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2446 // Revision 1.185 2004/06/11 09:07:30 rurban
2447 // support theme-specific LinkIconAttr: front or after or none
2449 // Revision 1.184 2004/06/04 20:32:53 rurban
2450 // Several locale related improvements suggested by Pierrick Meignen
2451 // LDAP fix by John Cole
2452 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2454 // Revision 1.183 2004/06/01 10:22:56 rurban
2455 // added url_get_contents() used in XmlParser and elsewhere
2457 // Revision 1.182 2004/05/25 12:40:48 rurban
2458 // trim the pagename
2460 // Revision 1.181 2004/05/25 10:18:44 rurban
2461 // Check for UTF-8 URLs; Internet Explorer produces these if you
2462 // type non-ASCII chars in the URL bar or follow unescaped links.
2463 // Fixes sf.net bug #953949
2464 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2466 // Revision 1.180 2004/05/18 16:23:39 rurban
2467 // rename split_pagename to SplitPagename
2469 // Revision 1.179 2004/05/18 16:18:37 rurban
2470 // AutoSplit at subpage seperators
2471 // RssFeed stability fix for empty feeds or broken connections
2473 // Revision 1.178 2004/05/12 10:49:55 rurban
2474 // require_once fix for those libs which are loaded before FileFinder and
2475 // its automatic include_path fix, and where require_once doesn't grok
2476 // dirname(__FILE__) != './lib'
2477 // upgrade fix with PearDB
2478 // navbar.tmpl: remove spaces for IE button alignment
2480 // Revision 1.177 2004/05/08 14:06:12 rurban
2481 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2482 // minor stability and portability fixes
2484 // Revision 1.176 2004/05/08 11:25:15 rurban
2487 // Revision 1.175 2004/05/06 17:30:38 rurban
2488 // CategoryGroup: oops, dos2unix eol
2489 // improved phpwiki_version:
2490 // pre -= .0001 (1.3.10pre: 1030.099)
2491 // -p1 += .001 (1.3.9-p1: 1030.091)
2492 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2493 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2494 // backend->backendType(), backend->database(),
2495 // backend->listOfFields(),
2496 // backend->listOfTables(),
2498 // Revision 1.174 2004/05/06 12:02:05 rurban
2499 // fix sf.net bug#949002: [ Link | ] assertion
2501 // Revision 1.173 2004/05/03 15:00:31 rurban
2502 // added more database upgrading: session.sess_ip, page.id autp_increment
2504 // Revision 1.172 2004/04/26 20:44:34 rurban
2505 // locking table specific for better databases
2507 // Revision 1.171 2004/04/19 23:13:03 zorloc
2508 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
2510 // Revision 1.170 2004/04/19 18:27:45 rurban
2511 // Prevent from some PHP5 warnings (ref args, no :: object init)
2512 // php5 runs now through, just one wrong XmlElement object init missing
2513 // Removed unneccesary UpgradeUser lines
2514 // Changed WikiLink to omit version if current (RecentChanges)
2516 // Revision 1.169 2004/04/15 21:29:48 rurban
2517 // allow [0] with new markup: link to page "0"
2519 // Revision 1.168 2004/04/10 02:30:49 rurban
2520 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2521 // Fixed "cannot setlocale..." (sf.net problem)
2523 // Revision 1.167 2004/04/02 15:06:55 rurban
2524 // fixed a nasty ADODB_mysql session update bug
2525 // improved UserPreferences layout (tabled hints)
2526 // fixed UserPreferences auth handling
2527 // improved auth stability
2528 // improved old cookie handling: fixed deletion of old cookies with paths
2530 // Revision 1.166 2004/04/01 15:57:10 rurban
2531 // simplified Sidebar theme: table, not absolute css positioning
2532 // added the new box methods.
2533 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2535 // Revision 1.165 2004/03/24 19:39:03 rurban
2536 // php5 workaround code (plus some interim debugging code in XmlElement)
2537 // php5 doesn't work yet with the current XmlElement class constructors,
2538 // WikiUserNew does work better than php4.
2539 // rewrote WikiUserNew user upgrading to ease php5 update
2540 // fixed pref handling in WikiUserNew
2541 // added Email Notification
2542 // added simple Email verification
2543 // removed emailVerify userpref subclass: just a email property
2544 // changed pref binary storage layout: numarray => hash of non default values
2545 // print optimize message only if really done.
2546 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2547 // prefs should be stored in db or homepage, besides the current session.
2549 // Revision 1.164 2004/03/18 21:41:09 rurban
2550 // fixed sqlite support
2551 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2553 // Revision 1.163 2004/03/17 18:41:49 rurban
2554 // just reformatting
2556 // Revision 1.162 2004/03/16 15:43:08 rurban
2557 // make fileSet sortable to please PageList
2559 // Revision 1.161 2004/03/12 15:48:07 rurban
2560 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2561 // simplified lib/stdlib.php:explodePageList
2563 // Revision 1.160 2004/02/28 21:14:08 rurban
2564 // generally more PHPDOC docs
2565 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2566 // fxied WikiUserNew pref handling: empty theme not stored, save only
2567 // changed prefs, sql prefs improved, fixed password update,
2568 // removed REPLACE sql (dangerous)
2569 // moved gettext init after the locale was guessed
2570 // + some minor changes
2573 // (c-file-style: "gnu")
2577 // c-basic-offset: 4
2578 // c-hanging-comment-ender-p: nil
2579 // indent-tabs-mode: nil