1 <?php //rcs_id('$Id: stdlib.php,v 1.267 2007-09-12 19:32:29 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) {
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 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
207 if (!empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX)) {
208 if ($GLOBALS['VALID_LINKS'] and $GLOBALS['request']->getArg('action') == 'pdf') {
209 $url = $base . $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
211 $url .= $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
221 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
222 $url .= "?pagename=" . rawurlencode($pagename);
227 $url .= "#" . MangleXmlIdentifier($anchor);
231 /** Convert relative URL to absolute URL.
233 * This converts a relative URL to one of PhpWiki's support files
234 * to an absolute one.
237 * @return string Absolute URL
239 function AbsoluteURL ($url) {
240 if (preg_match('/^https?:/', $url))
242 if ($url[0] != '/') {
243 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
244 while ($base != '/' and substr($url, 0, 3) == "../") {
245 $url = substr($url, 3);
246 $base = dirname($base);
252 return SERVER_URL . $url;
255 function DataURL ($url) {
256 if (preg_match('/^https?:/', $url))
258 $url = NormalizeWebFileName($url);
259 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
260 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
261 return AbsoluteURL($url);
265 * Generates icon in front of links.
267 * @param string $protocol_or_url URL or protocol to determine which icon to use.
269 * @return HtmlElement HtmlElement object that contains data to create img link to
270 * icon for use with url or protocol passed to the function. False if no img to be
273 function IconForLink($protocol_or_url) {
275 if (0 and $filename_suffix == false) {
276 // display apache style icon for file type instead of protocol icon
277 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
278 // - document: html, htm, text, txt, rtf, pdf, doc
279 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
280 // - audio: mp3,mp2,aiff,aif,au
281 // - multimedia: mpeg,mpg,mov,qt
283 list ($proto) = explode(':', $protocol_or_url, 2);
284 $src = $WikiTheme->getLinkIconURL($proto);
286 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
293 * Glue icon in front of or after text.
294 * Pref: 'noLinkIcons' - ignore icon if set
295 * Theme: 'LinkIcons' - 'yes' at front
296 * - 'no' display no icon
297 * - 'front' display at left
298 * - 'after' display at right
300 * @param string $protocol_or_url Protocol or URL. Used to determine the
302 * @param string $text The text.
303 * @return XmlContent.
305 function PossiblyGlueIconToText($proto_or_url, $text) {
306 global $request, $WikiTheme;
307 if ($request->getPref('noLinkIcons'))
309 $icon = IconForLink($proto_or_url);
312 if ($where = $WikiTheme->getLinkIconAttr()) {
313 if ($where == 'no') return $text;
314 if ($where != 'after') $where = 'front';
318 if ($where == 'after') {
319 // span the icon only to the last word (tie them together),
320 // to let the previous words wrap on line breaks.
321 if (!is_object($text)) {
322 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
323 list (, $prefix, $last_word) = $m;
329 $text = HTML::span(array('style' => 'white-space: nowrap'),
330 $last_word, HTML::Raw(' '), $icon);
332 $text = HTML($prefix, $text);
335 // span the icon only to the first word (tie them together),
336 // to let the next words wrap on line breaks
337 if (!is_object($text)) {
338 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
339 list (, $first_word, $tail) = $m;
345 $text = HTML::span(array('style' => 'white-space: nowrap'),
348 $text = HTML($text, $tail);
353 * Determines if the url passed to function is safe, by detecting if the characters
354 * '<', '>', or '"' are present.
355 * Check against their urlencoded values also.
357 * @param string $url URL to check for unsafe characters.
358 * @return boolean True if same, false else.
360 function IsSafeURL($url) {
361 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
365 * Generates an HtmlElement object to store data for a link.
367 * @param string $url URL that the link will point to.
368 * @param string $linktext Text to be displayed as link.
369 * @return HtmlElement HtmlElement object that contains data to construct an html link.
371 function LinkURL($url, $linktext = '') {
372 // FIXME: Is this needed (or sufficient?)
373 if(! IsSafeURL($url)) {
374 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
375 _("BAD URL -- remove all of <, >, \"")));
379 $linktext = preg_replace("/mailto:/A", "", $url);
380 $args = array('href' => $url);
381 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
382 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
383 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
385 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
392 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
393 * Disallows sizes which are too small.
394 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
396 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
398 function LinkImage($url, $alt = false) {
399 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
400 // Disallow tags in img src urls. Typical CSS attacks.
401 // FIXME: Is this needed (or sufficient?)
402 if(! IsSafeURL($url)) {
403 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
404 _("BAD URL -- remove all of <, >, \"")));
406 // support new syntax: [image.jpg size=50% border=n]
407 //if (!preg_match("/\.(".$force_img.")/i", $url))
409 $arr = split(' ',$url);
410 if (count($arr) > 1) {
413 if (empty($alt)) $alt = basename($url);
414 $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
415 if (count($arr) > 1) {
417 foreach ($arr as $attr) {
418 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
419 $link->setAttr('width',$m[1]);
420 $link->setAttr('height',$m[1]);
422 if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
423 $link->setAttr('width',$m[1]);
424 $link->setAttr('height',$m[2]);
426 if (preg_match('/^border=(\d+)$/',$attr,$m))
427 $link->setAttr('border',$m[1]);
428 if (preg_match('/^align=(\w+)$/',$attr,$m))
429 $link->setAttr('align',$m[1]);
430 if (preg_match('/^hspace=(\d+)$/',$attr,$m))
431 $link->setAttr('hspace',$m[1]);
432 if (preg_match('/^vspace=(\d+)$/',$attr,$m))
433 $link->setAttr('vspace',$m[1]);
436 // Check width and height as spam countermeasure
437 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
438 //$width = (int) $width; // px or % or other suffix
439 //$height = (int) $height;
440 if (($width < 3 and $height < 10) or
441 ($height < 3 and $width < 20) or
442 ($height < 7 and $width < 7))
444 trigger_error(_("Invalid image size"), E_USER_WARNING);
448 // Older php versions crash here with certain png's:
449 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
450 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
451 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
452 if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
453 ; // it's safe to assume that this will fail.
454 elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
457 if (($width < 3 and $height < 10)
458 or ($height < 3 and $width < 20)
459 or ($height < 7 and $width < 7))
461 trigger_error(_("Invalid image size"), E_USER_WARNING);
467 $link->setAttr('class', 'inlineimage');
469 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
470 * png|jpg|gif|jpeg|bmp|pl|cgi
471 * Note: Allow cgi's (pl,cgi) returning images.
473 if (!preg_match("/\.(".$force_img.")/i", $url)) {
474 //HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
475 // => HTML::object(array('src' => $url)) ...;
476 return ImgObject($link, $ori_url);
482 * <object> / <embed> tags instead of <img> for all non-image extensions allowed via INLINE_IMAGES
483 * Called by LinkImage(), not directly.
484 * Syntax: [image.svg size=50% border=n align= hspace= vspace= width= height=]
485 * $alt may be an alternate img
486 * TODO: Need to unify with WikiPluginCached::embedObject()
488 * Note that Safari 1.0 will crash with <object>, so use only <embed>
489 * http://www.alleged.org.uk/pdc/2002/svg-object.html
491 function ImgObject($img, $url) {
492 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
493 $args = split(' ', $url);
494 if (count($args) >= 1) {
495 $url = array_shift($args);
496 foreach ($args as $attr) {
497 if (preg_match('/^type=(\S+)$/',$attr,$m))
498 $img->setAttr('type', $m[1]);
499 if (preg_match('/^data=(\S+)$/',$attr,$m))
500 $img->setAttr('data', $m[1]);
503 $type = $img->getAttr('type');
505 // TODO: map extension to mime-types if type is not given and php < 4.3
506 if (function_exists('mime_content_type'))
507 $type = mime_content_type($url);
509 $link = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)));
510 $link->setAttr('class', 'inlineobject');
511 if (isBrowserSafari()) {
512 return HTML::embed($link->_attr);
514 $link->pushContent(HTML::embed($link->_attr));
521 // var in php5 deprecated
523 $this->items = array();
526 function push($item) {
527 $this->items[$this->size] = $item;
533 if ($this->size == 0) {
534 return false; // stack is empty
537 return $this->items[$this->size];
546 return $this->items[$this->size - 1];
552 // end class definition
554 function SplitQueryArgs ($query_args = '')
556 // FIXME: use the arg-seperator which might not be &
557 $split_args = split('&', $query_args);
559 while (list($key, $val) = each($split_args))
560 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
561 $args[$m[1]] = $m[2];
565 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
568 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
569 return HTML::strong(array('class' => 'rawurl'),
570 HTML::u(array('class' => 'baduri'),
571 _("BAD phpwiki: URL")));
575 $pagename = urldecode($m[1]);
578 if (empty($pagename) &&
579 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
580 // Convert old style links (to not break diff links in
582 $pagename = urldecode($m[2]);
583 $args = array("action" => $m[1]);
586 $args = SplitQueryArgs($qargs);
589 if (empty($pagename))
590 $pagename = $GLOBALS['request']->getArg('pagename');
592 if (isset($args['action']) && $args['action'] == 'browse')
593 unset($args['action']);
596 if (empty($args['action']))
598 else if (is_safe_action($args['action']))
599 $class = 'wikiaction';
601 if (empty($args['action']) || is_safe_action($args['action']))
602 $class = 'wikiaction';
604 // Don't allow administrative links on unlocked pages.
605 $dbi = $GLOBALS['request']->getDbh();
606 $page = $dbi->getPage($basepage ? $basepage : $pagename);
607 if (!$page->get('locked'))
608 return HTML::span(array('class' => 'wikiunsafe'),
609 HTML::u(_("Lock page to enable link")));
610 $class = 'wikiadmin';
614 $text = HTML::span(array('class' => 'rawurl'), $url);
616 $wikipage = new WikiPageName($pagename);
617 if (!$wikipage->isValid()) {
619 return $WikiTheme->linkBadWikiWord($wikipage, $url);
622 return HTML::a(array('href' => WikiURL($pagename, $args),
628 * A class to assist in parsing wiki pagenames.
630 * Now with subpages and anchors, parsing and passing around
631 * pagenames is more complicated. This should help.
635 /** Short name for page.
637 * This is the value of $name passed to the constructor.
638 * (For use, e.g. as a default label for links to the page.)
642 /** The full page name.
644 * This is the full name of the page (without anchor).
650 * This is the referenced anchor within the page, or the empty string.
656 * @param mixed $name Page name.
657 * WikiDB_Page, WikiDB_PageRevision, or string.
658 * This can be a relative subpage name (like '/SubPage'),
659 * or can be the empty string to refer to the $basename.
661 * @param string $anchor For links to anchors in page.
663 * @param mixed $basename Page name from which to interpret
664 * relative or other non-fully-specified page names.
666 function WikiPageName($name, $basename=false, $anchor=false) {
667 if (is_string($name)) {
668 $this->shortName = $name;
669 if (strstr($name, ':')) {
670 list($moniker, $shortName) = split (":", $name, 2);
671 $map = getInterwikiMap(); // allow overrides to custom maps
672 if (isset($map->_map[$moniker])) {
673 $url = $map->_map[$moniker];
674 if (strstr($url, '%s'))
675 $url = sprintf($url, $shortName);
679 // expand Talk or User, but not to absolute urls!
680 if (strstr($url, '//')) {
681 if ($moniker == 'Talk')
682 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
683 elseif ($moniker == 'User')
688 if (strstr($shortName, '?')) {
689 list($shortName, $dummy) = split("\?", $shortName, 2);
691 $this->shortName = $shortName;
694 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
695 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
697 $name = $this->_pagename($basename) . $name;
699 $name = $this->_normalize_bad_pagename($name);
700 $this->shortName = $name;
705 $name = $this->_pagename($name);
706 $this->shortName = $name;
709 $this->name = $this->_check($name);
710 $this->anchor = (string)$anchor;
717 function getParent() {
719 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
721 return substr($name, 0, -strlen($tail));
724 function isValid($strict = false) {
726 return !isset($this->_errors);
727 return (is_string($this->name) and $this->name != '');
730 function getWarnings() {
732 if (isset($this->_warnings))
733 $warnings = array_merge($warnings, $this->_warnings);
734 if (isset($this->_errors))
735 $warnings = array_merge($warnings, $this->_errors);
739 return sprintf(_("'%s': Bad page name: %s"),
740 $this->shortName, join(', ', $warnings));
743 function _pagename($page) {
744 if (isa($page, 'WikiDB_Page'))
745 return $page->getName();
746 elseif (isa($page, 'WikiDB_PageRevision'))
747 return $page->getPageName();
748 elseif (isa($page, 'WikiPageName'))
750 // '0' or e.g. '1984' should be allowed though
751 if (!is_string($page) and !is_integer($page)) {
752 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
753 $page, gettype($page), get_class($page)),
756 //assert(is_string($page));
760 function _normalize_bad_pagename($name) {
761 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
763 // Punt... You really shouldn't get here.
766 return $request->getArg('pagename');
768 assert($name[0] == SUBPAGE_SEPARATOR);
769 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
770 return substr($name, 1);
774 * Compress internal white-space to single space character.
776 * This leads to problems with loading a foreign charset pagename,
777 * which cannot be deleted anymore, because unknown chars are compressed.
778 * So BEFORE importing a file _check must be done !!!
780 function _check($pagename) {
781 // Compress internal white-space to single space character.
782 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
783 if ($pagename != $orig)
784 $this->_warnings[] = _("White space converted to single space");
786 // Delete any control characters.
787 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
788 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
789 if ($pagename != $orig)
790 $this->_errors[] = _("Control characters not allowed");
793 // Strip leading and trailing white-space.
794 $pagename = trim($pagename);
797 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
798 $pagename = substr($pagename, 1);
799 if ($pagename != $orig)
800 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
802 // ";" is urlencoded, so safe from php arg-delim problems
803 /*if (strstr($pagename, ';')) {
804 $this->_warnings[] = _("';' is deprecated");
805 $pagename = str_replace(';', '', $pagename);
808 // not only for SQL, also to restrict url length
809 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
810 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
811 $this->_errors[] = _("too long");
814 // disallow some chars only on file and cvs
815 if ((DATABASE_TYPE == 'cvs'
816 or DATABASE_TYPE == 'file'
817 or DATABASE_TYPE == 'flatfile')
818 and preg_match('/(:|\.\.)/', $pagename, $m))
820 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
821 $pagename = str_replace('..', '', $pagename);
822 $pagename = str_replace(':', '', $pagename);
830 * Convert old page markup to new-style markup.
832 * @param string $text Old-style wiki markup.
834 * @param string $markup_type
836 * <dt><code>"block"</code> <dd>Convert all markup.
837 * <dt><code>"inline"</code> <dd>Convert only inline markup.
838 * <dt><code>"links"</code> <dd>Convert only link markup.
841 * @return string New-style wiki markup.
843 * @bugs Footnotes don't work quite as before (esp if there are
844 * multiple references to the same footnote. But close enough,
845 * probably for now....
846 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
847 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
848 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
849 * also known to crash, even with Apache1.
851 function ConvertOldMarkup ($text, $markup_type = "block") {
857 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
858 // AnciennesR%E8glesDeFormatage crashes.
859 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
860 // also known to crash, even with Apache1.
862 // I suspect this only to crash with Apache2 and IIS.
863 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
864 and preg_match("/plugin CreateToc/", $text))
866 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
867 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
868 ._("Skipped."), E_USER_WARNING);
870 //if (!DEBUG) return $text;
875 /*****************************************************************
876 * Conversions for inline markup:
883 // escape escaped brackets
887 // change ! escapes to ~'s.
888 global $WikiNameRegexp, $request;
889 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
890 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
891 if (check_php_version(4,3,9)) {
892 $map = getInterwikiMap();
893 if ($map_regex = $map->getRegexp())
894 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
896 $bang_esc[] = $WikiNameRegexp;
897 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
900 $subs["links"] = array($orig, $repl);
902 // Temporarily URL-encode pairs of underscores in links to hide
903 // them from the re for bold markup.
904 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
905 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
908 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
911 // Convert footnote references.
912 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
913 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
915 // Convert old style emphases to HTML style emphasis.
916 $orig[] = '/__(.*?)__/';
917 $repl[] = '<strong>\\1</strong>';
918 $orig[] = "/''(.*?)''/";
919 $repl[] = '<em>\\1</em>';
921 // Escape nestled markup.
922 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
925 // in old markup headings only allowed at beginning of line
929 // Convert URL-encoded pairs of underscores in links back to
930 // real underscores after bold markup has been converted.
931 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
932 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
934 $subs["inline"] = array($orig, $repl);
936 /*****************************************************************
937 * Patterns which match block markup constructs which take
938 * special handling...
942 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
944 $blockpats[] = '\|(?:.*\n\|)*';
947 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
949 // Footnote definitions
950 $blockpats[] = '\[\s*(\d+)\s*\]';
954 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
958 $blockpats[] = '!{1,3}[^!]';
960 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
961 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
963 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
964 . join("|", $blockpats)
969 if ($markup_type != "block") {
970 list ($orig, $repl) = $subs[$markup_type];
971 return preg_replace($orig, $repl, $text);
974 list ($orig, $repl) = $subs['inline'];
977 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
978 // AnciennesR%E8glesDeFormatage and more
979 // See http://www.pcre.org/pcre.txt LIMITATIONS
980 while (preg_match($block_re, $text, $m)) {
981 $text = substr($text, strlen($m[0]));
982 list (,$leading_text, $block) = $m;
985 if (strchr(" \t", $block[0])) {
988 $suffix = "\n</pre>\n";
990 elseif ($block[0] == '|') {
992 $prefix = "<?plugin OldStyleTable\n";
995 elseif (strchr("#*;", $block[0])) {
996 // Old-style list item
997 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
998 list (,$ind,$bullet) = $m;
999 $block = substr($block, strlen($m[0]));
1001 $indent = str_repeat(' ', strlen($ind));
1002 if ($bullet[0] == ';') {
1003 //$term = ltrim(substr($bullet, 1));
1004 //return $indent . $term . "\n" . $indent . ' ';
1005 $prefix = $ind . $bullet;
1008 $prefix = $indent . $bullet . ' ';
1010 elseif ($block[0] == '[') {
1011 // Footnote definition
1012 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1014 $block = substr($block, strlen($m[0]));
1015 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1017 elseif ($block[0] == '<') {
1019 // HACK: no inline markup...
1023 elseif ($block[0] == '!') {
1025 preg_match('/^!{1,3}/', $block, $m);
1027 $block = substr($block, strlen($m[0]));
1033 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1034 if ($block) $block = preg_replace($orig, $repl, $block);
1035 $out .= $leading_text;
1040 return $out . preg_replace($orig, $repl, $text);
1046 * Expand tabs in string.
1048 * Converts all tabs to (the appropriate number of) spaces.
1050 * @param string $str
1051 * @param integer $tab_width
1054 function expand_tabs($str, $tab_width = 8) {
1055 $split = split("\t", $str);
1056 $tail = array_pop($split);
1058 foreach ($split as $hunk) {
1060 $pos = strlen(strrchr($expanded, "\n")) - 1;
1061 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1063 return substr($expanded, 1) . $tail;
1067 * Split WikiWords in page names.
1069 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1070 * places like page titles. This is rumored to help search engines
1073 * @param $page string The page name.
1075 * @return string The split name.
1077 function SplitPagename ($page) {
1079 if (preg_match("/\s/", $page))
1080 return $page; // Already split --- don't split any more.
1082 // This algorithm is specialized for several languages.
1083 // (Thanks to Pierrick MEIGNEN)
1084 // Improvements for other languages welcome.
1087 // This mess splits between a lower-case letter followed by
1088 // either an upper-case or a numeral; except that it wont
1089 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1090 switch ($GLOBALS['LANG']) {
1095 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1098 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1101 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1102 // This the single-letter words 'I' and 'A' from any following
1103 // capitalized words.
1104 switch ($GLOBALS['LANG']) {
1106 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1109 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1112 // Split numerals from following letters.
1113 $RE[] = '/(\d)([[:alpha:]])/';
1114 // Split at subpage seperators. TBD in Theme.php
1115 $RE[] = "/([^${sep}]+)(${sep})/";
1116 $RE[] = "/(${sep})([^${sep}]+)/";
1118 foreach ($RE as $key)
1119 $RE[$key] = pcre_fix_posix_classes($key);
1122 foreach ($RE as $regexp) {
1123 $page = preg_replace($regexp, '\\1 \\2', $page);
1128 function NoSuchRevision (&$request, $page, $version) {
1129 $html = HTML(HTML::h2(_("Revision Not Found")),
1130 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1131 $version, WikiLink($page, 'auto'))));
1132 include_once('lib/Template.php');
1133 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1139 * Get time offset for local time zone.
1141 * @param $time time_t Get offset for this time. Default: now.
1142 * @param $no_colon boolean Don't put colon between hours and minutes.
1143 * @return string Offset as a string in the format +HH:MM.
1145 function TimezoneOffset ($time = false, $no_colon = false) {
1146 if ($time === false)
1148 $secs = date('Z', $time);
1157 $colon = $no_colon ? '' : ':';
1158 $mins = intval(($secs + 30) / 60);
1159 return sprintf("%s%02d%s%02d",
1160 $sign, $mins / 60, $colon, $mins % 60);
1165 * Format time in ISO-8601 format.
1167 * @param $time time_t Time. Default: now.
1168 * @return string Date and time in ISO-8601 format.
1170 function Iso8601DateTime ($time = false) {
1171 if ($time === false)
1173 $tzoff = TimezoneOffset($time);
1174 $date = date('Y-m-d', $time);
1175 $time = date('H:i:s', $time);
1176 return $date . 'T' . $time . $tzoff;
1180 * Format time in RFC-2822 format.
1182 * @param $time time_t Time. Default: now.
1183 * @return string Date and time in RFC-2822 format.
1185 function Rfc2822DateTime ($time = false) {
1186 if ($time === false)
1188 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1192 * Format time in RFC-1123 format.
1194 * @param $time time_t Time. Default: now.
1195 * @return string Date and time in RFC-1123 format.
1197 function Rfc1123DateTime ($time = false) {
1198 if ($time === false)
1200 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1203 /** Parse date in RFC-1123 format.
1205 * According to RFC 1123 we must accept dates in the following
1208 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1209 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1210 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1212 * (Though we're only allowed to generate dates in the first format.)
1214 function ParseRfc1123DateTime ($timestr) {
1215 $timestr = trim($timestr);
1216 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1217 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1219 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1221 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1222 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1224 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1225 if ($year < 70) $year += 2000;
1226 elseif ($year < 100) $year += 1900;
1228 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1229 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1231 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1238 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1240 return false; // failed
1245 * Format time to standard 'ctime' format.
1247 * @param $time time_t Time. Default: now.
1248 * @return string Date and time.
1250 function CTime ($time = false)
1252 if ($time === false)
1254 return date("D M j H:i:s Y", $time);
1259 * Format number as kilobytes or bytes.
1260 * Short format is used for PageList
1261 * Long format is used in PageInfo
1263 * @param $bytes int. Default: 0.
1264 * @param $longformat bool. Default: false.
1265 * @return class FormattedText (XmlElement.php).
1267 function ByteFormatter ($bytes = 0, $longformat = false) {
1270 if ($bytes < 1024) {
1272 $size = fmt("%s b", $bytes);
1274 $size = fmt("%s bytes", $bytes);
1277 $kb = round($bytes / 1024, 1);
1279 $size = fmt("%s k", $kb);
1281 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1287 * Internationalized printf.
1289 * This is essentially the same as PHP's built-in printf
1290 * with the following exceptions:
1292 * <li> It passes the format string through gettext().
1293 * <li> It supports the argument reordering extensions.
1300 * __printf("Differences between versions %s and %s of %s",
1301 * $new_link, $old_link, $page_link);
1304 * Then in locale/po/de.po, one can reorder the printf arguments:
1307 * msgid "Differences between %s and %s of %s."
1308 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1311 * (Note that while PHP tries to expand $vars within double-quotes,
1312 * the values in msgstr undergo no such expansion, so the '$'s
1315 * One shouldn't use reordered arguments in the default format string.
1316 * Backslashes in the default string would be necessary to escape the
1317 * '$'s, and they'll cause all kinds of trouble....
1319 function __printf ($fmt) {
1320 $args = func_get_args();
1322 echo __vsprintf($fmt, $args);
1326 * Internationalized sprintf.
1328 * This is essentially the same as PHP's built-in printf with the
1329 * following exceptions:
1332 * <li> It passes the format string through gettext().
1333 * <li> It supports the argument reordering extensions.
1338 function __sprintf ($fmt) {
1339 $args = func_get_args();
1341 return __vsprintf($fmt, $args);
1345 * Internationalized vsprintf.
1347 * This is essentially the same as PHP's built-in printf with the
1348 * following exceptions:
1351 * <li> It passes the format string through gettext().
1352 * <li> It supports the argument reordering extensions.
1357 function __vsprintf ($fmt, $args) {
1358 $fmt = gettext($fmt);
1359 // PHP's sprintf doesn't support variable with specifiers,
1360 // like sprintf("%*s", 10, "x"); --- so we won't either.
1362 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1363 // Format string has '%2$s' style argument reordering.
1364 // PHP doesn't support this.
1365 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1366 // literal variable name substitution only to keep locale
1367 // strings uncluttered
1368 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1369 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1371 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1374 // Reorder arguments appropriately.
1375 foreach($m[1] as $argnum) {
1376 if ($argnum < 1 || $argnum > count($args))
1377 trigger_error(sprintf(_("%s: argument index out of range"),
1378 $argnum), E_USER_WARNING);
1379 $newargs[] = $args[$argnum - 1];
1384 // Not all PHP's have vsprintf, so...
1385 array_unshift($args, $fmt);
1386 return call_user_func_array('sprintf', $args);
1389 function file_mtime ($filename) {
1390 if ($stat = @stat($filename))
1396 function sort_file_mtime ($a, $b) {
1397 $ma = file_mtime($a);
1398 $mb = file_mtime($b);
1399 if (!$ma or !$mb or $ma == $mb) return 0;
1400 return ($ma > $mb) ? -1 : 1;
1405 * Build an array in $this->_fileList of files from $dirname.
1406 * Subdirectories are not traversed.
1408 * (This was a function LoadDir in lib/loadsave.php)
1409 * See also http://www.php.net/manual/en/function.readdir.php
1411 function getFiles($exclude='', $sortby='', $limit='') {
1412 $list = $this->_fileList;
1415 require_once('lib/PageList.php');
1416 switch (Pagelist::sortby($sortby, 'db')) {
1417 case 'pagename ASC': break;
1418 case 'pagename DESC':
1419 $list = array_reverse($list);
1422 usort($list,'sort_file_mtime');
1425 usort($list,'sort_file_mtime');
1426 $list = array_reverse($list);
1431 return array_splice($list, 0, $limit);
1435 function _filenameSelector($filename) {
1436 if (! $this->_pattern )
1439 if (! $this->_pcre_pattern )
1440 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1441 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1446 function fileSet($directory, $filepattern = false) {
1447 $this->_fileList = array();
1448 $this->_pattern = $filepattern;
1450 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1451 $this->_case = !isWindows();
1452 $this->_pathsep = '/';
1454 if (empty($directory)) {
1455 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1457 return; // early return
1460 @ $dir_handle = opendir($dir=$directory);
1461 if (empty($dir_handle)) {
1462 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1463 $dir), E_USER_NOTICE);
1464 return; // early return
1467 while ($filename = readdir($dir_handle)) {
1468 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1470 if ($this->_filenameSelector($filename)) {
1471 array_push($this->_fileList, "$filename");
1472 //trigger_error(sprintf(_("found file %s"), $filename),
1473 // E_USER_NOTICE); //debugging
1476 closedir($dir_handle);
1482 // expands a list containing regex's to its matching entries
1483 class ListRegexExpand {
1484 //var $match, $list, $index, $case_sensitive;
1485 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1486 $this->match = $match;
1487 $this->list = &$list;
1488 $this->case_sensitive = $case_sensitive;
1489 //$this->index = false;
1491 function listMatchCallback ($item, $key) {
1492 $quoted = str_replace('/','\/',$item);
1493 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1495 unset($this->list[$this->index]);
1496 $this->list[] = $item;
1499 function expandRegex ($index, &$pages) {
1500 $this->index = $index;
1501 array_walk($pages, array($this, 'listMatchCallback'));
1506 // Convert fileglob to regex style:
1507 // Convert some wildcards to pcre style, escape the rest
1508 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1509 // Fixed bug #994994: "/" in $glob.
1510 function glob_to_pcre ($glob) {
1511 // check simple case: no need to escape
1512 $escape = '\[](){}=!<>|:/';
1513 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1515 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1516 $glob = strtr($glob, "\\", "\xff");
1517 $glob = str_replace("/", "\\/", $glob);
1518 // first convert some unescaped expressions to pcre style: . => \.
1520 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1521 "\\1\xff\\2", $glob);
1524 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1525 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1526 if (!preg_match('/^[\?\*]/', $glob))
1528 if (!preg_match('/[\?\*]$/', $glob))
1531 // Fixes Bug 1182997
1532 // .*? handled above, now escape the rest
1533 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1534 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1536 return strtr($re, "\xff", "");
1539 function glob_match ($glob, $against, $case_sensitive = true) {
1540 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1544 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1545 $list = explode(',',$input);
1546 // expand wildcards from list of $allnames
1547 if (preg_match('/[\?\*]/',$input)) {
1548 // Optimizing loop invariants:
1549 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1550 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1552 if (preg_match('/[\?\*]/',$f)) {
1554 $expand = new ListRegexExpand($list,
1555 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1556 $expand->expandRegex($i, $allnames);
1563 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1564 function explodePageList($input, $include_empty=false, $sortby='pagename',
1565 $limit='', $exclude='') {
1566 include_once("lib/PageList.php");
1567 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1570 // Class introspections
1573 * Determine whether object is of a specified type.
1574 * In PHP builtin since 4.2.0 as is_a()
1575 * is_a() deprecated in PHP 5, in favor of instanceof operator
1577 * @param $object object An object.
1578 * @param $class string Class name.
1579 * @return bool True iff $object is a $class
1580 * or a sub-type of $class.
1582 function isa ($object, $class) {
1583 //if (check_php_version(5))
1584 // return $object instanceof $class;
1585 if (check_php_version(4,2) and !check_php_version(5))
1586 return is_a($object, $class);
1588 $lclass = check_php_version(5) ? $class : strtolower($class);
1589 return is_object($object)
1590 && ( strtolower(get_class($object)) == strtolower($class)
1591 || is_subclass_of($object, $lclass) );
1594 /** Determine whether (possible) object has method.
1596 * @param $object mixed Object
1597 * @param $method string Method name
1598 * @return bool True iff $object is an object with has method $method.
1600 function can ($object, $method) {
1601 return is_object($object) && method_exists($object, strtolower($method));
1604 /** Determine whether a function is okay to use.
1606 * Some providers (e.g. Lycos) disable some of PHP functions for
1607 * "security reasons." This makes those functions, of course,
1608 * unusable, despite the fact the function_exists() says they
1611 * This function test to see if a function exists and is not
1612 * disallowed by PHP's disable_functions config setting.
1614 * @param string $function_name Function name
1615 * @return bool True iff function can be used.
1617 function function_usable($function_name) {
1619 if (!is_array($disabled)) {
1620 $disabled = array();
1621 // Use get_cfg_var since ini_get() is one of the disabled functions
1622 // (on Lycos, at least.)
1623 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1624 foreach ($split as $f)
1625 $disabled[strtolower($f)] = true;
1628 return ( function_exists($function_name)
1629 and ! isset($disabled[strtolower($function_name)])
1636 * This is used for generating ETags.
1638 function wikihash ($x) {
1639 if (is_scalar($x)) {
1642 elseif (is_array($x)) {
1644 return md5(serialize($x));
1646 elseif (is_object($x)) {
1649 trigger_error("Can't hash $x", E_USER_ERROR);
1654 * Seed the random number generator.
1656 * better_srand() ensures the randomizer is seeded only once.
1658 * How random do you want it? See:
1659 * http://www.php.net/manual/en/function.srand.php
1660 * http://www.php.net/manual/en/function.mt-srand.php
1662 function better_srand($seed = '') {
1663 static $wascalled = FALSE;
1665 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1666 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1668 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1672 function rand_ascii($length = 1) {
1675 for ($i = 1; $i <= $length; $i++) {
1676 // return only typeable 7 bit ascii, avoid quotes
1677 if (function_exists('mt_rand'))
1678 $s .= chr(mt_rand(40, 126));
1680 // the usually bad glibc srand()
1681 $s .= chr(rand(40, 126));
1686 /* by Dan Frankowski.
1688 function rand_ascii_readable ($length = 6) {
1689 // Pick a few random letters or numbers
1692 // Don't use 1lI0O, because they're hard to read
1693 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1694 $letter_len = strlen($letters);
1695 for ($i=0; $i < $length; $i++) {
1696 if (function_exists('mt_rand'))
1697 $word .= $letters[mt_rand(0, $letter_len-1)];
1699 $word .= $letters[rand(0, $letter_len-1)];
1705 * Recursively count all non-empty elements
1706 * in array of any dimension or mixed - i.e.
1707 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1708 * See http://www.php.net/manual/en/function.count.php
1710 function count_all($arg) {
1711 // skip if argument is empty
1713 //print_r($arg); //debugging
1715 // not an array, return 1 (base case)
1718 // else call recursively for all elements $arg
1719 foreach($arg as $key => $val)
1720 $count += count_all($val);
1725 function isSubPage($pagename) {
1726 return (strstr($pagename, SUBPAGE_SEPARATOR));
1729 function subPageSlice($pagename, $pos) {
1730 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1731 $pages = array_slice($pages,$pos,1);
1738 * Class for "popping up" and alert box. (Except that right now, it doesn't
1742 * This is a hackish and needs to be refactored. However it would be nice to
1743 * unify all the different methods we use for showing Alerts and Dialogs.
1744 * (E.g. "Page deleted", login form, ...)
1749 * @param object $request
1750 * @param mixed $head Header ("title") for alert box.
1751 * @param mixed $body The text in the alert box.
1752 * @param hash $buttons An array mapping button labels to URLs.
1753 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1755 function Alert($head, $body, $buttons=false) {
1756 if ($buttons === false)
1759 if (is_array($body)) {
1761 foreach ($body as $li) {
1762 $html->pushContent(HTML::li($li));
1766 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1767 $this->_buttons = $buttons;
1771 * Show the alert box.
1776 $tokens = $this->_tokens;
1777 $tokens['BUTTONS'] = $this->_getButtons();
1779 $request->discardOutput();
1780 $tmpl = new Template('dialog', $request, $tokens);
1786 function _getButtons() {
1789 $buttons = $this->_buttons;
1791 $buttons = array(_("Okay") => $request->getURLtoSelf());
1794 foreach ($buttons as $label => $url)
1795 print "$label $url\n";
1796 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1797 return new XmlContent($out);
1802 // 1.3.9-p1 => 1030.091
1803 // 1.3.10pre => 1030.099
1804 // 1.3.11pre-20041120 => 1030.1120041120
1805 // 1.3.12-rc1 => 1030.119
1806 function phpwiki_version() {
1807 static $PHPWIKI_VERSION;
1808 if (!isset($PHPWIKI_VERSION)) {
1809 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1810 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1811 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1812 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1813 $PHPWIKI_VERSION -= 0.01;
1815 return $PHPWIKI_VERSION;
1818 function phpwiki_gzhandler($ob) {
1819 if (function_exists('gzencode'))
1820 $ob = gzencode($ob);
1821 $GLOBALS['request']->_ob_get_length = strlen($ob);
1822 if (!headers_sent()) {
1823 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1828 function isWikiWord($word) {
1829 global $WikiNameRegexp;
1830 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1831 return preg_match("/^$WikiNameRegexp\$/",$word);
1834 // needed to store serialized objects-values only (perm, pref)
1835 function obj2hash ($obj, $exclude = false, $fields = false) {
1837 if (! $fields ) $fields = get_object_vars($obj);
1838 foreach ($fields as $key => $val) {
1839 if (is_array($exclude)) {
1840 if (in_array($key, $exclude)) continue;
1848 * isUtf8String($string) - cheap utf-8 detection
1850 * segfaults for strings longer than 10kb!
1851 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1852 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1854 function isUtf8String( $s ) {
1855 $ptrASCII = '[\x00-\x7F]';
1856 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1857 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1858 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1859 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1860 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1861 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1865 * Check for UTF-8 URLs; Internet Explorer produces these if you
1866 * type non-ASCII chars in the URL bar or follow unescaped links.
1867 * Requires urldecoded pagename.
1868 * Fixes sf.net bug #953949
1870 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1872 function fixTitleEncoding( $s ) {
1877 if (empty($s)) return $s;
1879 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1881 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1882 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1884 $isutf = ($ishigh ? isUtf8String($s) : true);
1885 $locharset = strtolower($charset);
1887 if( $locharset != "utf-8" and $ishigh and $isutf )
1888 $s = charset_convert('UTF-8', $locharset, $s);
1889 if ($locharset == "utf-8" and $ishigh and !$isutf )
1890 return utf8_encode( $s );
1892 // Other languages can safely leave this function, or replace
1893 // it with one to detect and convert another legacy encoding.
1898 * MySQL fulltext index doesn't grok utf-8, so we
1899 * need to fold cases and convert to hex.
1900 * src: languages/Language.php:stripForSearch() from mediawiki
1903 function stripForSearch( $string ) {
1904 global $wikiLowerChars;
1905 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1906 return preg_replace(
1907 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1908 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1914 * Workaround for allow_url_fopen, to get the content of an external URI.
1915 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1916 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1918 function url_get_contents( $uri ) {
1919 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1920 return @file_get_contents($uri);
1922 require_once("lib/HttpClient.php");
1923 $bits = parse_url($uri);
1924 $host = $bits['host'];
1925 $port = isset($bits['port']) ? $bits['port'] : 80;
1926 $path = isset($bits['path']) ? $bits['path'] : '/';
1927 if (isset($bits['query'])) {
1928 $path .= '?'.$bits['query'];
1930 $client = new HttpClient($host, $port);
1931 $client->use_gzip = false;
1932 if (!$client->get($path)) {
1935 return $client->getContent();
1941 * Generate consecutively named strings:
1942 * Name, Name2, Name3, ...
1944 function GenerateId($name) {
1945 static $ids = array();
1946 if (empty($ids[$name])) {
1951 return $name . $ids[$name];
1955 // from IncludePage. To be of general use.
1956 // content: string or array of strings
1957 function firstNWordsOfContent( $n, $content ) {
1958 if ($content and $n > 0) {
1959 if (is_array($content)) {
1960 // fixme: return a list of lines then?
1961 //$content = join("\n", $content);
1962 //$return_array = true;
1964 foreach ($content as $line) {
1965 $words = explode(' ', $line);
1966 if ($wordcount + count($words) > $n) {
1967 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1968 . sprintf(_("... (first %s words)"), $n);
1971 $wordcount += count($words);
1977 // fixme: use better whitespace/word seperators
1978 $words = explode(' ', $content);
1979 if (count($words) > $n) {
1980 return join(' ', array_slice($words, 0, $n))
1981 . sprintf(_("... (first %s words)"), $n);
1991 // moved from lib/plugin/IncludePage.php
1992 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1993 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1995 if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
1996 . " \\s*$\\n?" // possible blank lines
1997 . " ( (?: ^.*\\n? )*? )" // some lines
1998 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1999 implode("\n", $content),
2001 // Strip trailing blanks lines and ---- <hr>s
2002 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2004 $text = $match[1] . $section ."\n". $text;
2005 return explode("\n", $text);
2008 $mesg = $page ." ". $section;
2011 return array(sprintf(_("<%s: no such section>"), $mesg));
2014 // use this faster version: only load ExternalReferrer if we came from an external referrer
2015 function isExternalReferrer(&$request) {
2016 if ($referrer = $request->get('HTTP_REFERER')) {
2017 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2018 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2019 require_once("lib/ExternalReferrer.php");
2020 $se = new SearchEngines();
2021 return $se->parseSearchQuery($referrer);
2023 //if (DEBUG) return array('query' => 'wiki');
2028 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2030 function loadPhpExtension($extension) {
2031 if (!extension_loaded($extension)) {
2032 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2033 $soname = ($isWindows ? 'php_' : '')
2035 . ($isWindows ? '.dll' : '.so');
2039 return extension_loaded($extension);
2042 function charset_convert($from, $to, $data) {
2044 //$wikicharset = strtolower($CHARSET);
2045 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2046 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2047 return utf8_decode($data);
2048 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2049 return utf8_encode($data);
2051 if (loadPhpExtension("iconv")) {
2052 $tmpdata = iconv($from, $to, $data);
2054 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2058 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2063 function string_starts_with($string, $prefix) {
2064 return (substr($string, 0, strlen($prefix)) == $prefix);
2066 function string_ends_with($string, $suffix) {
2067 return (substr($string, -strlen($suffix)) == $suffix);
2069 function array_remove($arr,$value) {
2070 return array_values(array_diff($arr,array($value)));
2074 * Ensure that the script will have another $secs time left.
2075 * Works only if safe_mode is off.
2076 * For example not to timeout on waiting socket connections.
2077 * Use the socket timeout as arg.
2079 function longer_timeout($secs = 30) {
2080 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2081 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2082 if ($timeleft < $secs)
2083 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2086 function printSimpleTrace($bt) {
2088 echo "\nTraceback:\n";
2089 if (function_exists('debug_print_backtrace')) { // >= 5
2090 debug_print_backtrace();
2092 foreach ($bt as $i => $elem) {
2093 if (!array_key_exists('file', $elem)) {
2096 //echo join(" ",array_values($elem)),"\n";
2097 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2103 * Return the used process memory, in bytes.
2104 * Enable the section which will work for you. They are very slow.
2105 * Special quirks for Windows: Requires cygwin.
2107 function getMemoryUsage() {
2108 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2109 if (function_exists('memory_get_usage') and memory_get_usage()) {
2110 return memory_get_usage();
2111 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2112 $mem = $u['ru_maxrss'];
2113 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2114 // what we want is the process memory only: apache or php (if CGI)
2117 // win32_ps_stat_proc, win32_ps_stat_mem
2118 if (function_exists('win32_ps_list_procs')) {
2119 $info = win32_ps_stat_proc($pid);
2120 $memstr = $info['mem']['working_set_size'];
2122 // This works only if it's a cygwin process (apache or php).
2123 // Requires a newer cygwin
2124 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2126 // if it's native windows use something like this:
2127 // (requires pslist from sysinternals.com, grep, sed and perl)
2128 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2130 return (integer) trim($memstr);
2133 //%MEM: Percentage of total memory in use by this process
2134 //VSZ: Total virtual memory size, in 1K blocks.
2135 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2136 //CPU time used by process since it started.
2137 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2138 $memstr = exec("ps -orss -p $pid|sed 1d");
2139 return (integer) trim($memstr);
2144 * @param var $needle
2145 * @param array $haystack one-dimensional numeric array only, no hash
2147 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2148 It will return false if not found or the index where it was found.
2149 From dennis.decoene@moveit.be http://www.php.net/array_search
2151 function binary_search($needle, $haystack) {
2152 $high = count($haystack);
2155 while (($high - $low) > 1) {
2156 $probe = floor(($high + $low) / 2);
2157 if ($haystack[$probe] < $needle) {
2159 } elseif ($haystack[$probe] == $needle) {
2160 $high = $low = $probe;
2166 if ($high == count($haystack) || $haystack[$high] != $needle) {
2173 function is_localhost($url = false) {
2175 global $HTTP_SERVER_VARS;
2176 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2180 // $Log: not supported by cvs2svn $
2181 // Revision 1.266 2007/09/01 13:24:23 rurban
2182 // add INSECURE_ACTIONS_LOCALHOST_ONLY. advanced security settings
2184 // Revision 1.265 2007/08/08 18:47:14 rurban
2185 // * Fix EmailNotify for Subpages: Unknown modifier ? at any page save.
2186 // Quoting error on glob_match.
2187 // * Fix binary_search
2189 // Revision 1.264 2007/07/15 17:39:42 rurban
2190 // add binary_search. enable memory ps calls
2192 // Revision 1.263 2007/07/14 12:05:29 rurban
2193 // add url field to WikiPageName for interwiki expansion
2195 // Revision 1.262 2007/06/07 17:02:01 rurban
2196 // fix display of pagenames containing ":" in certain lists
2198 // Revision 1.261 2007/06/01 06:37:53 rurban
2199 // use native debug_print_backtrace
2201 // Revision 1.260 2007/02/17 14:15:21 rurban
2202 // fix ImgLink params: $ori_url
2204 // Revision 1.259 2007/01/20 11:41:38 rurban
2205 // WikiPagename::_check: add flatfile support
2207 // Revision 1.258 2007/01/07 18:43:51 rurban
2208 // Remove FileFinder dependency for loadPhpExtension()
2210 // Revision 1.257 2007/01/03 21:24:56 rurban
2211 // Disable noisy ps subprocess on DEBUG. Turn it on explicitly on memory debugging. Add convert_charset helper. Use convert_charset().
2213 // Revision 1.256 2007/01/02 13:23:49 rurban
2214 // ftnt_${footnum}: do not confuse old php string definition parsers. Clarify API: sortby,limit and exclude are strings.
2216 // Revision 1.255 2006/12/22 16:53:38 rurban
2217 // Try to dl() load the iconv extension, if not already loaded
2219 // Revision 1.254 2006/12/02 19:53:05 rurban
2220 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2221 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2224 // Revision 1.253 2006/08/25 22:20:52 rurban
2225 // better split subpages at sep
2227 // Revision 1.252 2006/06/18 11:03:36 rurban
2228 // support rc version
2230 // Revision 1.251 2006/03/19 15:01:00 rurban
2231 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2233 // Revision 1.250 2006/03/07 20:45:44 rurban
2234 // wikihash for php-5.1
2236 // Revision 1.249 2005/10/30 14:24:33 rurban
2237 // move rand_ascii_readable from Captcha to stdlib
2239 // Revision 1.248 2005/10/29 14:18:30 uckelman
2240 // Added is_a() deprecation note.
2242 // Revision 1.247 2005/10/10 20:31:21 rurban
2245 // Revision 1.246 2005/10/10 19:38:48 rurban
2248 // Revision 1.245 2005/09/18 16:01:09 rurban
2249 // trick to send the correct gzipped Content-Length
2251 // Revision 1.244 2005/09/11 13:24:33 rurban
2252 // fix shortname, dont quote twice in ListRegexExpand
2254 // Revision 1.243 2005/08/06 15:01:38 rurban
2255 // workaround php VBASIC alike limitation: allow integer pagenames
2257 // Revision 1.242 2005/08/06 13:07:04 rurban
2258 // quote paths correctly (not the best method though)
2260 // Revision 1.241 2005/05/06 16:54:19 rurban
2261 // support optional EXTERNAL_LINK_TARGET, default: _blank
2263 // Revision 1.240 2005/04/23 11:15:49 rurban
2264 // handle allowed inlined objects within INLINE_IMAGES
2266 // Revision 1.239 2005/04/01 16:11:42 rurban
2269 // Revision 1.238 2005/03/04 16:29:14 rurban
2270 // Fixed bug #994994 (escape / in glob)
2271 // Optimized glob_to_pcre within fileSet() matching.
2273 // Revision 1.237 2005/02/12 17:22:18 rurban
2274 // locale update: missing . : fixed. unified strings
2275 // proper linebreaks
2277 // Revision 1.236 2005/02/08 13:41:32 rurban
2280 // Revision 1.235 2005/02/04 11:54:48 rurban
2283 // Revision 1.234 2005/02/03 05:09:25 rurban
2284 // Talk: + User: fix
2286 // Revision 1.233 2005/02/02 20:40:12 rurban
2287 // fix Talk: and User: names and links
2289 // Revision 1.232 2005/02/02 19:34:09 rurban
2290 // more maps: Talk, User
2292 // Revision 1.231 2005/01/30 19:48:52 rurban
2293 // enable ps memory on unix
2295 // Revision 1.230 2005/01/25 07:10:51 rurban
2296 // add getMemoryUsage to stdlib
2298 // Revision 1.229 2005/01/21 11:51:22 rurban
2301 // Revision 1.228 2005/01/17 20:28:30 rurban
2302 // Allow more pagename chars: Limit only on certain backends.
2303 // Re-Allow : and ; and control chars on non-file backends.
2305 // Revision 1.227 2005/01/14 18:32:08 uckelman
2306 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2307 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2308 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2309 // conversion of '__' into '<strong>', and then unhidden afterwards.
2311 // Revision 1.226 2004/12/26 17:12:06 rurban
2312 // avoid stdargs in url, php5 fixes
2314 // Revision 1.225 2004/12/22 19:02:29 rurban
2315 // fix glob for starting * or ?
2317 // Revision 1.224 2004/12/20 12:11:50 rurban
2318 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2319 // not reproducable other than on sf.net, but this seems to fix it.
2321 // Revision 1.223 2004/12/18 16:49:29 rurban
2322 // fix RPC for !USE_PATH_INFO, add debugging helper
2324 // Revision 1.222 2004/12/17 16:40:45 rurban
2325 // add not yet used url helper
2327 // Revision 1.221 2004/12/06 19:49:58 rurban
2328 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2329 // renamed delete_page to purge_page.
2330 // enable action=edit&version=-1 to force creation of a new version.
2331 // added BABYCART_PATH config
2332 // fixed magiqc in adodb.inc.php
2333 // and some more docs
2335 // Revision 1.220 2004/11/30 17:47:41 rurban
2336 // added mt_srand, check for native isa
2338 // Revision 1.219 2004/11/26 18:39:02 rurban
2339 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2341 // Revision 1.218 2004/11/25 08:28:48 rurban
2344 // Revision 1.217 2004/11/16 17:31:03 rurban
2345 // re-enable old block markup conversion
2347 // Revision 1.216 2004/11/11 18:31:26 rurban
2348 // add simple backtrace on such general failures to get at least an idea where
2350 // Revision 1.215 2004/11/11 14:34:12 rurban
2351 // minor clarifications
2353 // Revision 1.214 2004/11/11 11:01:20 rurban
2354 // fix loadPhpExtension
2356 // Revision 1.213 2004/11/01 10:43:57 rurban
2357 // seperate PassUser methods into seperate dir (memory usage)
2358 // fix WikiUser (old) overlarge data session
2359 // remove wikidb arg from various page class methods, use global ->_dbi instead
2362 // Revision 1.212 2004/10/22 09:15:39 rurban
2363 // Alert::show has no arg anymore
2365 // Revision 1.211 2004/10/22 09:05:11 rurban
2366 // added longer_timeout (HttpClient)
2369 // Revision 1.210 2004/10/14 21:06:02 rurban
2370 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2372 // Revision 1.209 2004/10/14 19:19:34 rurban
2373 // loadsave: check if the dumped file will be accessible from outside.
2374 // and some other minor fixes. (cvsclient native not yet ready)
2376 // Revision 1.208 2004/10/12 13:13:20 rurban
2377 // php5 compatibility (5.0.1 ok)
2379 // Revision 1.207 2004/09/26 12:21:40 rurban
2380 // removed old log entries.
2381 // added persistent start_debug on internal links and DEBUG
2382 // added isExternalReferrer (not yet used)
2384 // Revision 1.206 2004/09/25 16:28:36 rurban
2385 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2387 // Revision 1.205 2004/09/23 13:59:35 rurban
2388 // Before removing a page display a sample of 100 words.
2390 // Revision 1.204 2004/09/17 13:19:15 rurban
2391 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2394 // Revision 1.203 2004/09/16 08:00:52 rurban
2395 // just some comments
2397 // Revision 1.202 2004/09/14 10:11:44 rurban
2398 // start 2nd Id with ...Plugin2
2400 // Revision 1.201 2004/09/14 10:06:42 rurban
2401 // generate iterated plugin ids, set plugin span id also
2403 // Revision 1.200 2004/08/05 17:34:26 rurban
2404 // move require to sortby branch
2406 // Revision 1.199 2004/08/05 10:38:15 rurban
2407 // fix Bug #993692: Making Snapshots or Backups doesn't work anymore
2410 // Revision 1.198 2004/07/02 10:30:36 rurban
2411 // always disable getimagesize for < php-4.3 with external png's
2413 // Revision 1.197 2004/07/02 09:55:58 rurban
2414 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2416 // Revision 1.196 2004/07/01 08:51:22 rurban
2417 // dumphtml: added exclude, print pagename before processing
2419 // Revision 1.195 2004/06/29 08:52:22 rurban
2420 // Use ...version() $need_content argument in WikiDB also:
2421 // To reduce the memory footprint for larger sets of pagelists,
2422 // we don't cache the content (only true or false) and
2423 // we purge the pagedata (_cached_html) also.
2424 // _cached_html is only cached for the current pagename.
2425 // => Vastly improved page existance check, ACL check, ...
2427 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2429 // Revision 1.194 2004/06/29 06:48:04 rurban
2430 // Improve LDAP auth and GROUP_LDAP membership:
2431 // no error message on false password,
2432 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2433 // fixed two group queries (this -> user)
2434 // stdlib: ConvertOldMarkup still flawed
2436 // Revision 1.193 2004/06/28 13:27:03 rurban
2437 // CreateToc disabled for old markup and Apache2 only
2439 // Revision 1.192 2004/06/28 12:47:43 rurban
2440 // skip if non-DEBUG and old markup with CreateToc
2442 // Revision 1.191 2004/06/25 14:31:56 rurban
2443 // avoid debug_skip warning
2445 // Revision 1.190 2004/06/25 14:29:20 rurban
2446 // WikiGroup refactoring:
2447 // global group attached to user, code for not_current user.
2448 // improved helpers for special groups (avoid double invocations)
2449 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2450 // fixed a XHTML validation error on userprefs.tmpl
2452 // Revision 1.189 2004/06/20 09:45:35 rurban
2453 // php5 isa fix (wrong strtolower)
2455 // Revision 1.188 2004/06/16 10:38:58 rurban
2456 // Disallow refernces in calls if the declaration is a reference
2457 // ("allow_call_time_pass_reference clean").
2458 // PhpWiki is now allow_call_time_pass_reference = Off clean,
2459 // but several external libraries may not.
2460 // In detail these libs look to be affected (not tested):
2464 // Revision 1.187 2004/06/14 11:31:37 rurban
2465 // renamed global $Theme to $WikiTheme (gforge nameclash)
2466 // inherit PageList default options from PageList
2467 // default sortby=pagename
2468 // use options in PageList_Selectable (limit, sortby, ...)
2469 // added action revert, with button at action=diff
2470 // added option regex to WikiAdminSearchReplace
2472 // Revision 1.186 2004/06/13 13:54:25 rurban
2473 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2474 // FoafViewer: Check against external requirements, instead of fatal.
2475 // Change output for xhtmldumps: using file:// urls to the local fs.
2476 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2477 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2479 // Revision 1.185 2004/06/11 09:07:30 rurban
2480 // support theme-specific LinkIconAttr: front or after or none
2482 // Revision 1.184 2004/06/04 20:32:53 rurban
2483 // Several locale related improvements suggested by Pierrick Meignen
2484 // LDAP fix by John Cole
2485 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2487 // Revision 1.183 2004/06/01 10:22:56 rurban
2488 // added url_get_contents() used in XmlParser and elsewhere
2490 // Revision 1.182 2004/05/25 12:40:48 rurban
2491 // trim the pagename
2493 // Revision 1.181 2004/05/25 10:18:44 rurban
2494 // Check for UTF-8 URLs; Internet Explorer produces these if you
2495 // type non-ASCII chars in the URL bar or follow unescaped links.
2496 // Fixes sf.net bug #953949
2497 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2499 // Revision 1.180 2004/05/18 16:23:39 rurban
2500 // rename split_pagename to SplitPagename
2502 // Revision 1.179 2004/05/18 16:18:37 rurban
2503 // AutoSplit at subpage seperators
2504 // RssFeed stability fix for empty feeds or broken connections
2506 // Revision 1.178 2004/05/12 10:49:55 rurban
2507 // require_once fix for those libs which are loaded before FileFinder and
2508 // its automatic include_path fix, and where require_once doesn't grok
2509 // dirname(__FILE__) != './lib'
2510 // upgrade fix with PearDB
2511 // navbar.tmpl: remove spaces for IE button alignment
2513 // Revision 1.177 2004/05/08 14:06:12 rurban
2514 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2515 // minor stability and portability fixes
2517 // Revision 1.176 2004/05/08 11:25:15 rurban
2520 // Revision 1.175 2004/05/06 17:30:38 rurban
2521 // CategoryGroup: oops, dos2unix eol
2522 // improved phpwiki_version:
2523 // pre -= .0001 (1.3.10pre: 1030.099)
2524 // -p1 += .001 (1.3.9-p1: 1030.091)
2525 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2526 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2527 // backend->backendType(), backend->database(),
2528 // backend->listOfFields(),
2529 // backend->listOfTables(),
2531 // Revision 1.174 2004/05/06 12:02:05 rurban
2532 // fix sf.net bug#949002: [ Link | ] assertion
2534 // Revision 1.173 2004/05/03 15:00:31 rurban
2535 // added more database upgrading: session.sess_ip, page.id autp_increment
2537 // Revision 1.172 2004/04/26 20:44:34 rurban
2538 // locking table specific for better databases
2540 // Revision 1.171 2004/04/19 23:13:03 zorloc
2541 // Connect the rest of PhpWiki to the IniConfig system. Also the keyword regular expression is not a config setting
2543 // Revision 1.170 2004/04/19 18:27:45 rurban
2544 // Prevent from some PHP5 warnings (ref args, no :: object init)
2545 // php5 runs now through, just one wrong XmlElement object init missing
2546 // Removed unneccesary UpgradeUser lines
2547 // Changed WikiLink to omit version if current (RecentChanges)
2549 // Revision 1.169 2004/04/15 21:29:48 rurban
2550 // allow [0] with new markup: link to page "0"
2552 // Revision 1.168 2004/04/10 02:30:49 rurban
2553 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2554 // Fixed "cannot setlocale..." (sf.net problem)
2556 // Revision 1.167 2004/04/02 15:06:55 rurban
2557 // fixed a nasty ADODB_mysql session update bug
2558 // improved UserPreferences layout (tabled hints)
2559 // fixed UserPreferences auth handling
2560 // improved auth stability
2561 // improved old cookie handling: fixed deletion of old cookies with paths
2563 // Revision 1.166 2004/04/01 15:57:10 rurban
2564 // simplified Sidebar theme: table, not absolute css positioning
2565 // added the new box methods.
2566 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2568 // Revision 1.165 2004/03/24 19:39:03 rurban
2569 // php5 workaround code (plus some interim debugging code in XmlElement)
2570 // php5 doesn't work yet with the current XmlElement class constructors,
2571 // WikiUserNew does work better than php4.
2572 // rewrote WikiUserNew user upgrading to ease php5 update
2573 // fixed pref handling in WikiUserNew
2574 // added Email Notification
2575 // added simple Email verification
2576 // removed emailVerify userpref subclass: just a email property
2577 // changed pref binary storage layout: numarray => hash of non default values
2578 // print optimize message only if really done.
2579 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2580 // prefs should be stored in db or homepage, besides the current session.
2582 // Revision 1.164 2004/03/18 21:41:09 rurban
2583 // fixed sqlite support
2584 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2586 // Revision 1.163 2004/03/17 18:41:49 rurban
2587 // just reformatting
2589 // Revision 1.162 2004/03/16 15:43:08 rurban
2590 // make fileSet sortable to please PageList
2592 // Revision 1.161 2004/03/12 15:48:07 rurban
2593 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2594 // simplified lib/stdlib.php:explodePageList
2596 // Revision 1.160 2004/02/28 21:14:08 rurban
2597 // generally more PHPDOC docs
2598 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2599 // fxied WikiUserNew pref handling: empty theme not stored, save only
2600 // changed prefs, sql prefs improved, fixed password update,
2601 // removed REPLACE sql (dangerous)
2602 // moved gettext init after the locale was guessed
2603 // + some minor changes
2606 // (c-file-style: "gnu")
2610 // c-basic-offset: 4
2611 // c-hanging-comment-ender-p: nil
2612 // indent-tabs-mode: nil