1 <?php //rcs_id('$Id$');
3 Copyright 1999-2008 $ThePhpWikiProgrammingTeam
5 This file is part of PhpWiki.
7 PhpWiki is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 PhpWiki is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with PhpWiki; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 Standard functions for Wiki functionality
24 WikiURL ($pagename, $args, $get_abs_url)
26 IconForLink ($protocol_or_url)
27 PossiblyGlueIconToText($proto_or_url, $text)
29 LinkURL ($url, $linktext)
30 LinkImage ($url, $alt)
31 ImgObject ($img, $url)
33 SplitQueryArgs ($query_args)
34 LinkPhpwikiURL ($url, $text, $basepage)
35 ConvertOldMarkup ($content, $markup_type = "block")
36 MangleXmlIdentifier($str)
37 UnMangleXmlIdentifier($str)
39 class Stack { push($item), pop(), cnt(), top() }
40 class Alert { show() }
41 class WikiPageName {getParent(),isValid(),getWarnings() }
43 expand_tabs($str, $tab_width = 8)
45 NoSuchRevision ($request, $page, $version)
46 TimezoneOffset ($time, $no_colon)
47 Iso8601DateTime ($time)
48 Rfc2822DateTime ($time)
49 ParseRfc1123DateTime ($timestr)
51 ByteFormatter ($bytes = 0, $longformat = false)
54 __vsprintf ($fmt, $args)
56 file_mtime ($filename)
57 sort_file_mtime ($a, $b)
58 class fileSet {fileSet($directory, $filepattern = false),
59 getFiles($exclude='', $sortby='', $limit='') }
60 class ListRegexExpand { listMatchCallback($item, $key),
61 expandRegex ($index, &$pages) }
64 glob_match ($glob, $against, $case_sensitive = true)
65 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
66 explodePageList ($input, $perm = false)
68 can ($object, $method)
69 function_usable ($function_name)
71 better_srand ($seed = '')
74 subPageSlice ($pagename, $pos)
78 obj2hash ($obj, $exclude = false, $fields = false)
81 url_get_contents ($uri)
83 firstNWordsOfContent ($n, $content)
84 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
87 charset_convert($from, $to, $data)
89 function: LinkInterWikiLink($link, $linktext)
90 moved to: lib/interwiki.php
91 function: linkExistingWikiWord($wikiword, $linktext, $version)
92 moved to: lib/WikiTheme.php
93 function: LinkUnknownWikiWord($wikiword, $linktext)
94 moved to: lib/WikiTheme.php
95 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
96 gone see: lib/plugin/RecentChanges.php
98 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
99 else define('_PHPWIKI_STDLIB_LOADED', true);
101 define('MAX_PAGENAME_LENGTH', 100);
104 * Convert string to a valid XML identifier.
106 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
108 * We would like to have, e.g. named anchors within wiki pages
109 * names like "Table of Contents" --- clearly not a valid XML
110 * fragment identifier.
112 * This function implements a one-to-one map from {any string}
113 * to {valid XML identifiers}.
116 * converting all bytes not in [A-Za-z0-9:_-],
117 * and any leading byte not in [A-Za-z] to 'xbb.',
118 * where 'bb' is the hexadecimal representation of the
121 * As a special case, the empty string is converted to 'empty.'
126 function MangleXmlIdentifier($str) {
130 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
131 "'x' . sprintf('%02x', ord('\\0')) . '.'",
135 function UnMangleXmlIdentifier($str) {
136 if ($str == 'empty.')
138 return preg_replace('/x(\w\w)\./e',
139 "sprintf('%c', hex('\\0'))",
144 * Returns a name for the WIKI_ID cookie that should be unique on the host.
145 * But for it to be unique you must have set a unique WIKI_NAME in your
146 * configuration file.
147 * @return string The name of the WIKI_ID cookie to use for this wiki.
149 function GetCookieName() {
150 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
154 * Generates a valid URL for a given Wiki pagename.
155 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
156 * If a WikiDB_Page object function will extract the name to link to.
157 * If a WikiDB_PageRevision object function will extract the name to link to.
159 * @param boolean $get_abs_url Default value is false.
160 * @return string The absolute URL to the page passed as $pagename.
162 function WikiURL($pagename, $args = '', $get_abs_url = false) {
163 global $request, $WikiTheme;
166 if (is_object($pagename)) {
167 if (isa($pagename, 'WikiDB_Page')) {
168 $pagename = $pagename->getName();
170 elseif (isa($pagename, 'WikiDB_PageRevision')) {
171 $page = $pagename->getPage();
172 $args['version'] = $pagename->getVersion();
173 $pagename = $page->getName();
175 elseif (isa($pagename, 'WikiPageName')) {
176 $anchor = $pagename->anchor;
177 $pagename = $pagename->name;
179 $anchor = $pagename->anchor;
180 $pagename = $pagename->name;
183 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
185 $args = 'start_debug=' . $request->getArg('start_debug');
186 elseif (is_array($args))
187 $args['start_debug'] = $request->getArg('start_debug');
189 $args .= '&start_debug=' . $request->getArg('start_debug');
191 if (is_array($args)) {
193 foreach ($args as $key => $val) {
194 // avoid default args
195 if (USE_PATH_INFO and $key == 'pagename')
197 elseif ($key == 'action' and $val == 'browse')
199 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
200 $enc_args[] = urlencode($key) . '=' . urlencode($val);
202 $args = join('&', $enc_args);
205 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
206 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
207 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
209 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
210 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
211 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
214 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
216 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
226 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
227 $url .= "?pagename=" . rawurlencode($pagename);
232 $url .= "#" . MangleXmlIdentifier($anchor);
236 /** Convert relative URL to absolute URL.
238 * This converts a relative URL to one of PhpWiki's support files
239 * to an absolute one.
242 * @return string Absolute URL
244 function AbsoluteURL ($url) {
245 if (preg_match('/^https?:/', $url))
247 if ($url[0] != '/') {
248 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
249 while ($base != '/' and substr($url, 0, 3) == "../") {
250 $url = substr($url, 3);
251 $base = dirname($base);
257 return SERVER_URL . $url;
260 function DataURL ($url) {
261 if (preg_match('/^https?:/', $url))
263 $url = NormalizeWebFileName($url);
264 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
265 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
266 return AbsoluteURL($url);
270 * Generates icon in front of links.
272 * @param string $protocol_or_url URL or protocol to determine which icon to use.
274 * @return HtmlElement HtmlElement object that contains data to create img link to
275 * icon for use with url or protocol passed to the function. False if no img to be
278 function IconForLink($protocol_or_url) {
280 if (0 and $filename_suffix == false) {
281 // display apache style icon for file type instead of protocol icon
282 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
283 // - document: html, htm, text, txt, rtf, pdf, doc
284 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
285 // - audio: mp3,mp2,aiff,aif,au
286 // - multimedia: mpeg,mpg,mov,qt
288 list ($proto) = explode(':', $protocol_or_url, 2);
289 $src = $WikiTheme->getLinkIconURL($proto);
291 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
298 * Glue icon in front of or after text.
299 * Pref: 'noLinkIcons' - ignore icon if set
300 * WikiTheme: 'LinkIcons' - 'yes' at front
301 * - 'no' display no icon
302 * - 'front' display at left
303 * - 'after' display at right
305 * @param string $protocol_or_url Protocol or URL. Used to determine the
307 * @param string $text The text.
308 * @return XmlContent.
310 function PossiblyGlueIconToText($proto_or_url, $text) {
311 global $request, $WikiTheme;
312 if ($request->getPref('noLinkIcons'))
314 $icon = IconForLink($proto_or_url);
317 if ($where = $WikiTheme->getLinkIconAttr()) {
318 if ($where == 'no') return $text;
319 if ($where != 'after') $where = 'front';
323 if ($where == 'after') {
324 // span the icon only to the last word (tie them together),
325 // to let the previous words wrap on line breaks.
326 if (!is_object($text)) {
327 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
328 list (, $prefix, $last_word) = $m;
334 $text = HTML::span(array('style' => 'white-space: nowrap'),
335 $last_word, HTML::Raw(' '), $icon);
337 $text = HTML($prefix, $text);
340 // span the icon only to the first word (tie them together),
341 // to let the next words wrap on line breaks
342 if (!is_object($text)) {
343 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
344 list (, $first_word, $tail) = $m;
350 $text = HTML::span(array('style' => 'white-space: nowrap'),
353 $text = HTML($text, $tail);
358 * Determines if the url passed to function is safe, by detecting if the characters
359 * '<', '>', or '"' are present.
360 * Check against their urlencoded values also.
362 * @param string $url URL to check for unsafe characters.
363 * @return boolean True if same, false else.
365 function IsSafeURL($url) {
366 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
370 * Generates an HtmlElement object to store data for a link.
372 * @param string $url URL that the link will point to.
373 * @param string $linktext Text to be displayed as link.
374 * @return HtmlElement HtmlElement object that contains data to construct an html link.
376 function LinkURL($url, $linktext = '') {
377 // FIXME: Is this needed (or sufficient?)
378 if(! IsSafeURL($url)) {
379 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
380 _("BAD URL -- remove all of <, >, \"")));
384 $linktext = preg_replace("/mailto:/A", "", $url);
385 $args = array('href' => $url);
386 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
387 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
388 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
390 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
397 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
398 * Disallows sizes which are too small.
399 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
401 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
403 function LinkImage($url, $alt = false) {
404 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
405 // Disallow tags in img src urls. Typical CSS attacks.
406 // FIXME: Is this needed (or sufficient?)
407 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
409 if(! IsSafeURL($url)) {
410 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
411 _("BAD URL -- remove all of <, >, \"")));
414 // support new syntax: [prefix/image.jpg size=50% border=n]
415 //if (!preg_match("/\.(".$force_img.")/i", $url))
416 if (empty($alt)) $alt = basename($url);
417 $arr = split(' ',$url);
418 $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
419 if (count($arr) > 1) {
422 foreach ($arr as $attr) {
423 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
424 $link->setAttr('width',$m[1]);
425 $link->setAttr('height',$m[1]);
427 elseif (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
428 $link->setAttr('width',$m[1]);
429 $link->setAttr('height',$m[2]);
431 elseif (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
432 $link->setAttr('width',$m[1]);
433 elseif (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
434 $link->setAttr('height',$m[1]);
435 elseif (preg_match('/^border=(\d+)$/',$attr,$m))
436 $link->setAttr('border',$m[1]);
437 elseif (preg_match('/^align=(\w+)$/',$attr,$m))
438 $link->setAttr('align',$m[1]);
439 elseif (preg_match('/^hspace=(\d+)$/',$attr,$m))
440 $link->setAttr('hspace',$m[1]);
441 elseif (preg_match('/^vspace=(\d+)$/',$attr,$m))
442 $link->setAttr('vspace',$m[1]);
445 if(! IsSafeURL($url)) {
446 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
447 _("BAD URL -- remove all of <, >, \"")));
450 $link->setAttr('src', $url);
455 // Check width and height as spam countermeasure
456 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
457 //$width = (int) $width; // px or % or other suffix
458 //$height = (int) $height;
459 if (($width < 3 and $height < 10) or
460 ($height < 3 and $width < 20) or
461 ($height < 7 and $width < 7))
463 trigger_error(_("Invalid image size"), E_USER_WARNING);
468 // Prepare for getimagesize($url)
469 // $url only valid for external urls, otherwise local path
470 // Older php versions crash here with certain png's:
471 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
472 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
473 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
474 if (DISABLE_GETIMAGESIZE)
476 elseif (! preg_match("/\.$force_img$/i", $url))
477 ; // only valid image extensions or scripts assumed to generate images
478 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
479 ; // it's safe to assume that this will fail.
480 elseif (preg_match("/^http/",$url)) { // external url
481 $size = @getimagesize($url);
482 } else { // local file
483 if (file_exists($file = NormalizeLocalFileName($url))) { // here
484 $size = @getimagesize($file);
485 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
486 $size = @getimagesize($file);
487 $link->setAttr('src', rawurldecode($url));
488 } elseif (string_starts_with($url, getUploadDataPath())) { // there
489 $file = substr($file, strlen(getUploadDataPath()));
490 $size = @getimagesize(getUploadFilePath().rawurldecode($file));
491 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
492 } else { // elsewhere
493 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
499 if (($width < 3 and $height < 10)
500 or ($height < 3 and $width < 20)
501 or ($height < 7 and $width < 7))
503 trigger_error(_("Invalid image size"), E_USER_WARNING);
509 $link->setAttr('class', 'inlineimage');
511 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
512 * png|jpg|gif|jpeg|bmp|pl|cgi
513 * Note: Allow cgi's (pl,cgi) returning images.
515 if (!preg_match("/\.(".$force_img.")/i", $url)) {
516 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
517 // => HTML::object(array('src' => $url)) ...;
518 return ImgObject($link, $ori_url);
524 * <object> / <embed> tags instead of <img> for all non-image extensions
526 * Called by LinkImage(), not directly.
527 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
528 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
529 * $alt may be an alternate img
530 * TODO: Need to unify with WikiPluginCached::embedObject()
532 * Note that Safari 1.0 will crash with <object>, so use only <embed>
533 * http://www.alleged.org.uk/pdc/2002/svg-object.html
535 * Allowed object tags:
536 * DATA=URI (object data)
537 * CLASSID=URI (location of implementation)
538 * ARCHIVE=CDATA (archive files)
539 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
540 * WIDTH=Length (object width)
541 * HEIGHT=Length (object height)
542 * NAME=CDATA (name for form submission)
543 * USEMAP=URI (client-side image map)
544 * TYPE=ContentType (content-type of object)
545 * CODETYPE=ContentType (content-type of code)
546 * STANDBY=Text (message to show while loading)
547 * TABINDEX=NUMBER (position in tabbing order)
548 * DECLARE (do not instantiate object)
549 * The rest is added as <param name="" value="" /> tags
551 function ImgObject($img, $url) {
552 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
553 $args = split(' ', $url);
555 if (count($args) >= 1) {
556 $url = array_shift($args);
558 foreach ($args as $attr) {
559 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
560 "codetype,standby,tabindex,declare") as $param)
562 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
563 $img->setAttr($param, $m[1]);
569 // now all remaing args are added as <param> to the object
570 foreach ($args as $attr) {
571 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
572 $params[] = HTML::param(array('name' => $m[1],
577 $type = $img->getAttr('type');
579 // TODO: map extension to mime-types if type is not given and php < 4.3
580 if (function_exists('mime_content_type'))
581 $type = mime_content_type($url);
583 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
585 $object->setAttr('class', 'inlineobject');
587 foreach ($params as $param) $object->pushContent($param);
589 if (isBrowserSafari()) {
590 return HTML::embed($object->_attr, $object->_content);
592 $object->pushContent(HTML::embed($object->_attr));
599 // var in php5 deprecated
601 $this->items = array();
604 function push($item) {
605 $this->items[$this->size] = $item;
611 if ($this->size == 0) {
612 return false; // stack is empty
615 return $this->items[$this->size];
624 return $this->items[$this->size - 1];
630 // end class definition
632 function SplitQueryArgs ($query_args = '')
634 // FIXME: use the arg-seperator which might not be &
635 $split_args = split('&', $query_args);
637 while (list($key, $val) = each($split_args))
638 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
639 $args[$m[1]] = $m[2];
643 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
646 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
647 return HTML::strong(array('class' => 'rawurl'),
648 HTML::u(array('class' => 'baduri'),
649 _("BAD phpwiki: URL")));
653 $pagename = urldecode($m[1]);
656 if (empty($pagename) &&
657 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
658 // Convert old style links (to not break diff links in
660 $pagename = urldecode($m[2]);
661 $args = array("action" => $m[1]);
664 $args = SplitQueryArgs($qargs);
667 if (empty($pagename))
668 $pagename = $GLOBALS['request']->getArg('pagename');
670 if (isset($args['action']) && $args['action'] == 'browse')
671 unset($args['action']);
674 if (empty($args['action']))
676 else if (is_safe_action($args['action']))
677 $class = 'wikiaction';
679 if (empty($args['action']) || is_safe_action($args['action']))
680 $class = 'wikiaction';
682 // Don't allow administrative links on unlocked pages.
683 $dbi = $GLOBALS['request']->getDbh();
684 $page = $dbi->getPage($basepage ? $basepage : $pagename);
685 if (!$page->get('locked'))
686 return HTML::span(array('class' => 'wikiunsafe'),
687 HTML::u(_("Lock page to enable link")));
688 $class = 'wikiadmin';
692 $text = HTML::span(array('class' => 'rawurl'), $url);
694 $wikipage = new WikiPageName($pagename);
695 if (!$wikipage->isValid()) {
697 return $WikiTheme->linkBadWikiWord($wikipage, $url);
700 return HTML::a(array('href' => WikiURL($pagename, $args),
706 * A class to assist in parsing wiki pagenames.
708 * Now with subpages and anchors, parsing and passing around
709 * pagenames is more complicated. This should help.
713 /** Short name for page.
715 * This is the value of $name passed to the constructor.
716 * (For use, e.g. as a default label for links to the page.)
720 /** The full page name.
722 * This is the full name of the page (without anchor).
728 * This is the referenced anchor within the page, or the empty string.
734 * @param mixed $name Page name.
735 * WikiDB_Page, WikiDB_PageRevision, or string.
736 * This can be a relative subpage name (like '/SubPage'),
737 * or can be the empty string to refer to the $basename.
739 * @param string $anchor For links to anchors in page.
741 * @param mixed $basename Page name from which to interpret
742 * relative or other non-fully-specified page names.
744 function WikiPageName($name, $basename=false, $anchor=false) {
745 if (is_string($name)) {
746 $this->shortName = $name;
747 if (strstr($name, ':')) {
748 list($moniker, $shortName) = split (":", $name, 2);
749 $map = getInterwikiMap(); // allow overrides to custom maps
750 if (isset($map->_map[$moniker])) {
751 $url = $map->_map[$moniker];
752 if (strstr($url, '%s'))
753 $url = sprintf($url, $shortName);
757 // expand Talk or User, but not to absolute urls!
758 if (strstr($url, '//')) {
759 if ($moniker == 'Talk')
760 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
761 elseif ($moniker == 'User')
766 if (strstr($shortName, '?')) {
767 list($shortName, $dummy) = split("\?", $shortName, 2);
769 $this->shortName = $shortName;
772 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
773 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
775 $name = $this->_pagename($basename) . $name;
777 $name = $this->_normalize_bad_pagename($name);
778 $this->shortName = $name;
783 $name = $this->_pagename($name);
784 $this->shortName = $name;
787 $this->name = $this->_check($name);
788 $this->anchor = (string)$anchor;
795 function getParent() {
797 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
799 return substr($name, 0, -strlen($tail));
802 function isValid($strict = false) {
804 return !isset($this->_errors);
805 return (is_string($this->name) and $this->name != '');
808 function getWarnings() {
810 if (isset($this->_warnings))
811 $warnings = array_merge($warnings, $this->_warnings);
812 if (isset($this->_errors))
813 $warnings = array_merge($warnings, $this->_errors);
817 return sprintf(_("'%s': Bad page name: %s"),
818 $this->shortName, join(', ', $warnings));
821 function _pagename($page) {
822 if (isa($page, 'WikiDB_Page'))
823 return $page->getName();
824 elseif (isa($page, 'WikiDB_PageRevision'))
825 return $page->getPageName();
826 elseif (isa($page, 'WikiPageName'))
828 // '0' or e.g. '1984' should be allowed though
829 if (!is_string($page) and !is_integer($page)) {
830 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
831 $page, gettype($page), get_class($page)),
834 //assert(is_string($page));
838 function _normalize_bad_pagename($name) {
839 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
841 // Punt... You really shouldn't get here.
844 return $request->getArg('pagename');
846 assert($name[0] == SUBPAGE_SEPARATOR);
847 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
848 return substr($name, 1);
852 * Compress internal white-space to single space character.
854 * This leads to problems with loading a foreign charset pagename,
855 * which cannot be deleted anymore, because unknown chars are compressed.
856 * So BEFORE importing a file _check must be done !!!
858 function _check($pagename) {
859 // Compress internal white-space to single space character.
860 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
861 if ($pagename != $orig)
862 $this->_warnings[] = _("White space converted to single space");
864 // Delete any control characters.
865 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
866 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
867 if ($pagename != $orig)
868 $this->_errors[] = _("Control characters not allowed");
871 // Strip leading and trailing white-space.
872 $pagename = trim($pagename);
875 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
876 $pagename = substr($pagename, 1);
877 if ($pagename != $orig)
878 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
880 // ";" is urlencoded, so safe from php arg-delim problems
881 /*if (strstr($pagename, ';')) {
882 $this->_warnings[] = _("';' is deprecated");
883 $pagename = str_replace(';', '', $pagename);
886 // not only for SQL, also to restrict url length
887 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
888 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
889 $this->_errors[] = _("too long");
892 // disallow some chars only on file and cvs
893 if ((DATABASE_TYPE == 'cvs'
894 or DATABASE_TYPE == 'file'
895 or DATABASE_TYPE == 'flatfile')
896 and preg_match('/(:|\.\.)/', $pagename, $m))
898 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
899 $pagename = str_replace('..', '', $pagename);
900 $pagename = str_replace(':', '', $pagename);
908 * Convert old page markup to new-style markup.
910 * @param string $text Old-style wiki markup.
912 * @param string $markup_type
914 * <dt><code>"block"</code> <dd>Convert all markup.
915 * <dt><code>"inline"</code> <dd>Convert only inline markup.
916 * <dt><code>"links"</code> <dd>Convert only link markup.
919 * @return string New-style wiki markup.
921 * @bugs Footnotes don't work quite as before (esp if there are
922 * multiple references to the same footnote. But close enough,
923 * probably for now....
924 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
925 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
926 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
927 * also known to crash, even with Apache1.
929 function ConvertOldMarkup ($text, $markup_type = "block") {
935 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
936 // AnciennesR%E8glesDeFormatage crashes.
937 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
938 // also known to crash, even with Apache1.
940 // I suspect this only to crash with Apache2 and IIS.
941 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
942 and preg_match("/plugin CreateToc/", $text))
944 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
945 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
946 ._("Skipped."), E_USER_WARNING);
948 //if (!DEBUG) return $text;
953 /*****************************************************************
954 * Conversions for inline markup:
961 // escape escaped brackets
965 // change ! escapes to ~'s.
966 global $WikiNameRegexp, $request;
967 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
968 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
969 if (check_php_version(4,3,9)) {
970 $map = getInterwikiMap();
971 if ($map_regex = $map->getRegexp())
972 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
974 $bang_esc[] = $WikiNameRegexp;
975 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
978 $subs["links"] = array($orig, $repl);
980 // Temporarily URL-encode pairs of underscores in links to hide
981 // them from the re for bold markup.
982 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
983 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
986 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
989 // Convert footnote references.
990 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
991 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
993 // Convert old style emphases to HTML style emphasis.
994 $orig[] = '/__(.*?)__/';
995 $repl[] = '<strong>\\1</strong>';
996 $orig[] = "/''(.*?)''/";
997 $repl[] = '<em>\\1</em>';
999 // Escape nestled markup.
1000 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1003 // in old markup headings only allowed at beginning of line
1007 // Convert URL-encoded pairs of underscores in links back to
1008 // real underscores after bold markup has been converted.
1009 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1010 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1012 $subs["inline"] = array($orig, $repl);
1014 /*****************************************************************
1015 * Patterns which match block markup constructs which take
1016 * special handling...
1020 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1022 $blockpats[] = '\|(?:.*\n\|)*';
1025 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1027 // Footnote definitions
1028 $blockpats[] = '\[\s*(\d+)\s*\]';
1032 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1036 $blockpats[] = '!{1,3}[^!]';
1038 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1039 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1041 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1042 . join("|", $blockpats)
1047 if ($markup_type != "block") {
1048 list ($orig, $repl) = $subs[$markup_type];
1049 return preg_replace($orig, $repl, $text);
1052 list ($orig, $repl) = $subs['inline'];
1055 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1056 // AnciennesR%E8glesDeFormatage and more
1057 // See http://www.pcre.org/pcre.txt LIMITATIONS
1058 while (preg_match($block_re, $text, $m)) {
1059 $text = substr($text, strlen($m[0]));
1060 list (,$leading_text, $block) = $m;
1063 if (strchr(" \t", $block[0])) {
1065 $prefix = "<pre>\n";
1066 $suffix = "\n</pre>\n";
1068 elseif ($block[0] == '|') {
1070 $prefix = "<?plugin OldStyleTable\n";
1073 elseif (strchr("#*;", $block[0])) {
1074 // Old-style list item
1075 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1076 list (,$ind,$bullet) = $m;
1077 $block = substr($block, strlen($m[0]));
1079 $indent = str_repeat(' ', strlen($ind));
1080 if ($bullet[0] == ';') {
1081 //$term = ltrim(substr($bullet, 1));
1082 //return $indent . $term . "\n" . $indent . ' ';
1083 $prefix = $ind . $bullet;
1086 $prefix = $indent . $bullet . ' ';
1088 elseif ($block[0] == '[') {
1089 // Footnote definition
1090 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1092 $block = substr($block, strlen($m[0]));
1093 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1095 elseif ($block[0] == '<') {
1097 // HACK: no inline markup...
1101 elseif ($block[0] == '!') {
1103 preg_match('/^!{1,3}/', $block, $m);
1105 $block = substr($block, strlen($m[0]));
1111 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1112 if ($block) $block = preg_replace($orig, $repl, $block);
1113 $out .= $leading_text;
1118 return $out . preg_replace($orig, $repl, $text);
1124 * Expand tabs in string.
1126 * Converts all tabs to (the appropriate number of) spaces.
1128 * @param string $str
1129 * @param integer $tab_width
1132 function expand_tabs($str, $tab_width = 8) {
1133 $split = split("\t", $str);
1134 $tail = array_pop($split);
1136 foreach ($split as $hunk) {
1138 $pos = strlen(strrchr($expanded, "\n")) - 1;
1139 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1141 return substr($expanded, 1) . $tail;
1145 * Split WikiWords in page names.
1147 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1148 * places like page titles. This is rumored to help search engines
1151 * @param $page string The page name.
1153 * @return string The split name.
1155 function SplitPagename ($page) {
1157 if (preg_match("/\s/", $page))
1158 return $page; // Already split --- don't split any more.
1160 // This algorithm is specialized for several languages.
1161 // (Thanks to Pierrick MEIGNEN)
1162 // Improvements for other languages welcome.
1165 // This mess splits between a lower-case letter followed by
1166 // either an upper-case or a numeral; except that it wont
1167 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1168 switch ($GLOBALS['LANG']) {
1173 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1176 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1179 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1180 // This the single-letter words 'I' and 'A' from any following
1181 // capitalized words.
1182 switch ($GLOBALS['LANG']) {
1184 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1187 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1190 // Split numerals from following letters.
1191 $RE[] = '/(\d)([[:alpha:]])/';
1192 // Split at subpage seperators. TBD in WikiTheme.php
1193 $RE[] = "/([^${sep}]+)(${sep})/";
1194 $RE[] = "/(${sep})([^${sep}]+)/";
1196 foreach ($RE as $key)
1197 $RE[$key] = pcre_fix_posix_classes($key);
1200 foreach ($RE as $regexp) {
1201 $page = preg_replace($regexp, '\\1 \\2', $page);
1206 function NoSuchRevision (&$request, $page, $version) {
1207 $html = HTML(HTML::h2(_("Revision Not Found")),
1208 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1209 $version, WikiLink($page, 'auto'))));
1210 include_once('lib/Template.php');
1211 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1217 * Get time offset for local time zone.
1219 * @param $time time_t Get offset for this time. Default: now.
1220 * @param $no_colon boolean Don't put colon between hours and minutes.
1221 * @return string Offset as a string in the format +HH:MM.
1223 function TimezoneOffset ($time = false, $no_colon = false) {
1224 if ($time === false)
1226 $secs = date('Z', $time);
1235 $colon = $no_colon ? '' : ':';
1236 $mins = intval(($secs + 30) / 60);
1237 return sprintf("%s%02d%s%02d",
1238 $sign, $mins / 60, $colon, $mins % 60);
1243 * Format time in ISO-8601 format.
1245 * @param $time time_t Time. Default: now.
1246 * @return string Date and time in ISO-8601 format.
1248 function Iso8601DateTime ($time = false) {
1249 if ($time === false)
1251 $tzoff = TimezoneOffset($time);
1252 $date = date('Y-m-d', $time);
1253 $time = date('H:i:s', $time);
1254 return $date . 'T' . $time . $tzoff;
1258 * Format time in RFC-2822 format.
1260 * @param $time time_t Time. Default: now.
1261 * @return string Date and time in RFC-2822 format.
1263 function Rfc2822DateTime ($time = false) {
1264 if ($time === false)
1266 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1270 * Format time in RFC-1123 format.
1272 * @param $time time_t Time. Default: now.
1273 * @return string Date and time in RFC-1123 format.
1275 function Rfc1123DateTime ($time = false) {
1276 if ($time === false)
1278 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1281 /** Parse date in RFC-1123 format.
1283 * According to RFC 1123 we must accept dates in the following
1286 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1287 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1288 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1290 * (Though we're only allowed to generate dates in the first format.)
1292 function ParseRfc1123DateTime ($timestr) {
1293 $timestr = trim($timestr);
1294 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1295 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1297 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1299 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1300 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1302 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1303 if ($year < 70) $year += 2000;
1304 elseif ($year < 100) $year += 1900;
1306 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1307 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1309 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1316 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1318 return false; // failed
1323 * Format time to standard 'ctime' format.
1325 * @param $time time_t Time. Default: now.
1326 * @return string Date and time.
1328 function CTime ($time = false)
1330 if ($time === false)
1332 return date("D M j H:i:s Y", $time);
1337 * Format number as kilobytes or bytes.
1338 * Short format is used for PageList
1339 * Long format is used in PageInfo
1341 * @param $bytes int. Default: 0.
1342 * @param $longformat bool. Default: false.
1343 * @return class FormattedText (XmlElement.php).
1345 function ByteFormatter ($bytes = 0, $longformat = false) {
1348 if ($bytes < 1024) {
1350 $size = fmt("%s b", $bytes);
1352 $size = fmt("%s bytes", $bytes);
1355 $kb = round($bytes / 1024, 1);
1357 $size = fmt("%s k", $kb);
1359 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1365 * Internationalized printf.
1367 * This is essentially the same as PHP's built-in printf
1368 * with the following exceptions:
1370 * <li> It passes the format string through gettext().
1371 * <li> It supports the argument reordering extensions.
1378 * __printf("Differences between versions %s and %s of %s",
1379 * $new_link, $old_link, $page_link);
1382 * Then in locale/po/de.po, one can reorder the printf arguments:
1385 * msgid "Differences between %s and %s of %s."
1386 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1389 * (Note that while PHP tries to expand $vars within double-quotes,
1390 * the values in msgstr undergo no such expansion, so the '$'s
1393 * One shouldn't use reordered arguments in the default format string.
1394 * Backslashes in the default string would be necessary to escape the
1395 * '$'s, and they'll cause all kinds of trouble....
1397 function __printf ($fmt) {
1398 $args = func_get_args();
1400 echo __vsprintf($fmt, $args);
1404 * Internationalized sprintf.
1406 * This is essentially the same as PHP's built-in printf with the
1407 * following exceptions:
1410 * <li> It passes the format string through gettext().
1411 * <li> It supports the argument reordering extensions.
1416 function __sprintf ($fmt) {
1417 $args = func_get_args();
1419 return __vsprintf($fmt, $args);
1423 * Internationalized vsprintf.
1425 * This is essentially the same as PHP's built-in printf with the
1426 * following exceptions:
1429 * <li> It passes the format string through gettext().
1430 * <li> It supports the argument reordering extensions.
1435 function __vsprintf ($fmt, $args) {
1436 $fmt = gettext($fmt);
1437 // PHP's sprintf doesn't support variable with specifiers,
1438 // like sprintf("%*s", 10, "x"); --- so we won't either.
1440 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1441 // Format string has '%2$s' style argument reordering.
1442 // PHP doesn't support this.
1443 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1444 // literal variable name substitution only to keep locale
1445 // strings uncluttered
1446 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1447 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1449 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1452 // Reorder arguments appropriately.
1453 foreach($m[1] as $argnum) {
1454 if ($argnum < 1 || $argnum > count($args))
1455 trigger_error(sprintf(_("%s: argument index out of range"),
1456 $argnum), E_USER_WARNING);
1457 $newargs[] = $args[$argnum - 1];
1462 // Not all PHP's have vsprintf, so...
1463 array_unshift($args, $fmt);
1464 return call_user_func_array('sprintf', $args);
1467 function file_mtime ($filename) {
1468 if ($stat = @stat($filename))
1474 function sort_file_mtime ($a, $b) {
1475 $ma = file_mtime($a);
1476 $mb = file_mtime($b);
1477 if (!$ma or !$mb or $ma == $mb) return 0;
1478 return ($ma > $mb) ? -1 : 1;
1483 * Build an array in $this->_fileList of files from $dirname.
1484 * Subdirectories are not traversed.
1486 * (This was a function LoadDir in lib/loadsave.php)
1487 * See also http://www.php.net/manual/en/function.readdir.php
1489 function getFiles($exclude='', $sortby='', $limit='') {
1490 $list = $this->_fileList;
1493 require_once('lib/PageList.php');
1494 switch (Pagelist::sortby($sortby, 'db')) {
1495 case 'pagename ASC': break;
1496 case 'pagename DESC':
1497 $list = array_reverse($list);
1500 usort($list,'sort_file_mtime');
1503 usort($list,'sort_file_mtime');
1504 $list = array_reverse($list);
1509 return array_splice($list, 0, $limit);
1513 function _filenameSelector($filename) {
1514 if (! $this->_pattern )
1517 if (! $this->_pcre_pattern )
1518 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1519 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1524 function fileSet($directory, $filepattern = false) {
1525 $this->_fileList = array();
1526 $this->_pattern = $filepattern;
1528 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1530 $this->_case = !isWindows();
1531 $this->_pathsep = '/';
1533 if (empty($directory)) {
1534 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1536 return; // early return
1539 @ $dir_handle = opendir($dir=$directory);
1540 if (empty($dir_handle)) {
1541 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1542 $dir), E_USER_NOTICE);
1543 return; // early return
1546 while ($filename = readdir($dir_handle)) {
1547 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1549 if ($this->_filenameSelector($filename)) {
1550 array_push($this->_fileList, "$filename");
1551 //trigger_error(sprintf(_("found file %s"), $filename),
1552 // E_USER_NOTICE); //debugging
1555 closedir($dir_handle);
1561 // expands a list containing regex's to its matching entries
1562 class ListRegexExpand {
1563 //var $match, $list, $index, $case_sensitive;
1564 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1565 $this->match = $match;
1566 $this->list = &$list;
1567 $this->case_sensitive = $case_sensitive;
1568 //$this->index = false;
1570 function listMatchCallback ($item, $key) {
1571 $quoted = str_replace('/','\/',$item);
1572 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1574 unset($this->list[$this->index]);
1575 $this->list[] = $item;
1578 function expandRegex ($index, &$pages) {
1579 $this->index = $index;
1580 array_walk($pages, array($this, 'listMatchCallback'));
1585 // Convert fileglob to regex style:
1586 // Convert some wildcards to pcre style, escape the rest
1587 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1588 // Fixed bug #994994: "/" in $glob.
1589 function glob_to_pcre ($glob) {
1590 // check simple case: no need to escape
1591 $escape = '\[](){}=!<>|:/';
1592 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1594 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1595 $glob = strtr($glob, "\\", "\xff");
1596 $glob = str_replace("/", "\\/", $glob);
1597 // first convert some unescaped expressions to pcre style: . => \.
1599 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1600 "\\1\xff\\2", $glob);
1603 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1604 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1605 if (!preg_match('/^[\?\*]/', $glob))
1607 if (!preg_match('/[\?\*]$/', $glob))
1610 // Fixes Bug 1182997
1611 // .*? handled above, now escape the rest
1612 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1613 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1615 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1617 $re = preg_replace('/\xff/', '', $re);
1621 function glob_match ($glob, $against, $case_sensitive = true) {
1622 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1626 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1627 $list = explode(',',$input);
1628 // expand wildcards from list of $allnames
1629 if (preg_match('/[\?\*]/',$input)) {
1630 // Optimizing loop invariants:
1631 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1632 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1634 if (preg_match('/[\?\*]/',$f)) {
1636 $expand = new ListRegexExpand($list,
1637 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1638 $expand->expandRegex($i, $allnames);
1645 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1646 function explodePageList($input, $include_empty=false, $sortby='pagename',
1647 $limit='', $exclude='') {
1648 include_once("lib/PageList.php");
1649 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1652 // Class introspections
1655 * Determine whether object is of a specified type.
1656 * In PHP builtin since 4.2.0 as is_a()
1657 * is_a() deprecated in PHP 5, in favor of instanceof operator
1659 * @param $object object An object.
1660 * @param $class string Class name.
1661 * @return bool True iff $object is a $class
1662 * or a sub-type of $class.
1664 function isa ($object, $class) {
1665 //if (check_php_version(5))
1666 // return $object instanceof $class;
1667 if (check_php_version(4,2) and !check_php_version(5))
1668 return is_a($object, $class);
1670 $lclass = check_php_version(5) ? $class : strtolower($class);
1671 return is_object($object)
1672 && ( strtolower(get_class($object)) == strtolower($class)
1673 || is_subclass_of($object, $lclass) );
1676 /** Determine whether (possible) object has method.
1678 * @param $object mixed Object
1679 * @param $method string Method name
1680 * @return bool True iff $object is an object with has method $method.
1682 function can ($object, $method) {
1683 return is_object($object) && method_exists($object, strtolower($method));
1686 /** Determine whether a function is okay to use.
1688 * Some providers (e.g. Lycos) disable some of PHP functions for
1689 * "security reasons." This makes those functions, of course,
1690 * unusable, despite the fact the function_exists() says they
1693 * This function test to see if a function exists and is not
1694 * disallowed by PHP's disable_functions config setting.
1696 * @param string $function_name Function name
1697 * @return bool True iff function can be used.
1699 function function_usable($function_name) {
1701 if (!is_array($disabled)) {
1702 $disabled = array();
1703 // Use get_cfg_var since ini_get() is one of the disabled functions
1704 // (on Lycos, at least.)
1705 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1706 foreach ($split as $f)
1707 $disabled[strtolower($f)] = true;
1710 return ( function_exists($function_name)
1711 and ! isset($disabled[strtolower($function_name)])
1718 * This is used for generating ETags.
1720 function wikihash ($x) {
1721 if (is_scalar($x)) {
1724 elseif (is_array($x)) {
1726 return md5(serialize($x));
1728 elseif (is_object($x)) {
1731 trigger_error("Can't hash $x", E_USER_ERROR);
1736 * Seed the random number generator.
1738 * better_srand() ensures the randomizer is seeded only once.
1740 * How random do you want it? See:
1741 * http://www.php.net/manual/en/function.srand.php
1742 * http://www.php.net/manual/en/function.mt-srand.php
1744 function better_srand($seed = '') {
1745 static $wascalled = FALSE;
1747 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1748 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1750 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1754 function rand_ascii($length = 1) {
1757 for ($i = 1; $i <= $length; $i++) {
1758 // return only typeable 7 bit ascii, avoid quotes
1759 if (function_exists('mt_rand'))
1760 $s .= chr(mt_rand(40, 126));
1762 // the usually bad glibc srand()
1763 $s .= chr(rand(40, 126));
1768 /* by Dan Frankowski.
1770 function rand_ascii_readable ($length = 6) {
1771 // Pick a few random letters or numbers
1774 // Don't use 1lI0O, because they're hard to read
1775 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1776 $letter_len = strlen($letters);
1777 for ($i=0; $i < $length; $i++) {
1778 if (function_exists('mt_rand'))
1779 $word .= $letters[mt_rand(0, $letter_len-1)];
1781 $word .= $letters[rand(0, $letter_len-1)];
1787 * Recursively count all non-empty elements
1788 * in array of any dimension or mixed - i.e.
1789 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1790 * See http://www.php.net/manual/en/function.count.php
1792 function count_all($arg) {
1793 // skip if argument is empty
1795 //print_r($arg); //debugging
1797 // not an array, return 1 (base case)
1800 // else call recursively for all elements $arg
1801 foreach($arg as $key => $val)
1802 $count += count_all($val);
1807 function isSubPage($pagename) {
1808 return (strstr($pagename, SUBPAGE_SEPARATOR));
1811 function subPageSlice($pagename, $pos) {
1812 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1813 $pages = array_slice($pages,$pos,1);
1820 * Class for "popping up" and alert box. (Except that right now, it doesn't
1824 * This is a hackish and needs to be refactored. However it would be nice to
1825 * unify all the different methods we use for showing Alerts and Dialogs.
1826 * (E.g. "Page deleted", login form, ...)
1831 * @param object $request
1832 * @param mixed $head Header ("title") for alert box.
1833 * @param mixed $body The text in the alert box.
1834 * @param hash $buttons An array mapping button labels to URLs.
1835 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1837 function Alert($head, $body, $buttons=false) {
1838 if ($buttons === false)
1841 if (is_array($body)) {
1843 foreach ($body as $li) {
1844 $html->pushContent(HTML::li($li));
1848 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1849 $this->_buttons = $buttons;
1853 * Show the alert box.
1858 $tokens = $this->_tokens;
1859 $tokens['BUTTONS'] = $this->_getButtons();
1861 $request->discardOutput();
1862 $tmpl = new Template('dialog', $request, $tokens);
1868 function _getButtons() {
1871 $buttons = $this->_buttons;
1873 $buttons = array(_("Okay") => $request->getURLtoSelf());
1876 foreach ($buttons as $label => $url)
1877 print "$label $url\n";
1878 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1879 return new XmlContent($out);
1884 // 1.3.9-p1 => 1030.091
1885 // 1.3.10pre => 1030.099
1886 // 1.3.11pre-20041120 => 1030.1120041120
1887 // 1.3.12-rc1 => 1030.119
1888 function phpwiki_version() {
1889 static $PHPWIKI_VERSION;
1890 if (!isset($PHPWIKI_VERSION)) {
1891 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1892 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1893 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1894 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1895 $PHPWIKI_VERSION -= 0.01;
1897 return $PHPWIKI_VERSION;
1900 function phpwiki_gzhandler($ob) {
1901 if (function_exists('gzencode'))
1902 $ob = gzencode($ob);
1903 $GLOBALS['request']->_ob_get_length = strlen($ob);
1904 if (!headers_sent()) {
1905 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1910 function isWikiWord($word) {
1911 global $WikiNameRegexp;
1912 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1913 return preg_match("/^$WikiNameRegexp\$/",$word);
1916 // needed to store serialized objects-values only (perm, pref)
1917 function obj2hash ($obj, $exclude = false, $fields = false) {
1919 if (! $fields ) $fields = get_object_vars($obj);
1920 foreach ($fields as $key => $val) {
1921 if (is_array($exclude)) {
1922 if (in_array($key, $exclude)) continue;
1930 * isUtf8String($string) - cheap utf-8 detection
1932 * segfaults for strings longer than 10kb!
1933 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1934 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1936 function isUtf8String( $s ) {
1937 $ptrASCII = '[\x00-\x7F]';
1938 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1939 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1940 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1941 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1942 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1943 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1947 * Check for UTF-8 URLs; Internet Explorer produces these if you
1948 * type non-ASCII chars in the URL bar or follow unescaped links.
1949 * Requires urldecoded pagename.
1950 * Fixes sf.net bug #953949
1952 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1954 function fixTitleEncoding( $s ) {
1959 if (empty($s)) return $s;
1961 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1963 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1964 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1966 $isutf = ($ishigh ? isUtf8String($s) : true);
1967 $locharset = strtolower($charset);
1969 if( $locharset != "utf-8" and $ishigh and $isutf )
1970 $s = charset_convert('UTF-8', $locharset, $s);
1971 if ($locharset == "utf-8" and $ishigh and !$isutf )
1972 return utf8_encode( $s );
1974 // Other languages can safely leave this function, or replace
1975 // it with one to detect and convert another legacy encoding.
1980 * MySQL fulltext index doesn't grok utf-8, so we
1981 * need to fold cases and convert to hex.
1982 * src: languages/Language.php:stripForSearch() from mediawiki
1985 function stripForSearch( $string ) {
1986 global $wikiLowerChars;
1987 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1988 return preg_replace(
1989 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1990 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1996 * Workaround for allow_url_fopen, to get the content of an external URI.
1997 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1998 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2000 function url_get_contents( $uri ) {
2001 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2002 return @file_get_contents($uri);
2004 require_once("lib/HttpClient.php");
2005 $bits = parse_url($uri);
2006 $host = $bits['host'];
2007 $port = isset($bits['port']) ? $bits['port'] : 80;
2008 $path = isset($bits['path']) ? $bits['path'] : '/';
2009 if (isset($bits['query'])) {
2010 $path .= '?'.$bits['query'];
2012 $client = new HttpClient($host, $port);
2013 $client->use_gzip = false;
2014 if (!$client->get($path)) {
2017 return $client->getContent();
2023 * Generate consecutively named strings:
2024 * Name, Name2, Name3, ...
2026 function GenerateId($name) {
2027 static $ids = array();
2028 if (empty($ids[$name])) {
2033 return $name . $ids[$name];
2037 // from IncludePage. To be of general use.
2038 // content: string or array of strings
2039 function firstNWordsOfContent( $n, $content ) {
2040 if ($content and $n > 0) {
2041 if (is_array($content)) {
2042 // fixme: return a list of lines then?
2043 //$content = join("\n", $content);
2044 //$return_array = true;
2046 foreach ($content as $line) {
2047 $words = explode(' ', $line);
2048 if ($wordcount + count($words) > $n) {
2049 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2050 . sprintf(_("... (first %s words)"), $n);
2053 $wordcount += count($words);
2059 // fixme: use better whitespace/word seperators
2060 $words = explode(' ', $content);
2061 if (count($words) > $n) {
2062 return join(' ', array_slice($words, 0, $n))
2063 . sprintf(_("... (first %s words)"), $n);
2073 // moved from lib/plugin/IncludePage.php
2074 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2075 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2077 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2078 . " \\s*$\\n?" // possible blank lines
2079 . " ( (?: ^.*\\n? )*? )" // some lines
2080 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2081 implode("\n", $content),
2083 // Strip trailing blanks lines and ---- <hr>s
2084 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2086 $text = $match[1] . $section ."\n". $text;
2087 return explode("\n", $text);
2090 $mesg = $page ." ". $section;
2093 return array(sprintf(_("<%s: no such section>"), $mesg));
2096 // Extract the first $sections sections of the page
2097 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2099 $mycontent = $content;
2102 while ($sections > 0) {
2104 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2105 . " \\s*$\\n?" // possible blank lines
2106 . " ( (?: ^.*\\n? )*? )" // some lines
2107 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2108 implode("\n", $mycontent),
2110 $section = $match[2];
2111 // Strip trailing blanks lines and ---- <hr>s
2112 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2114 $text = $match[1] . $section ."\n". $text;
2117 $mycontent = explode("\n", $match[4]);
2119 if ($sections === 0) {
2120 return explode("\n", $result);
2126 // use this faster version: only load ExternalReferrer if we came from an external referrer
2127 function isExternalReferrer(&$request) {
2128 if ($referrer = $request->get('HTTP_REFERER')) {
2129 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2130 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2131 require_once("lib/ExternalReferrer.php");
2132 $se = new SearchEngines();
2133 return $se->parseSearchQuery($referrer);
2135 //if (DEBUG) return array('query' => 'wiki');
2140 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2142 function loadPhpExtension($extension) {
2143 if (!extension_loaded($extension)) {
2144 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2145 $soname = ($isWindows ? 'php_' : '')
2147 . ($isWindows ? '.dll' : '.so');
2151 return extension_loaded($extension);
2154 function charset_convert($from, $to, $data) {
2156 //$wikicharset = strtolower($CHARSET);
2157 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2158 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2159 return utf8_decode($data);
2160 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2161 return utf8_encode($data);
2163 if (loadPhpExtension("iconv")) {
2164 $tmpdata = iconv($from, $to, $data);
2166 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2170 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2175 function string_starts_with($string, $prefix) {
2176 return (substr($string, 0, strlen($prefix)) == $prefix);
2178 function string_ends_with($string, $suffix) {
2179 return (substr($string, -strlen($suffix)) == $suffix);
2181 function array_remove($arr,$value) {
2182 return array_values(array_diff($arr,array($value)));
2186 * Ensure that the script will have another $secs time left.
2187 * Works only if safe_mode is off.
2188 * For example not to timeout on waiting socket connections.
2189 * Use the socket timeout as arg.
2191 function longer_timeout($secs = 30) {
2192 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2193 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2194 if ($timeleft < $secs)
2195 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2198 function printSimpleTrace($bt) {
2200 echo "\nTraceback:\n";
2201 if (function_exists('debug_print_backtrace')) { // >= 5
2202 debug_print_backtrace();
2204 foreach ($bt as $i => $elem) {
2205 if (!array_key_exists('file', $elem)) {
2208 //echo join(" ",array_values($elem)),"\n";
2209 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2215 * Return the used process memory, in bytes.
2216 * Enable the section which will work for you. They are very slow.
2217 * Special quirks for Windows: Requires cygwin.
2219 function getMemoryUsage() {
2220 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2221 if (function_exists('memory_get_usage') and memory_get_usage()) {
2222 return memory_get_usage();
2223 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2224 $mem = $u['ru_maxrss'];
2225 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2226 // what we want is the process memory only: apache or php (if CGI)
2229 // win32_ps_stat_proc, win32_ps_stat_mem
2230 if (function_exists('win32_ps_list_procs')) {
2231 $info = win32_ps_stat_proc($pid);
2232 $memstr = $info['mem']['working_set_size'];
2234 // This works only if it's a cygwin process (apache or php).
2235 // Requires a newer cygwin
2236 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2238 // if it's native windows use something like this:
2239 // (requires pslist from sysinternals.com, grep, sed and perl)
2240 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2242 return (integer) trim($memstr);
2245 //%MEM: Percentage of total memory in use by this process
2246 //VSZ: Total virtual memory size, in 1K blocks.
2247 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2248 //CPU time used by process since it started.
2249 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2250 $memstr = exec("ps -orss -p $pid|sed 1d");
2251 return (integer) trim($memstr);
2256 * @param var $needle
2257 * @param array $haystack one-dimensional numeric array only, no hash
2259 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2260 It will return false if not found or the index where it was found.
2261 From dennis.decoene@moveit.be http://www.php.net/array_search
2263 function binary_search($needle, $haystack) {
2264 $high = count($haystack);
2267 while (($high - $low) > 1) {
2268 $probe = floor(($high + $low) / 2);
2269 if ($haystack[$probe] < $needle) {
2271 } elseif ($haystack[$probe] == $needle) {
2272 $high = $low = $probe;
2278 if ($high == count($haystack) || $haystack[$high] != $needle) {
2285 function is_localhost($url = false) {
2287 global $HTTP_SERVER_VARS;
2288 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2293 * Take a string and quote it sufficiently to be passed as a Javascript
2294 * string between ''s
2296 function javascript_quote_string($s) {
2297 return str_replace("'", "\'", $s);
2300 function isSerialized($s) {
2301 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2304 // (c-file-style: "gnu")
2308 // c-basic-offset: 4
2309 // c-hanging-comment-ender-p: nil
2310 // indent-tabs-mode: nil