1 <?php //rcs_id('$Id: stdlib.php,v 1.268 2007-09-15 12:28:46 rurban Exp $');
3 Copyright 1999-2007 $ThePhpWikiProgrammingTeam
5 This file is part of PhpWiki.
7 PhpWiki is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 PhpWiki is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with PhpWiki; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 Standard functions for Wiki functionality
24 WikiURL ($pagename, $args, $get_abs_url)
26 IconForLink ($protocol_or_url)
27 PossiblyGlueIconToText($proto_or_url, $text)
29 LinkURL ($url, $linktext)
30 LinkImage ($url, $alt)
32 SplitQueryArgs ($query_args)
33 LinkPhpwikiURL ($url, $text, $basepage)
34 ConvertOldMarkup ($content, $markup_type = "block")
35 MangleXmlIdentifier($str)
36 UnMangleXmlIdentifier($str)
38 class Stack { push($item), pop(), cnt(), top() }
39 class Alert { show() }
40 class WikiPageName {getParent(),isValid(),getWarnings() }
42 expand_tabs($str, $tab_width = 8)
44 NoSuchRevision ($request, $page, $version)
45 TimezoneOffset ($time, $no_colon)
46 Iso8601DateTime ($time)
47 Rfc2822DateTime ($time)
48 ParseRfc1123DateTime ($timestr)
50 ByteFormatter ($bytes = 0, $longformat = false)
53 __vsprintf ($fmt, $args)
55 file_mtime ($filename)
56 sort_file_mtime ($a, $b)
57 class fileSet {fileSet($directory, $filepattern = false),
58 getFiles($exclude='', $sortby='', $limit='') }
59 class ListRegexExpand { listMatchCallback($item, $key),
60 expandRegex ($index, &$pages) }
63 glob_match ($glob, $against, $case_sensitive = true)
64 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
65 explodePageList ($input, $perm = false)
67 can ($object, $method)
68 function_usable ($function_name)
70 better_srand ($seed = '')
73 subPageSlice ($pagename, $pos)
77 obj2hash ($obj, $exclude = false, $fields = false)
80 url_get_contents ($uri)
82 firstNWordsOfContent ($n, $content)
83 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
86 charset_convert($from, $to, $data)
88 function: LinkInterWikiLink($link, $linktext)
89 moved to: lib/interwiki.php
90 function: linkExistingWikiWord($wikiword, $linktext, $version)
91 moved to: lib/Theme.php
92 function: LinkUnknownWikiWord($wikiword, $linktext)
93 moved to: lib/Theme.php
94 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
95 gone see: lib/plugin/RecentChanges.php
97 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
98 else define('_PHPWIKI_STDLIB_LOADED', true);
100 define('MAX_PAGENAME_LENGTH', 100);
103 * Convert string to a valid XML identifier.
105 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
107 * We would like to have, e.g. named anchors within wiki pages
108 * names like "Table of Contents" --- clearly not a valid XML
109 * fragment identifier.
111 * This function implements a one-to-one map from {any string}
112 * to {valid XML identifiers}.
115 * converting all bytes not in [A-Za-z0-9:_-],
116 * and any leading byte not in [A-Za-z] to 'xbb.',
117 * where 'bb' is the hexadecimal representation of the
120 * As a special case, the empty string is converted to 'empty.'
125 function MangleXmlIdentifier($str) {
129 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
130 "'x' . sprintf('%02x', ord('\\0')) . '.'",
134 function UnMangleXmlIdentifier($str) {
135 if ($str == 'empty.')
137 return preg_replace('/x(\w\w)\./e',
138 "sprintf('%c', hex('\\0'))",
143 * Returns a name for the WIKI_ID cookie that should be unique on the host.
144 * But for it to be unique you must have set a unique WIKI_NAME in your
145 * configuration file.
146 * @return string The name of the WIKI_ID cookie to use for this wiki.
148 function GetCookieName() {
149 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
153 * Generates a valid URL for a given Wiki pagename.
154 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
155 * If a WikiDB_Page object function will extract the name to link to.
156 * If a WikiDB_PageRevision object function will extract the name to link to.
158 * @param boolean $get_abs_url Default value is false.
159 * @return string The absolute URL to the page passed as $pagename.
161 function WikiURL($pagename, $args = '', $get_abs_url = false) {
162 global $request, $WikiTheme;
165 if (is_object($pagename)) {
166 if (isa($pagename, 'WikiDB_Page')) {
167 $pagename = $pagename->getName();
169 elseif (isa($pagename, 'WikiDB_PageRevision')) {
170 $page = $pagename->getPage();
171 $args['version'] = $pagename->getVersion();
172 $pagename = $page->getName();
174 elseif (isa($pagename, 'WikiPageName')) {
175 $anchor = $pagename->anchor;
176 $pagename = $pagename->name;
178 $anchor = $pagename->anchor;
179 $pagename = $pagename->name;
182 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
184 $args = 'start_debug=' . $request->getArg('start_debug');
185 elseif (is_array($args))
186 $args['start_debug'] = $request->getArg('start_debug');
188 $args .= '&start_debug=' . $request->getArg('start_debug');
190 if (is_array($args)) {
192 foreach ($args as $key => $val) {
193 // avoid default args
194 if (USE_PATH_INFO and $key == 'pagename')
196 elseif ($key == 'action' and $val == 'browse')
198 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
199 $enc_args[] = urlencode($key) . '=' . urlencode($val);
201 $args = join('&', $enc_args);
204 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
205 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
206 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
208 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
209 if ($WikiTheme->VALID_LINKS and $request->getArg('action') == 'pdf') {
210 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
213 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
215 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
225 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
226 $url .= "?pagename=" . rawurlencode($pagename);
231 $url .= "#" . MangleXmlIdentifier($anchor);
235 /** Convert relative URL to absolute URL.
237 * This converts a relative URL to one of PhpWiki's support files
238 * to an absolute one.
241 * @return string Absolute URL
243 function AbsoluteURL ($url) {
244 if (preg_match('/^https?:/', $url))
246 if ($url[0] != '/') {
247 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
248 while ($base != '/' and substr($url, 0, 3) == "../") {
249 $url = substr($url, 3);
250 $base = dirname($base);
256 return SERVER_URL . $url;
259 function DataURL ($url) {
260 if (preg_match('/^https?:/', $url))
262 $url = NormalizeWebFileName($url);
263 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
264 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
265 return AbsoluteURL($url);
269 * Generates icon in front of links.
271 * @param string $protocol_or_url URL or protocol to determine which icon to use.
273 * @return HtmlElement HtmlElement object that contains data to create img link to
274 * icon for use with url or protocol passed to the function. False if no img to be
277 function IconForLink($protocol_or_url) {
279 if (0 and $filename_suffix == false) {
280 // display apache style icon for file type instead of protocol icon
281 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
282 // - document: html, htm, text, txt, rtf, pdf, doc
283 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
284 // - audio: mp3,mp2,aiff,aif,au
285 // - multimedia: mpeg,mpg,mov,qt
287 list ($proto) = explode(':', $protocol_or_url, 2);
288 $src = $WikiTheme->getLinkIconURL($proto);
290 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
297 * Glue icon in front of or after text.
298 * Pref: 'noLinkIcons' - ignore icon if set
299 * Theme: 'LinkIcons' - 'yes' at front
300 * - 'no' display no icon
301 * - 'front' display at left
302 * - 'after' display at right
304 * @param string $protocol_or_url Protocol or URL. Used to determine the
306 * @param string $text The text.
307 * @return XmlContent.
309 function PossiblyGlueIconToText($proto_or_url, $text) {
310 global $request, $WikiTheme;
311 if ($request->getPref('noLinkIcons'))
313 $icon = IconForLink($proto_or_url);
316 if ($where = $WikiTheme->getLinkIconAttr()) {
317 if ($where == 'no') return $text;
318 if ($where != 'after') $where = 'front';
322 if ($where == 'after') {
323 // span the icon only to the last word (tie them together),
324 // to let the previous words wrap on line breaks.
325 if (!is_object($text)) {
326 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
327 list (, $prefix, $last_word) = $m;
333 $text = HTML::span(array('style' => 'white-space: nowrap'),
334 $last_word, HTML::Raw(' '), $icon);
336 $text = HTML($prefix, $text);
339 // span the icon only to the first word (tie them together),
340 // to let the next words wrap on line breaks
341 if (!is_object($text)) {
342 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
343 list (, $first_word, $tail) = $m;
349 $text = HTML::span(array('style' => 'white-space: nowrap'),
352 $text = HTML($text, $tail);
357 * Determines if the url passed to function is safe, by detecting if the characters
358 * '<', '>', or '"' are present.
359 * Check against their urlencoded values also.
361 * @param string $url URL to check for unsafe characters.
362 * @return boolean True if same, false else.
364 function IsSafeURL($url) {
365 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
369 * Generates an HtmlElement object to store data for a link.
371 * @param string $url URL that the link will point to.
372 * @param string $linktext Text to be displayed as link.
373 * @return HtmlElement HtmlElement object that contains data to construct an html link.
375 function LinkURL($url, $linktext = '') {
376 // FIXME: Is this needed (or sufficient?)
377 if(! IsSafeURL($url)) {
378 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
379 _("BAD URL -- remove all of <, >, \"")));
383 $linktext = preg_replace("/mailto:/A", "", $url);
384 $args = array('href' => $url);
385 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
386 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
387 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
389 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
396 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
397 * Disallows sizes which are too small.
398 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
400 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
402 function LinkImage($url, $alt = false) {
403 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
404 // Disallow tags in img src urls. Typical CSS attacks.
405 // FIXME: Is this needed (or sufficient?)
406 if(! IsSafeURL($url)) {
407 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
408 _("BAD URL -- remove all of <, >, \"")));
410 // support new syntax: [image.jpg size=50% border=n]
411 //if (!preg_match("/\.(".$force_img.")/i", $url))
413 $arr = split(' ',$url);
414 if (count($arr) > 1) {
417 if (empty($alt)) $alt = basename($url);
418 $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
419 if (count($arr) > 1) {
421 foreach ($arr as $attr) {
422 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
423 $link->setAttr('width',$m[1]);
424 $link->setAttr('height',$m[1]);
426 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
427 $link->setAttr('width',$m[1]);
428 $link->setAttr('height',$m[2]);
430 if (preg_match('/^border=(\d+)$/',$attr,$m))
431 $link->setAttr('border',$m[1]);
432 if (preg_match('/^align=(\w+)$/',$attr,$m))
433 $link->setAttr('align',$m[1]);
434 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
435 $link->setAttr('hspace',$m[1]);
436 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
437 $link->setAttr('vspace',$m[1]);
440 // Check width and height as spam countermeasure
441 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
442 //$width = (int) $width; // px or % or other suffix
443 //$height = (int) $height;
444 if (($width < 3 and $height < 10) or
445 ($height < 3 and $width < 20) or
446 ($height < 7 and $width < 7))
448 trigger_error(_("Invalid image size"), E_USER_WARNING);
452 // Older php versions crash here with certain png's:
453 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
454 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
455 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
456 if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
457 ; // it's safe to assume that this will fail.
458 elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
461 if (($width < 3 and $height < 10)
462 or ($height < 3 and $width < 20)
463 or ($height < 7 and $width < 7))
465 trigger_error(_("Invalid image size"), E_USER_WARNING);
471 $link->setAttr('class', 'inlineimage');
473 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
474 * png|jpg|gif|jpeg|bmp|pl|cgi
475 * Note: Allow cgi's (pl,cgi) returning images.
477 if (!preg_match("/\.(".$force_img.")/i", $url)) {
478 //HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
479 // => HTML::object(array('src' => $url)) ...;
480 return ImgObject($link, $ori_url);
486 * <object> / <embed> tags instead of <img> for all non-image extensions allowed via INLINE_IMAGES
487 * Called by LinkImage(), not directly.
488 * Syntax: [image.svg size=50% border=n align= hspace= vspace= width= height=]
489 * $alt may be an alternate img
490 * TODO: Need to unify with WikiPluginCached::embedObject()
492 * Note that Safari 1.0 will crash with <object>, so use only <embed>
493 * http://www.alleged.org.uk/pdc/2002/svg-object.html
495 function ImgObject($img, $url) {
496 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
497 $args = split(' ', $url);
498 if (count($args) >= 1) {
499 $url = array_shift($args);
500 foreach ($args as $attr) {
501 if (preg_match('/^type=(\S+)$/',$attr,$m))
502 $img->setAttr('type', $m[1]);
503 if (preg_match('/^data=(\S+)$/',$attr,$m))
504 $img->setAttr('data', $m[1]);
507 $type = $img->getAttr('type');
509 // TODO: map extension to mime-types if type is not given and php < 4.3
510 if (function_exists('mime_content_type'))
511 $type = mime_content_type($url);
513 $link = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)));
514 $link->setAttr('class', 'inlineobject');
515 if (isBrowserSafari()) {
516 return HTML::embed($link->_attr);
518 $link->pushContent(HTML::embed($link->_attr));
525 // var in php5 deprecated
527 $this->items = array();
530 function push($item) {
531 $this->items[$this->size] = $item;
537 if ($this->size == 0) {
538 return false; // stack is empty
541 return $this->items[$this->size];
550 return $this->items[$this->size - 1];
556 // end class definition
558 function SplitQueryArgs ($query_args = '')
560 // FIXME: use the arg-seperator which might not be &
561 $split_args = split('&', $query_args);
563 while (list($key, $val) = each($split_args))
564 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
565 $args[$m[1]] = $m[2];
569 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
572 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
573 return HTML::strong(array('class' => 'rawurl'),
574 HTML::u(array('class' => 'baduri'),
575 _("BAD phpwiki: URL")));
579 $pagename = urldecode($m[1]);
582 if (empty($pagename) &&
583 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
584 // Convert old style links (to not break diff links in
586 $pagename = urldecode($m[2]);
587 $args = array("action" => $m[1]);
590 $args = SplitQueryArgs($qargs);
593 if (empty($pagename))
594 $pagename = $GLOBALS['request']->getArg('pagename');
596 if (isset($args['action']) && $args['action'] == 'browse')
597 unset($args['action']);
600 if (empty($args['action']))
602 else if (is_safe_action($args['action']))
603 $class = 'wikiaction';
605 if (empty($args['action']) || is_safe_action($args['action']))
606 $class = 'wikiaction';
608 // Don't allow administrative links on unlocked pages.
609 $dbi = $GLOBALS['request']->getDbh();
610 $page = $dbi->getPage($basepage ? $basepage : $pagename);
611 if (!$page->get('locked'))
612 return HTML::span(array('class' => 'wikiunsafe'),
613 HTML::u(_("Lock page to enable link")));
614 $class = 'wikiadmin';
618 $text = HTML::span(array('class' => 'rawurl'), $url);
620 $wikipage = new WikiPageName($pagename);
621 if (!$wikipage->isValid()) {
623 return $WikiTheme->linkBadWikiWord($wikipage, $url);
626 return HTML::a(array('href' => WikiURL($pagename, $args),
632 * A class to assist in parsing wiki pagenames.
634 * Now with subpages and anchors, parsing and passing around
635 * pagenames is more complicated. This should help.
639 /** Short name for page.
641 * This is the value of $name passed to the constructor.
642 * (For use, e.g. as a default label for links to the page.)
646 /** The full page name.
648 * This is the full name of the page (without anchor).
654 * This is the referenced anchor within the page, or the empty string.
660 * @param mixed $name Page name.
661 * WikiDB_Page, WikiDB_PageRevision, or string.
662 * This can be a relative subpage name (like '/SubPage'),
663 * or can be the empty string to refer to the $basename.
665 * @param string $anchor For links to anchors in page.
667 * @param mixed $basename Page name from which to interpret
668 * relative or other non-fully-specified page names.
670 function WikiPageName($name, $basename=false, $anchor=false) {
671 if (is_string($name)) {
672 $this->shortName = $name;
673 if (strstr($name, ':')) {
674 list($moniker, $shortName) = split (":", $name, 2);
675 $map = getInterwikiMap(); // allow overrides to custom maps
676 if (isset($map->_map[$moniker])) {
677 $url = $map->_map[$moniker];
678 if (strstr($url, '%s'))
679 $url = sprintf($url, $shortName);
683 // expand Talk or User, but not to absolute urls!
684 if (strstr($url, '//')) {
685 if ($moniker == 'Talk')
686 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
687 elseif ($moniker == 'User')
692 if (strstr($shortName, '?')) {
693 list($shortName, $dummy) = split("\?", $shortName, 2);
695 $this->shortName = $shortName;
698 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
699 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
701 $name = $this->_pagename($basename) . $name;
703 $name = $this->_normalize_bad_pagename($name);
704 $this->shortName = $name;
709 $name = $this->_pagename($name);
710 $this->shortName = $name;
713 $this->name = $this->_check($name);
714 $this->anchor = (string)$anchor;
721 function getParent() {
723 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
725 return substr($name, 0, -strlen($tail));
728 function isValid($strict = false) {
730 return !isset($this->_errors);
731 return (is_string($this->name) and $this->name != '');
734 function getWarnings() {
736 if (isset($this->_warnings))
737 $warnings = array_merge($warnings, $this->_warnings);
738 if (isset($this->_errors))
739 $warnings = array_merge($warnings, $this->_errors);
743 return sprintf(_("'%s': Bad page name: %s"),
744 $this->shortName, join(', ', $warnings));
747 function _pagename($page) {
748 if (isa($page, 'WikiDB_Page'))
749 return $page->getName();
750 elseif (isa($page, 'WikiDB_PageRevision'))
751 return $page->getPageName();
752 elseif (isa($page, 'WikiPageName'))
754 // '0' or e.g. '1984' should be allowed though
755 if (!is_string($page) and !is_integer($page)) {
756 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
757 $page, gettype($page), get_class($page)),
760 //assert(is_string($page));
764 function _normalize_bad_pagename($name) {
765 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
767 // Punt... You really shouldn't get here.
770 return $request->getArg('pagename');
772 assert($name[0] == SUBPAGE_SEPARATOR);
773 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
774 return substr($name, 1);
778 * Compress internal white-space to single space character.
780 * This leads to problems with loading a foreign charset pagename,
781 * which cannot be deleted anymore, because unknown chars are compressed.
782 * So BEFORE importing a file _check must be done !!!
784 function _check($pagename) {
785 // Compress internal white-space to single space character.
786 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
787 if ($pagename != $orig)
788 $this->_warnings[] = _("White space converted to single space");
790 // Delete any control characters.
791 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
792 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
793 if ($pagename != $orig)
794 $this->_errors[] = _("Control characters not allowed");
797 // Strip leading and trailing white-space.
798 $pagename = trim($pagename);
801 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
802 $pagename = substr($pagename, 1);
803 if ($pagename != $orig)
804 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
806 // ";" is urlencoded, so safe from php arg-delim problems
807 /*if (strstr($pagename, ';')) {
808 $this->_warnings[] = _("';' is deprecated");
809 $pagename = str_replace(';', '', $pagename);
812 // not only for SQL, also to restrict url length
813 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
814 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
815 $this->_errors[] = _("too long");
818 // disallow some chars only on file and cvs
819 if ((DATABASE_TYPE == 'cvs'
820 or DATABASE_TYPE == 'file'
821 or DATABASE_TYPE == 'flatfile')
822 and preg_match('/(:|\.\.)/', $pagename, $m))
824 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
825 $pagename = str_replace('..', '', $pagename);
826 $pagename = str_replace(':', '', $pagename);
834 * Convert old page markup to new-style markup.
836 * @param string $text Old-style wiki markup.
838 * @param string $markup_type
840 * <dt><code>"block"</code> <dd>Convert all markup.
841 * <dt><code>"inline"</code> <dd>Convert only inline markup.
842 * <dt><code>"links"</code> <dd>Convert only link markup.
845 * @return string New-style wiki markup.
847 * @bugs Footnotes don't work quite as before (esp if there are
848 * multiple references to the same footnote. But close enough,
849 * probably for now....
850 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
851 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
852 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
853 * also known to crash, even with Apache1.
855 function ConvertOldMarkup ($text, $markup_type = "block") {
861 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
862 // AnciennesR%E8glesDeFormatage crashes.
863 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
864 // also known to crash, even with Apache1.
866 // I suspect this only to crash with Apache2 and IIS.
867 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
868 and preg_match("/plugin CreateToc/", $text))
870 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
871 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
872 ._("Skipped."), E_USER_WARNING);
874 //if (!DEBUG) return $text;
879 /*****************************************************************
880 * Conversions for inline markup:
887 // escape escaped brackets
891 // change ! escapes to ~'s.
892 global $WikiNameRegexp, $request;
893 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
894 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
895 if (check_php_version(4,3,9)) {
896 $map = getInterwikiMap();
897 if ($map_regex = $map->getRegexp())
898 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
900 $bang_esc[] = $WikiNameRegexp;
901 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
904 $subs["links"] = array($orig, $repl);
906 // Temporarily URL-encode pairs of underscores in links to hide
907 // them from the re for bold markup.
908 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
909 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
912 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
915 // Convert footnote references.
916 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
917 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
919 // Convert old style emphases to HTML style emphasis.
920 $orig[] = '/__(.*?)__/';
921 $repl[] = '<strong>\\1</strong>';
922 $orig[] = "/''(.*?)''/";
923 $repl[] = '<em>\\1</em>';
925 // Escape nestled markup.
926 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
929 // in old markup headings only allowed at beginning of line
933 // Convert URL-encoded pairs of underscores in links back to
934 // real underscores after bold markup has been converted.
935 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
936 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
938 $subs["inline"] = array($orig, $repl);
940 /*****************************************************************
941 * Patterns which match block markup constructs which take
942 * special handling...
946 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
948 $blockpats[] = '\|(?:.*\n\|)*';
951 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
953 // Footnote definitions
954 $blockpats[] = '\[\s*(\d+)\s*\]';
958 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
962 $blockpats[] = '!{1,3}[^!]';
964 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
965 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
967 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
968 . join("|", $blockpats)
973 if ($markup_type != "block") {
974 list ($orig, $repl) = $subs[$markup_type];
975 return preg_replace($orig, $repl, $text);
978 list ($orig, $repl) = $subs['inline'];
981 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
982 // AnciennesR%E8glesDeFormatage and more
983 // See http://www.pcre.org/pcre.txt LIMITATIONS
984 while (preg_match($block_re, $text, $m)) {
985 $text = substr($text, strlen($m[0]));
986 list (,$leading_text, $block) = $m;
989 if (strchr(" \t", $block[0])) {
992 $suffix = "\n</pre>\n";
994 elseif ($block[0] == '|') {
996 $prefix = "<?plugin OldStyleTable\n";
999 elseif (strchr("#*;", $block[0])) {
1000 // Old-style list item
1001 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1002 list (,$ind,$bullet) = $m;
1003 $block = substr($block, strlen($m[0]));
1005 $indent = str_repeat(' ', strlen($ind));
1006 if ($bullet[0] == ';') {
1007 //$term = ltrim(substr($bullet, 1));
1008 //return $indent . $term . "\n" . $indent . ' ';
1009 $prefix = $ind . $bullet;
1012 $prefix = $indent . $bullet . ' ';
1014 elseif ($block[0] == '[') {
1015 // Footnote definition
1016 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1018 $block = substr($block, strlen($m[0]));
1019 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1021 elseif ($block[0] == '<') {
1023 // HACK: no inline markup...
1027 elseif ($block[0] == '!') {
1029 preg_match('/^!{1,3}/', $block, $m);
1031 $block = substr($block, strlen($m[0]));
1037 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1038 if ($block) $block = preg_replace($orig, $repl, $block);
1039 $out .= $leading_text;
1044 return $out . preg_replace($orig, $repl, $text);
1050 * Expand tabs in string.
1052 * Converts all tabs to (the appropriate number of) spaces.
1054 * @param string $str
1055 * @param integer $tab_width
1058 function expand_tabs($str, $tab_width = 8) {
1059 $split = split("\t", $str);
1060 $tail = array_pop($split);
1062 foreach ($split as $hunk) {
1064 $pos = strlen(strrchr($expanded, "\n")) - 1;
1065 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1067 return substr($expanded, 1) . $tail;
1071 * Split WikiWords in page names.
1073 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1074 * places like page titles. This is rumored to help search engines
1077 * @param $page string The page name.
1079 * @return string The split name.
1081 function SplitPagename ($page) {
1083 if (preg_match("/\s/", $page))
1084 return $page; // Already split --- don't split any more.
1086 // This algorithm is specialized for several languages.
1087 // (Thanks to Pierrick MEIGNEN)
1088 // Improvements for other languages welcome.
1091 // This mess splits between a lower-case letter followed by
1092 // either an upper-case or a numeral; except that it wont
1093 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1094 switch ($GLOBALS['LANG']) {
1099 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1102 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1105 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1106 // This the single-letter words 'I' and 'A' from any following
1107 // capitalized words.
1108 switch ($GLOBALS['LANG']) {
1110 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1113 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1116 // Split numerals from following letters.
1117 $RE[] = '/(\d)([[:alpha:]])/';
1118 // Split at subpage seperators. TBD in Theme.php
1119 $RE[] = "/([^${sep}]+)(${sep})/";
1120 $RE[] = "/(${sep})([^${sep}]+)/";
1122 foreach ($RE as $key)
1123 $RE[$key] = pcre_fix_posix_classes($key);
1126 foreach ($RE as $regexp) {
1127 $page = preg_replace($regexp, '\\1 \\2', $page);
1132 function NoSuchRevision (&$request, $page, $version) {
1133 $html = HTML(HTML::h2(_("Revision Not Found")),
1134 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1135 $version, WikiLink($page, 'auto'))));
1136 include_once('lib/Template.php');
1137 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1143 * Get time offset for local time zone.
1145 * @param $time time_t Get offset for this time. Default: now.
1146 * @param $no_colon boolean Don't put colon between hours and minutes.
1147 * @return string Offset as a string in the format +HH:MM.
1149 function TimezoneOffset ($time = false, $no_colon = false) {
1150 if ($time === false)
1152 $secs = date('Z', $time);
1161 $colon = $no_colon ? '' : ':';
1162 $mins = intval(($secs + 30) / 60);
1163 return sprintf("%s%02d%s%02d",
1164 $sign, $mins / 60, $colon, $mins % 60);
1169 * Format time in ISO-8601 format.
1171 * @param $time time_t Time. Default: now.
1172 * @return string Date and time in ISO-8601 format.
1174 function Iso8601DateTime ($time = false) {
1175 if ($time === false)
1177 $tzoff = TimezoneOffset($time);
1178 $date = date('Y-m-d', $time);
1179 $time = date('H:i:s', $time);
1180 return $date . 'T' . $time . $tzoff;
1184 * Format time in RFC-2822 format.
1186 * @param $time time_t Time. Default: now.
1187 * @return string Date and time in RFC-2822 format.
1189 function Rfc2822DateTime ($time = false) {
1190 if ($time === false)
1192 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1196 * Format time in RFC-1123 format.
1198 * @param $time time_t Time. Default: now.
1199 * @return string Date and time in RFC-1123 format.
1201 function Rfc1123DateTime ($time = false) {
1202 if ($time === false)
1204 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1207 /** Parse date in RFC-1123 format.
1209 * According to RFC 1123 we must accept dates in the following
1212 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1213 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1214 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1216 * (Though we're only allowed to generate dates in the first format.)
1218 function ParseRfc1123DateTime ($timestr) {
1219 $timestr = trim($timestr);
1220 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1221 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1223 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1225 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1226 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1228 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1229 if ($year < 70) $year += 2000;
1230 elseif ($year < 100) $year += 1900;
1232 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1233 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1235 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1242 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1244 return false; // failed
1249 * Format time to standard 'ctime' format.
1251 * @param $time time_t Time. Default: now.
1252 * @return string Date and time.
1254 function CTime ($time = false)
1256 if ($time === false)
1258 return date("D M j H:i:s Y", $time);
1263 * Format number as kilobytes or bytes.
1264 * Short format is used for PageList
1265 * Long format is used in PageInfo
1267 * @param $bytes int. Default: 0.
1268 * @param $longformat bool. Default: false.
1269 * @return class FormattedText (XmlElement.php).
1271 function ByteFormatter ($bytes = 0, $longformat = false) {
1274 if ($bytes < 1024) {
1276 $size = fmt("%s b", $bytes);
1278 $size = fmt("%s bytes", $bytes);
1281 $kb = round($bytes / 1024, 1);
1283 $size = fmt("%s k", $kb);
1285 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1291 * Internationalized printf.
1293 * This is essentially the same as PHP's built-in printf
1294 * with the following exceptions:
1296 * <li> It passes the format string through gettext().
1297 * <li> It supports the argument reordering extensions.
1304 * __printf("Differences between versions %s and %s of %s",
1305 * $new_link, $old_link, $page_link);
1308 * Then in locale/po/de.po, one can reorder the printf arguments:
1311 * msgid "Differences between %s and %s of %s."
1312 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1315 * (Note that while PHP tries to expand $vars within double-quotes,
1316 * the values in msgstr undergo no such expansion, so the '$'s
1319 * One shouldn't use reordered arguments in the default format string.
1320 * Backslashes in the default string would be necessary to escape the
1321 * '$'s, and they'll cause all kinds of trouble....
1323 function __printf ($fmt) {
1324 $args = func_get_args();
1326 echo __vsprintf($fmt, $args);
1330 * Internationalized sprintf.
1332 * This is essentially the same as PHP's built-in printf with the
1333 * following exceptions:
1336 * <li> It passes the format string through gettext().
1337 * <li> It supports the argument reordering extensions.
1342 function __sprintf ($fmt) {
1343 $args = func_get_args();
1345 return __vsprintf($fmt, $args);
1349 * Internationalized vsprintf.
1351 * This is essentially the same as PHP's built-in printf with the
1352 * following exceptions:
1355 * <li> It passes the format string through gettext().
1356 * <li> It supports the argument reordering extensions.
1361 function __vsprintf ($fmt, $args) {
1362 $fmt = gettext($fmt);
1363 // PHP's sprintf doesn't support variable with specifiers,
1364 // like sprintf("%*s", 10, "x"); --- so we won't either.
1366 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1367 // Format string has '%2$s' style argument reordering.
1368 // PHP doesn't support this.
1369 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1370 // literal variable name substitution only to keep locale
1371 // strings uncluttered
1372 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1373 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1375 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1378 // Reorder arguments appropriately.
1379 foreach($m[1] as $argnum) {
1380 if ($argnum < 1 || $argnum > count($args))
1381 trigger_error(sprintf(_("%s: argument index out of range"),
1382 $argnum), E_USER_WARNING);
1383 $newargs[] = $args[$argnum - 1];
1388 // Not all PHP's have vsprintf, so...
1389 array_unshift($args, $fmt);
1390 return call_user_func_array('sprintf', $args);
1393 function file_mtime ($filename) {
1394 if ($stat = @stat($filename))
1400 function sort_file_mtime ($a, $b) {
1401 $ma = file_mtime($a);
1402 $mb = file_mtime($b);
1403 if (!$ma or !$mb or $ma == $mb) return 0;
1404 return ($ma > $mb) ? -1 : 1;
1409 * Build an array in $this->_fileList of files from $dirname.
1410 * Subdirectories are not traversed.
1412 * (This was a function LoadDir in lib/loadsave.php)
1413 * See also http://www.php.net/manual/en/function.readdir.php
1415 function getFiles($exclude='', $sortby='', $limit='') {
1416 $list = $this->_fileList;
1419 require_once('lib/PageList.php');
1420 switch (Pagelist::sortby($sortby, 'db')) {
1421 case 'pagename ASC': break;
1422 case 'pagename DESC':
1423 $list = array_reverse($list);
1426 usort($list,'sort_file_mtime');
1429 usort($list,'sort_file_mtime');
1430 $list = array_reverse($list);
1435 return array_splice($list, 0, $limit);
1439 function _filenameSelector($filename) {
1440 if (! $this->_pattern )
1443 if (! $this->_pcre_pattern )
1444 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1445 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1450 function fileSet($directory, $filepattern = false) {
1451 $this->_fileList = array();
1452 $this->_pattern = $filepattern;
1454 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1455 $this->_case = !isWindows();
1456 $this->_pathsep = '/';
1458 if (empty($directory)) {
1459 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1461 return; // early return
1464 @ $dir_handle = opendir($dir=$directory);
1465 if (empty($dir_handle)) {
1466 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1467 $dir), E_USER_NOTICE);
1468 return; // early return
1471 while ($filename = readdir($dir_handle)) {
1472 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1474 if ($this->_filenameSelector($filename)) {
1475 array_push($this->_fileList, "$filename");
1476 //trigger_error(sprintf(_("found file %s"), $filename),
1477 // E_USER_NOTICE); //debugging
1480 closedir($dir_handle);
1486 // expands a list containing regex's to its matching entries
1487 class ListRegexExpand {
1488 //var $match, $list, $index, $case_sensitive;
1489 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1490 $this->match = $match;
1491 $this->list = &$list;
1492 $this->case_sensitive = $case_sensitive;
1493 //$this->index = false;
1495 function listMatchCallback ($item, $key) {
1496 $quoted = str_replace('/','\/',$item);
1497 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1499 unset($this->list[$this->index]);
1500 $this->list[] = $item;
1503 function expandRegex ($index, &$pages) {
1504 $this->index = $index;
1505 array_walk($pages, array($this, 'listMatchCallback'));
1510 // Convert fileglob to regex style:
1511 // Convert some wildcards to pcre style, escape the rest
1512 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1513 // Fixed bug #994994: "/" in $glob.
1514 function glob_to_pcre ($glob) {
1515 // check simple case: no need to escape
1516 $escape = '\[](){}=!<>|:/';
1517 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1519 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1520 $glob = strtr($glob, "\\", "\xff");
1521 $glob = str_replace("/", "\\/", $glob);
1522 // first convert some unescaped expressions to pcre style: . => \.
1524 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1525 "\\1\xff\\2", $glob);
1528 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1529 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1530 if (!preg_match('/^[\?\*]/', $glob))
1532 if (!preg_match('/[\?\*]$/', $glob))
1535 // Fixes Bug 1182997
1536 // .*? handled above, now escape the rest
1537 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1538 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1540 return strtr($re, "\xff", "");
1543 function glob_match ($glob, $against, $case_sensitive = true) {
1544 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1548 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1549 $list = explode(',',$input);
1550 // expand wildcards from list of $allnames
1551 if (preg_match('/[\?\*]/',$input)) {
1552 // Optimizing loop invariants:
1553 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1554 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1556 if (preg_match('/[\?\*]/',$f)) {
1558 $expand = new ListRegexExpand($list,
1559 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1560 $expand->expandRegex($i, $allnames);
1567 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1568 function explodePageList($input, $include_empty=false, $sortby='pagename',
1569 $limit='', $exclude='') {
1570 include_once("lib/PageList.php");
1571 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1574 // Class introspections
1577 * Determine whether object is of a specified type.
1578 * In PHP builtin since 4.2.0 as is_a()
1579 * is_a() deprecated in PHP 5, in favor of instanceof operator
1581 * @param $object object An object.
1582 * @param $class string Class name.
1583 * @return bool True iff $object is a $class
1584 * or a sub-type of $class.
1586 function isa ($object, $class) {
1587 //if (check_php_version(5))
1588 // return $object instanceof $class;
1589 if (check_php_version(4,2) and !check_php_version(5))
1590 return is_a($object, $class);
1592 $lclass = check_php_version(5) ? $class : strtolower($class);
1593 return is_object($object)
1594 && ( strtolower(get_class($object)) == strtolower($class)
1595 || is_subclass_of($object, $lclass) );
1598 /** Determine whether (possible) object has method.
1600 * @param $object mixed Object
1601 * @param $method string Method name
1602 * @return bool True iff $object is an object with has method $method.
1604 function can ($object, $method) {
1605 return is_object($object) && method_exists($object, strtolower($method));
1608 /** Determine whether a function is okay to use.
1610 * Some providers (e.g. Lycos) disable some of PHP functions for
1611 * "security reasons." This makes those functions, of course,
1612 * unusable, despite the fact the function_exists() says they
1615 * This function test to see if a function exists and is not
1616 * disallowed by PHP's disable_functions config setting.
1618 * @param string $function_name Function name
1619 * @return bool True iff function can be used.
1621 function function_usable($function_name) {
1623 if (!is_array($disabled)) {
1624 $disabled = array();
1625 // Use get_cfg_var since ini_get() is one of the disabled functions
1626 // (on Lycos, at least.)
1627 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1628 foreach ($split as $f)
1629 $disabled[strtolower($f)] = true;
1632 return ( function_exists($function_name)
1633 and ! isset($disabled[strtolower($function_name)])
1640 * This is used for generating ETags.
1642 function wikihash ($x) {
1643 if (is_scalar($x)) {
1646 elseif (is_array($x)) {
1648 return md5(serialize($x));
1650 elseif (is_object($x)) {
1653 trigger_error("Can't hash $x", E_USER_ERROR);
1658 * Seed the random number generator.
1660 * better_srand() ensures the randomizer is seeded only once.
1662 * How random do you want it? See:
1663 * http://www.php.net/manual/en/function.srand.php
1664 * http://www.php.net/manual/en/function.mt-srand.php
1666 function better_srand($seed = '') {
1667 static $wascalled = FALSE;
1669 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1670 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1672 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1676 function rand_ascii($length = 1) {
1679 for ($i = 1; $i <= $length; $i++) {
1680 // return only typeable 7 bit ascii, avoid quotes
1681 if (function_exists('mt_rand'))
1682 $s .= chr(mt_rand(40, 126));
1684 // the usually bad glibc srand()
1685 $s .= chr(rand(40, 126));
1690 /* by Dan Frankowski.
1692 function rand_ascii_readable ($length = 6) {
1693 // Pick a few random letters or numbers
1696 // Don't use 1lI0O, because they're hard to read
1697 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1698 $letter_len = strlen($letters);
1699 for ($i=0; $i < $length; $i++) {
1700 if (function_exists('mt_rand'))
1701 $word .= $letters[mt_rand(0, $letter_len-1)];
1703 $word .= $letters[rand(0, $letter_len-1)];
1709 * Recursively count all non-empty elements
1710 * in array of any dimension or mixed - i.e.
1711 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1712 * See http://www.php.net/manual/en/function.count.php
1714 function count_all($arg) {
1715 // skip if argument is empty
1717 //print_r($arg); //debugging
1719 // not an array, return 1 (base case)
1722 // else call recursively for all elements $arg
1723 foreach($arg as $key => $val)
1724 $count += count_all($val);
1729 function isSubPage($pagename) {
1730 return (strstr($pagename, SUBPAGE_SEPARATOR));
1733 function subPageSlice($pagename, $pos) {
1734 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1735 $pages = array_slice($pages,$pos,1);
1742 * Class for "popping up" and alert box. (Except that right now, it doesn't
1746 * This is a hackish and needs to be refactored. However it would be nice to
1747 * unify all the different methods we use for showing Alerts and Dialogs.
1748 * (E.g. "Page deleted", login form, ...)
1753 * @param object $request
1754 * @param mixed $head Header ("title") for alert box.
1755 * @param mixed $body The text in the alert box.
1756 * @param hash $buttons An array mapping button labels to URLs.
1757 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1759 function Alert($head, $body, $buttons=false) {
1760 if ($buttons === false)
1763 if (is_array($body)) {
1765 foreach ($body as $li) {
1766 $html->pushContent(HTML::li($li));
1770 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1771 $this->_buttons = $buttons;
1775 * Show the alert box.
1780 $tokens = $this->_tokens;
1781 $tokens['BUTTONS'] = $this->_getButtons();
1783 $request->discardOutput();
1784 $tmpl = new Template('dialog', $request, $tokens);
1790 function _getButtons() {
1793 $buttons = $this->_buttons;
1795 $buttons = array(_("Okay") => $request->getURLtoSelf());
1798 foreach ($buttons as $label => $url)
1799 print "$label $url\n";
1800 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1801 return new XmlContent($out);
1806 // 1.3.9-p1 => 1030.091
1807 // 1.3.10pre => 1030.099
1808 // 1.3.11pre-20041120 => 1030.1120041120
1809 // 1.3.12-rc1 => 1030.119
1810 function phpwiki_version() {
1811 static $PHPWIKI_VERSION;
1812 if (!isset($PHPWIKI_VERSION)) {
1813 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1814 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1815 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1816 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1817 $PHPWIKI_VERSION -= 0.01;
1819 return $PHPWIKI_VERSION;
1822 function phpwiki_gzhandler($ob) {
1823 if (function_exists('gzencode'))
1824 $ob = gzencode($ob);
1825 $GLOBALS['request']->_ob_get_length = strlen($ob);
1826 if (!headers_sent()) {
1827 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1832 function isWikiWord($word) {
1833 global $WikiNameRegexp;
1834 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1835 return preg_match("/^$WikiNameRegexp\$/",$word);
1838 // needed to store serialized objects-values only (perm, pref)
1839 function obj2hash ($obj, $exclude = false, $fields = false) {
1841 if (! $fields ) $fields = get_object_vars($obj);
1842 foreach ($fields as $key => $val) {
1843 if (is_array($exclude)) {
1844 if (in_array($key, $exclude)) continue;
1852 * isUtf8String($string) - cheap utf-8 detection
1854 * segfaults for strings longer than 10kb!
1855 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1856 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1858 function isUtf8String( $s ) {
1859 $ptrASCII = '[\x00-\x7F]';
1860 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1861 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1862 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1863 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1864 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1865 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1869 * Check for UTF-8 URLs; Internet Explorer produces these if you
1870 * type non-ASCII chars in the URL bar or follow unescaped links.
1871 * Requires urldecoded pagename.
1872 * Fixes sf.net bug #953949
1874 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1876 function fixTitleEncoding( $s ) {
1881 if (empty($s)) return $s;
1883 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1885 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1886 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1888 $isutf = ($ishigh ? isUtf8String($s) : true);
1889 $locharset = strtolower($charset);
1891 if( $locharset != "utf-8" and $ishigh and $isutf )
1892 $s = charset_convert('UTF-8', $locharset, $s);
1893 if ($locharset == "utf-8" and $ishigh and !$isutf )
1894 return utf8_encode( $s );
1896 // Other languages can safely leave this function, or replace
1897 // it with one to detect and convert another legacy encoding.
1902 * MySQL fulltext index doesn't grok utf-8, so we
1903 * need to fold cases and convert to hex.
1904 * src: languages/Language.php:stripForSearch() from mediawiki
1907 function stripForSearch( $string ) {
1908 global $wikiLowerChars;
1909 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1910 return preg_replace(
1911 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1912 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1918 * Workaround for allow_url_fopen, to get the content of an external URI.
1919 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1920 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1922 function url_get_contents( $uri ) {
1923 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1924 return @file_get_contents($uri);
1926 require_once("lib/HttpClient.php");
1927 $bits = parse_url($uri);
1928 $host = $bits['host'];
1929 $port = isset($bits['port']) ? $bits['port'] : 80;
1930 $path = isset($bits['path']) ? $bits['path'] : '/';
1931 if (isset($bits['query'])) {
1932 $path .= '?'.$bits['query'];
1934 $client = new HttpClient($host, $port);
1935 $client->use_gzip = false;
1936 if (!$client->get($path)) {
1939 return $client->getContent();
1945 * Generate consecutively named strings:
1946 * Name, Name2, Name3, ...
1948 function GenerateId($name) {
1949 static $ids = array();
1950 if (empty($ids[$name])) {
1955 return $name . $ids[$name];
1959 // from IncludePage. To be of general use.
1960 // content: string or array of strings
1961 function firstNWordsOfContent( $n, $content ) {
1962 if ($content and $n > 0) {
1963 if (is_array($content)) {
1964 // fixme: return a list of lines then?
1965 //$content = join("\n", $content);
1966 //$return_array = true;
1968 foreach ($content as $line) {
1969 $words = explode(' ', $line);
1970 if ($wordcount + count($words) > $n) {
1971 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1972 . sprintf(_("... (first %s words)"), $n);
1975 $wordcount += count($words);
1981 // fixme: use better whitespace/word seperators
1982 $words = explode(' ', $content);
1983 if (count($words) > $n) {
1984 return join(' ', array_slice($words, 0, $n))
1985 . sprintf(_("... (first %s words)"), $n);
1995 // moved from lib/plugin/IncludePage.php
1996 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1997 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1999 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
2000 . " \\s*$\\n?" // possible blank lines
2001 . " ( (?: ^.*\\n? )*? )" // some lines
2002 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2003 implode("\n", $content),
2005 // Strip trailing blanks lines and ---- <hr>s
2006 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2008 $text = $match[1] . $section ."\n". $text;
2009 return explode("\n", $text);
2012 $mesg = $page ." ". $section;
2015 return array(sprintf(_("<%s: no such section>"), $mesg));
2018 // use this faster version: only load ExternalReferrer if we came from an external referrer
2019 function isExternalReferrer(&$request) {
2020 if ($referrer = $request->get('HTTP_REFERER')) {
2021 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2022 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2023 require_once("lib/ExternalReferrer.php");
2024 $se = new SearchEngines();
2025 return $se->parseSearchQuery($referrer);
2027 //if (DEBUG) return array('query' => 'wiki');
2032 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2034 function loadPhpExtension($extension) {
2035 if (!extension_loaded($extension)) {
2036 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2037 $soname = ($isWindows ? 'php_' : '')
2039 . ($isWindows ? '.dll' : '.so');
2043 return extension_loaded($extension);
2046 function charset_convert($from, $to, $data) {
2048 //$wikicharset = strtolower($CHARSET);
2049 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2050 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2051 return utf8_decode($data);
2052 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2053 return utf8_encode($data);
2055 if (loadPhpExtension("iconv")) {
2056 $tmpdata = iconv($from, $to, $data);
2058 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2062 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2067 function string_starts_with($string, $prefix) {
2068 return (substr($string, 0, strlen($prefix)) == $prefix);
2070 function string_ends_with($string, $suffix) {
2071 return (substr($string, -strlen($suffix)) == $suffix);
2073 function array_remove($arr,$value) {
2074 return array_values(array_diff($arr,array($value)));
2078 * Ensure that the script will have another $secs time left.
2079 * Works only if safe_mode is off.
2080 * For example not to timeout on waiting socket connections.
2081 * Use the socket timeout as arg.
2083 function longer_timeout($secs = 30) {
2084 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2085 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2086 if ($timeleft < $secs)
2087 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2090 function printSimpleTrace($bt) {
2092 echo "\nTraceback:\n";
2093 if (function_exists('debug_print_backtrace')) { // >= 5
2094 debug_print_backtrace();
2096 foreach ($bt as $i => $elem) {
2097 if (!array_key_exists('file', $elem)) {
2100 //echo join(" ",array_values($elem)),"\n";
2101 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2107 * Return the used process memory, in bytes.
2108 * Enable the section which will work for you. They are very slow.
2109 * Special quirks for Windows: Requires cygwin.
2111 function getMemoryUsage() {
2112 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2113 if (function_exists('memory_get_usage') and memory_get_usage()) {
2114 return memory_get_usage();
2115 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2116 $mem = $u['ru_maxrss'];
2117 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2118 // what we want is the process memory only: apache or php (if CGI)
2121 // win32_ps_stat_proc, win32_ps_stat_mem
2122 if (function_exists('win32_ps_list_procs')) {
2123 $info = win32_ps_stat_proc($pid);
2124 $memstr = $info['mem']['working_set_size'];
2126 // This works only if it's a cygwin process (apache or php).
2127 // Requires a newer cygwin
2128 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2130 // if it's native windows use something like this:
2131 // (requires pslist from sysinternals.com, grep, sed and perl)
2132 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2134 return (integer) trim($memstr);
2137 //%MEM: Percentage of total memory in use by this process
2138 //VSZ: Total virtual memory size, in 1K blocks.
2139 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2140 //CPU time used by process since it started.
2141 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2142 $memstr = exec("ps -orss -p $pid|sed 1d");
2143 return (integer) trim($memstr);
2148 * @param var $needle
2149 * @param array $haystack one-dimensional numeric array only, no hash
2151 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2152 It will return false if not found or the index where it was found.
2153 From dennis.decoene@moveit.be http://www.php.net/array_search
2155 function binary_search($needle, $haystack) {
2156 $high = count($haystack);
2159 while (($high - $low) > 1) {
2160 $probe = floor(($high + $low) / 2);
2161 if ($haystack[$probe] < $needle) {
2163 } elseif ($haystack[$probe] == $needle) {
2164 $high = $low = $probe;
2170 if ($high == count($haystack) || $haystack[$high] != $needle) {
2177 function is_localhost($url = false) {
2179 global $HTTP_SERVER_VARS;
2180 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2184 // $Log: not supported by cvs2svn $
2185 // Revision 1.267 2007/09/12 19:32:29 rurban
2186 // link only VALID_LINKS with pagelist HTML_DUMP
2188 // Revision 1.266 2007/09/01 13:24:23 rurban
2189 // add INSECURE_ACTIONS_LOCALHOST_ONLY. advanced security settings
2191 // Revision 1.265 2007/08/08 18:47:14 rurban
2192 // * Fix EmailNotify for Subpages: Unknown modifier ? at any page save.
2193 // Quoting error on glob_match.
2194 // * Fix binary_search
2196 // Revision 1.264 2007/07/15 17:39:42 rurban
2197 // add binary_search. enable memory ps calls
2199 // Revision 1.263 2007/07/14 12:05:29 rurban
2200 // add url field to WikiPageName for interwiki expansion
2202 // Revision 1.262 2007/06/07 17:02:01 rurban
2203 // fix display of pagenames containing ":" in certain lists
2205 // Revision 1.261 2007/06/01 06:37:53 rurban
2206 // use native debug_print_backtrace
2208 // Revision 1.260 2007/02/17 14:15:21 rurban
2209 // fix ImgLink params: $ori_url
2211 // Revision 1.259 2007/01/20 11:41:38 rurban
2212 // WikiPagename::_check: add flatfile support
2214 // Revision 1.258 2007/01/07 18:43:51 rurban
2215 // Remove FileFinder dependency for loadPhpExtension()
2217 // Revision 1.257 2007/01/03 21:24:56 rurban
2218 // Disable noisy ps subprocess on DEBUG. Turn it on explicitly on memory debugging. Add convert_charset helper. Use convert_charset().
2220 // Revision 1.256 2007/01/02 13:23:49 rurban
2221 // ftnt_${footnum}: do not confuse old php string definition parsers. Clarify API: sortby,limit and exclude are strings.
2223 // Revision 1.255 2006/12/22 16:53:38 rurban
2224 // Try to dl() load the iconv extension, if not already loaded
2226 // Revision 1.254 2006/12/02 19:53:05 rurban
2227 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2228 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2231 // Revision 1.253 2006/08/25 22:20:52 rurban
2232 // better split subpages at sep
2234 // Revision 1.252 2006/06/18 11:03:36 rurban
2235 // support rc version
2237 // Revision 1.251 2006/03/19 15:01:00 rurban
2238 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2240 // Revision 1.250 2006/03/07 20:45:44 rurban
2241 // wikihash for php-5.1
2243 // Revision 1.249 2005/10/30 14:24:33 rurban
2244 // move rand_ascii_readable from Captcha to stdlib
2246 // Revision 1.248 2005/10/29 14:18:30 uckelman
2247 // Added is_a() deprecation note.
2249 // Revision 1.247 2005/10/10 20:31:21 rurban
2252 // Revision 1.246 2005/10/10 19:38:48 rurban
2255 // Revision 1.245 2005/09/18 16:01:09 rurban
2256 // trick to send the correct gzipped Content-Length
2258 // Revision 1.244 2005/09/11 13:24:33 rurban
2259 // fix shortname, dont quote twice in ListRegexExpand
2261 // Revision 1.243 2005/08/06 15:01:38 rurban
2262 // workaround php VBASIC alike limitation: allow integer pagenames
2264 // Revision 1.242 2005/08/06 13:07:04 rurban
2265 // quote paths correctly (not the best method though)
2267 // Revision 1.241 2005/05/06 16:54:19 rurban
2268 // support optional EXTERNAL_LINK_TARGET, default: _blank
2270 // Revision 1.240 2005/04/23 11:15:49 rurban
2271 // handle allowed inlined objects within INLINE_IMAGES
2273 // Revision 1.239 2005/04/01 16:11:42 rurban
2276 // Revision 1.238 2005/03/04 16:29:14 rurban
2277 // Fixed bug #994994 (escape / in glob)
2278 // Optimized glob_to_pcre within fileSet() matching.
2280 // Revision 1.237 2005/02/12 17:22:18 rurban
2281 // locale update: missing . : fixed. unified strings
2282 // proper linebreaks
2284 // Revision 1.236 2005/02/08 13:41:32 rurban
2287 // Revision 1.235 2005/02/04 11:54:48 rurban
2290 // Revision 1.234 2005/02/03 05:09:25 rurban
2291 // Talk: + User: fix
2293 // Revision 1.233 2005/02/02 20:40:12 rurban
2294 // fix Talk: and User: names and links
2296 // Revision 1.232 2005/02/02 19:34:09 rurban
2297 // more maps: Talk, User
2299 // Revision 1.231 2005/01/30 19:48:52 rurban
2300 // enable ps memory on unix
2302 // Revision 1.230 2005/01/25 07:10:51 rurban
2303 // add getMemoryUsage to stdlib
2305 // Revision 1.229 2005/01/21 11:51:22 rurban
2308 // Revision 1.228 2005/01/17 20:28:30 rurban
2309 // Allow more pagename chars: Limit only on certain backends.
2310 // Re-Allow : and ; and control chars on non-file backends.
2312 // Revision 1.227 2005/01/14 18:32:08 uckelman
2313 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2314 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2315 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2316 // conversion of '__' into '<strong>', and then unhidden afterwards.
2318 // Revision 1.226 2004/12/26 17:12:06 rurban
2319 // avoid stdargs in url, php5 fixes
2321 // Revision 1.225 2004/12/22 19:02:29 rurban
2322 // fix glob for starting * or ?
2324 // Revision 1.224 2004/12/20 12:11:50 rurban
2325 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2326 // not reproducable other than on sf.net, but this seems to fix it.
2328 // Revision 1.223 2004/12/18 16:49:29 rurban
2329 // fix RPC for !USE_PATH_INFO, add debugging helper
2331 // Revision 1.222 2004/12/17 16:40:45 rurban
2332 // add not yet used url helper
2334 // Revision 1.221 2004/12/06 19:49:58 rurban
2335 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2336 // renamed delete_page to purge_page.
2337 // enable action=edit&version=-1 to force creation of a new version.
2338 // added BABYCART_PATH config
2339 // fixed magiqc in adodb.inc.php
2340 // and some more docs
2342 // Revision 1.220 2004/11/30 17:47:41 rurban
2343 // added mt_srand, check for native isa
2345 // Revision 1.219 2004/11/26 18:39:02 rurban
2346 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2348 // Revision 1.218 2004/11/25 08:28:48 rurban
2351 // Revision 1.217 2004/11/16 17:31:03 rurban
2352 // re-enable old block markup conversion
2354 // Revision 1.216 2004/11/11 18:31:26 rurban
2355 // add simple backtrace on such general failures to get at least an idea where
2357 // Revision 1.215 2004/11/11 14:34:12 rurban
2358 // minor clarifications
2360 // Revision 1.214 2004/11/11 11:01:20 rurban
2361 // fix loadPhpExtension
2363 // Revision 1.213 2004/11/01 10:43:57 rurban
2364 // seperate PassUser methods into seperate dir (memory usage)
2365 // fix WikiUser (old) overlarge data session
2366 // remove wikidb arg from various page class methods, use global ->_dbi instead
2369 // Revision 1.212 2004/10/22 09:15:39 rurban
2370 // Alert::show has no arg anymore
2372 // Revision 1.211 2004/10/22 09:05:11 rurban
2373 // added longer_timeout (HttpClient)
2376 // Revision 1.210 2004/10/14 21:06:02 rurban
2377 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2379 // Revision 1.209 2004/10/14 19:19:34 rurban
2380 // loadsave: check if the dumped file will be accessible from outside.
2381 // and some other minor fixes. (cvsclient native not yet ready)
2383 // Revision 1.208 2004/10/12 13:13:20 rurban
2384 // php5 compatibility (5.0.1 ok)
2386 // Revision 1.207 2004/09/26 12:21:40 rurban
2387 // removed old log entries.
2388 // added persistent start_debug on internal links and DEBUG
2389 // added isExternalReferrer (not yet used)
2391 // Revision 1.206 2004/09/25 16:28:36 rurban
2392 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2394 // Revision 1.205 2004/09/23 13:59:35 rurban
2395 // Before removing a page display a sample of 100 words.
2397 // Revision 1.204 2004/09/17 13:19:15 rurban
2398 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2401 // Revision 1.203 2004/09/16 08:00:52 rurban
2402 // just some comments
2404 // Revision 1.202 2004/09/14 10:11:44 rurban
2405 // start 2nd Id with ...Plugin2
2407 // Revision 1.201 2004/09/14 10:06:42 rurban
2408 // generate iterated plugin ids, set plugin span id also
2410 // Revision 1.200 2004/08/05 17:34:26 rurban
2411 // move require to sortby branch
2413 // Revision 1.199 2004/08/05 10:38:15 rurban
2414 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
2417 // Revision 1.198 2004/07/02 10:30:36 rurban
2418 // always disable getimagesize for < php-4.3 with external png's
2420 // Revision 1.197 2004/07/02 09:55:58 rurban
2421 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2423 // Revision 1.196 2004/07/01 08:51:22 rurban
2424 // dumphtml: added exclude, print pagename before processing
2426 // Revision 1.195 2004/06/29 08:52:22 rurban
2427 // Use ...version() $need_content argument in WikiDB also:
2428 // To reduce the memory footprint for larger sets of pagelists,
2429 // we don't cache the content (only true or false) and
2430 // we purge the pagedata (_cached_html) also.
2431 // _cached_html is only cached for the current pagename.
2432 // => Vastly improved page existance check, ACL check, ...
2434 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2436 // Revision 1.194 2004/06/29 06:48:04 rurban
2437 // Improve LDAP auth and GROUP_LDAP membership:
2438 // no error message on false password,
2439 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2440 // fixed two group queries (this -> user)
2441 // stdlib: ConvertOldMarkup still flawed
2443 // Revision 1.193 2004/06/28 13:27:03 rurban
2444 // CreateToc disabled for old markup and Apache2 only
2446 // Revision 1.192 2004/06/28 12:47:43 rurban
2447 // skip if non-DEBUG and old markup with CreateToc
2449 // Revision 1.191 2004/06/25 14:31:56 rurban
2450 // avoid debug_skip warning
2452 // Revision 1.190 2004/06/25 14:29:20 rurban
2453 // WikiGroup refactoring:
2454 // global group attached to user, code for not_current user.
2455 // improved helpers for special groups (avoid double invocations)
2456 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2457 // fixed a XHTML validation error on userprefs.tmpl
2459 // Revision 1.189 2004/06/20 09:45:35 rurban
2460 // php5 isa fix (wrong strtolower)
2462 // Revision 1.188 2004/06/16 10:38:58 rurban
2463 // Disallow refernces in calls if the declaration is a reference
2464 // ("allow_call_time_pass_reference clean").
2465 // PhpWiki is now allow_call_time_pass_reference = Off clean,
2466 // but several external libraries may not.
2467 // In detail these libs look to be affected (not tested):
2471 // Revision 1.187 2004/06/14 11:31:37 rurban
2472 // renamed global $Theme to $WikiTheme (gforge nameclash)
2473 // inherit PageList default options from PageList
2474 // default sortby=pagename
2475 // use options in PageList_Selectable (limit, sortby, ...)
2476 // added action revert, with button at action=diff
2477 // added option regex to WikiAdminSearchReplace
2479 // Revision 1.186 2004/06/13 13:54:25 rurban
2480 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2481 // FoafViewer: Check against external requirements, instead of fatal.
2482 // Change output for xhtmldumps: using file:// urls to the local fs.
2483 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2484 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2486 // Revision 1.185 2004/06/11 09:07:30 rurban
2487 // support theme-specific LinkIconAttr: front or after or none
2489 // Revision 1.184 2004/06/04 20:32:53 rurban
2490 // Several locale related improvements suggested by Pierrick Meignen
2491 // LDAP fix by John Cole
2492 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2494 // Revision 1.183 2004/06/01 10:22:56 rurban
2495 // added url_get_contents() used in XmlParser and elsewhere
2497 // Revision 1.182 2004/05/25 12:40:48 rurban
2498 // trim the pagename
2500 // Revision 1.181 2004/05/25 10:18:44 rurban
2501 // Check for UTF-8 URLs; Internet Explorer produces these if you
2502 // type non-ASCII chars in the URL bar or follow unescaped links.
2503 // Fixes sf.net bug #953949
2504 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2506 // Revision 1.180 2004/05/18 16:23:39 rurban
2507 // rename split_pagename to SplitPagename
2509 // Revision 1.179 2004/05/18 16:18:37 rurban
2510 // AutoSplit at subpage seperators
2511 // RssFeed stability fix for empty feeds or broken connections
2513 // Revision 1.178 2004/05/12 10:49:55 rurban
2514 // require_once fix for those libs which are loaded before FileFinder and
2515 // its automatic include_path fix, and where require_once doesn't grok
2516 // dirname(__FILE__) != './lib'
2517 // upgrade fix with PearDB
2518 // navbar.tmpl: remove spaces for IE button alignment
2520 // Revision 1.177 2004/05/08 14:06:12 rurban
2521 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2522 // minor stability and portability fixes
2524 // Revision 1.176 2004/05/08 11:25:15 rurban
2527 // Revision 1.175 2004/05/06 17:30:38 rurban
2528 // CategoryGroup: oops, dos2unix eol
2529 // improved phpwiki_version:
2530 // pre -= .0001 (1.3.10pre: 1030.099)
2531 // -p1 += .001 (1.3.9-p1: 1030.091)
2532 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2533 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2534 // backend->backendType(), backend->database(),
2535 // backend->listOfFields(),
2536 // backend->listOfTables(),
2538 // Revision 1.174 2004/05/06 12:02:05 rurban
2539 // fix sf.net bug#949002: [ Link | ] assertion
2541 // Revision 1.173 2004/05/03 15:00:31 rurban
2542 // added more database upgrading: session.sess_ip, page.id autp_increment
2544 // Revision 1.172 2004/04/26 20:44:34 rurban
2545 // locking table specific for better databases
2547 // Revision 1.171 2004/04/19 23:13:03 zorloc
2548 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
2550 // Revision 1.170 2004/04/19 18:27:45 rurban
2551 // Prevent from some PHP5 warnings (ref args, no :: object init)
2552 // php5 runs now through, just one wrong XmlElement object init missing
2553 // Removed unneccesary UpgradeUser lines
2554 // Changed WikiLink to omit version if current (RecentChanges)
2556 // Revision 1.169 2004/04/15 21:29:48 rurban
2557 // allow [0] with new markup: link to page "0"
2559 // Revision 1.168 2004/04/10 02:30:49 rurban
2560 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2561 // Fixed "cannot setlocale..." (sf.net problem)
2563 // Revision 1.167 2004/04/02 15:06:55 rurban
2564 // fixed a nasty ADODB_mysql session update bug
2565 // improved UserPreferences layout (tabled hints)
2566 // fixed UserPreferences auth handling
2567 // improved auth stability
2568 // improved old cookie handling: fixed deletion of old cookies with paths
2570 // Revision 1.166 2004/04/01 15:57:10 rurban
2571 // simplified Sidebar theme: table, not absolute css positioning
2572 // added the new box methods.
2573 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2575 // Revision 1.165 2004/03/24 19:39:03 rurban
2576 // php5 workaround code (plus some interim debugging code in XmlElement)
2577 // php5 doesn't work yet with the current XmlElement class constructors,
2578 // WikiUserNew does work better than php4.
2579 // rewrote WikiUserNew user upgrading to ease php5 update
2580 // fixed pref handling in WikiUserNew
2581 // added Email Notification
2582 // added simple Email verification
2583 // removed emailVerify userpref subclass: just a email property
2584 // changed pref binary storage layout: numarray => hash of non default values
2585 // print optimize message only if really done.
2586 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2587 // prefs should be stored in db or homepage, besides the current session.
2589 // Revision 1.164 2004/03/18 21:41:09 rurban
2590 // fixed sqlite support
2591 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2593 // Revision 1.163 2004/03/17 18:41:49 rurban
2594 // just reformatting
2596 // Revision 1.162 2004/03/16 15:43:08 rurban
2597 // make fileSet sortable to please PageList
2599 // Revision 1.161 2004/03/12 15:48:07 rurban
2600 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2601 // simplified lib/stdlib.php:explodePageList
2603 // Revision 1.160 2004/02/28 21:14:08 rurban
2604 // generally more PHPDOC docs
2605 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2606 // fxied WikiUserNew pref handling: empty theme not stored, save only
2607 // changed prefs, sql prefs improved, fixed password update,
2608 // removed REPLACE sql (dangerous)
2609 // moved gettext init after the locale was guessed
2610 // + some minor changes
2613 // (c-file-style: "gnu")
2617 // c-basic-offset: 4
2618 // c-hanging-comment-ender-p: nil
2619 // indent-tabs-mode: nil