1 <?php //rcs_id('$Id$');
3 Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4 Copyright 2008 Marc-Etienne Vargenau, Alcatel-Lucent
6 This file is part of PhpWiki.
8 PhpWiki is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 PhpWiki is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with PhpWiki; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 Standard functions for Wiki functionality
25 WikiURL ($pagename, $args, $get_abs_url)
27 IconForLink ($protocol_or_url)
28 PossiblyGlueIconToText($proto_or_url, $text)
30 LinkURL ($url, $linktext)
31 LinkImage ($url, $alt)
32 ImgObject ($img, $url)
34 SplitQueryArgs ($query_args)
35 LinkPhpwikiURL ($url, $text, $basepage)
36 ConvertOldMarkup ($content, $markup_type = "block")
37 MangleXmlIdentifier($str)
38 UnMangleXmlIdentifier($str)
40 class Stack { push($item), pop(), cnt(), top() }
41 class Alert { show() }
42 class WikiPageName {getParent(),isValid(),getWarnings() }
44 expand_tabs($str, $tab_width = 8)
46 NoSuchRevision ($request, $page, $version)
47 TimezoneOffset ($time, $no_colon)
48 Iso8601DateTime ($time)
49 Rfc2822DateTime ($time)
50 ParseRfc1123DateTime ($timestr)
52 ByteFormatter ($bytes = 0, $longformat = false)
55 __vsprintf ($fmt, $args)
57 file_mtime ($filename)
58 sort_file_mtime ($a, $b)
59 class fileSet {fileSet($directory, $filepattern = false),
60 getFiles($exclude='', $sortby='', $limit='') }
61 class ListRegexExpand { listMatchCallback($item, $key),
62 expandRegex ($index, &$pages) }
65 glob_match ($glob, $against, $case_sensitive = true)
66 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
67 explodePageList ($input, $perm = false)
69 can ($object, $method)
70 function_usable ($function_name)
72 better_srand ($seed = '')
75 subPageSlice ($pagename, $pos)
79 obj2hash ($obj, $exclude = false, $fields = false)
82 url_get_contents ($uri)
84 firstNWordsOfContent ($n, $content)
85 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
88 charset_convert($from, $to, $data)
90 function: LinkInterWikiLink($link, $linktext)
91 moved to: lib/interwiki.php
92 function: linkExistingWikiWord($wikiword, $linktext, $version)
93 moved to: lib/WikiTheme.php
94 function: LinkUnknownWikiWord($wikiword, $linktext)
95 moved to: lib/WikiTheme.php
96 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
97 gone see: lib/plugin/RecentChanges.php
99 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
100 else define('_PHPWIKI_STDLIB_LOADED', true);
102 define('MAX_PAGENAME_LENGTH', 100);
105 * Convert string to a valid XML identifier.
107 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
109 * We would like to have, e.g. named anchors within wiki pages
110 * names like "Table of Contents" --- clearly not a valid XML
111 * fragment identifier.
113 * This function implements a one-to-one map from {any string}
114 * to {valid XML identifiers}.
117 * converting all bytes not in [A-Za-z0-9:_-],
118 * and any leading byte not in [A-Za-z] to 'xbb.',
119 * where 'bb' is the hexadecimal representation of the
122 * As a special case, the empty string is converted to 'empty.'
127 function MangleXmlIdentifier($str) {
131 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
132 "'x' . sprintf('%02x', ord('\\0')) . '.'",
136 function UnMangleXmlIdentifier($str) {
137 if ($str == 'empty.')
139 return preg_replace('/x(\w\w)\./e',
140 "sprintf('%c', hex('\\0'))",
145 * Returns a name for the WIKI_ID cookie that should be unique on the host.
146 * But for it to be unique you must have set a unique WIKI_NAME in your
147 * configuration file.
148 * @return string The name of the WIKI_ID cookie to use for this wiki.
150 function GetCookieName() {
151 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
155 * Generates a valid URL for a given Wiki pagename.
156 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
157 * If a WikiDB_Page object function will extract the name to link to.
158 * If a WikiDB_PageRevision object function will extract the name to link to.
160 * @param boolean $get_abs_url Default value is false.
161 * @return string The absolute URL to the page passed as $pagename.
163 function WikiURL($pagename, $args = '', $get_abs_url = false) {
164 global $request, $WikiTheme;
167 if (is_object($pagename)) {
168 if (isa($pagename, 'WikiDB_Page')) {
169 $pagename = $pagename->getName();
171 elseif (isa($pagename, 'WikiDB_PageRevision')) {
172 $page = $pagename->getPage();
173 $args['version'] = $pagename->getVersion();
174 $pagename = $page->getName();
176 elseif (isa($pagename, 'WikiPageName')) {
177 $anchor = $pagename->anchor;
178 $pagename = $pagename->name;
180 $anchor = $pagename->anchor;
181 $pagename = $pagename->name;
184 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
186 $args = 'start_debug=' . $request->getArg('start_debug');
187 elseif (is_array($args))
188 $args['start_debug'] = $request->getArg('start_debug');
190 $args .= '&start_debug=' . $request->getArg('start_debug');
192 if (is_array($args)) {
194 foreach ($args as $key => $val) {
195 // avoid default args
196 if (USE_PATH_INFO and $key == 'pagename')
198 elseif ($key == 'action' and $val == 'browse')
200 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
201 $enc_args[] = urlencode($key) . '=' . urlencode($val);
203 $args = join('&', $enc_args);
206 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
207 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
208 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
210 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
211 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
212 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
215 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
217 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
227 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
228 $url .= "?pagename=" . rawurlencode($pagename);
233 $url .= "#" . MangleXmlIdentifier($anchor);
237 /** Convert relative URL to absolute URL.
239 * This converts a relative URL to one of PhpWiki's support files
240 * to an absolute one.
243 * @return string Absolute URL
245 function AbsoluteURL ($url) {
246 if (preg_match('/^https?:/', $url))
248 if ($url[0] != '/') {
249 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
250 while ($base != '/' and substr($url, 0, 3) == "../") {
251 $url = substr($url, 3);
252 $base = dirname($base);
258 return SERVER_URL . $url;
261 function DataURL ($url) {
262 if (preg_match('/^https?:/', $url))
264 $url = NormalizeWebFileName($url);
265 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
266 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
267 return AbsoluteURL($url);
271 * Generates icon in front of links.
273 * @param string $protocol_or_url URL or protocol to determine which icon to use.
275 * @return HtmlElement HtmlElement object that contains data to create img link to
276 * icon for use with url or protocol passed to the function. False if no img to be
279 function IconForLink($protocol_or_url) {
281 if (0 and $filename_suffix == false) {
282 // display apache style icon for file type instead of protocol icon
283 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
284 // - document: html, htm, text, txt, rtf, pdf, doc
285 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
286 // - audio: mp3,mp2,aiff,aif,au
287 // - multimedia: mpeg,mpg,mov,qt
289 list ($proto) = explode(':', $protocol_or_url, 2);
290 $src = $WikiTheme->getLinkIconURL($proto);
292 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
299 * Glue icon in front of or after text.
300 * Pref: 'noLinkIcons' - ignore icon if set
301 * WikiTheme: 'LinkIcons' - 'yes' at front
302 * - 'no' display no icon
303 * - 'front' display at left
304 * - 'after' display at right
306 * @param string $protocol_or_url Protocol or URL. Used to determine the
308 * @param string $text The text.
309 * @return XmlContent.
311 function PossiblyGlueIconToText($proto_or_url, $text) {
312 global $request, $WikiTheme;
313 if ($request->getPref('noLinkIcons'))
315 $icon = IconForLink($proto_or_url);
318 if ($where = $WikiTheme->getLinkIconAttr()) {
319 if ($where == 'no') return $text;
320 if ($where != 'after') $where = 'front';
324 if ($where == 'after') {
325 // span the icon only to the last word (tie them together),
326 // to let the previous words wrap on line breaks.
327 if (!is_object($text)) {
328 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
329 list (, $prefix, $last_word) = $m;
335 $text = HTML::span(array('style' => 'white-space: nowrap'),
336 $last_word, HTML::Raw(' '), $icon);
338 $text = HTML($prefix, $text);
341 // span the icon only to the first word (tie them together),
342 // to let the next words wrap on line breaks
343 if (!is_object($text)) {
344 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
345 list (, $first_word, $tail) = $m;
351 $text = HTML::span(array('style' => 'white-space: nowrap'),
354 $text = HTML($text, $tail);
359 * Determines if the url passed to function is safe, by detecting if the characters
360 * '<', '>', or '"' are present.
361 * Check against their urlencoded values also.
363 * @param string $url URL to check for unsafe characters.
364 * @return boolean True if same, false else.
366 function IsSafeURL($url) {
367 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
371 * Generates an HtmlElement object to store data for a link.
373 * @param string $url URL that the link will point to.
374 * @param string $linktext Text to be displayed as link.
375 * @return HtmlElement HtmlElement object that contains data to construct an html link.
377 function LinkURL($url, $linktext = '') {
378 // FIXME: Is this needed (or sufficient?)
379 if(! IsSafeURL($url)) {
380 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
381 _("BAD URL -- remove all of <, >, \"")));
385 $linktext = preg_replace("/mailto:/A", "", $url);
386 $args = array('href' => $url);
387 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
388 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
389 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
391 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
398 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
399 * Disallows sizes which are too small.
400 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
402 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
404 function LinkImage($url, $alt = false) {
405 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
406 // Disallow tags in img src urls. Typical CSS attacks.
407 // FIXME: Is this needed (or sufficient?)
408 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
410 if(! IsSafeURL($url)) {
411 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
412 _("BAD URL -- remove all of <, >, \"")));
415 // support new syntax: [prefix/image.jpg size=50% border=n]
416 //if (!preg_match("/\.(".$force_img.")/i", $url))
417 if (empty($alt)) $alt = basename($url);
418 $arr = split(' ',$url);
419 $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
420 if (count($arr) > 1) {
423 foreach ($arr as $attr) {
424 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
425 $link->setAttr('width',$m[1]);
426 $link->setAttr('height',$m[1]);
428 elseif (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
429 $link->setAttr('width',$m[1]);
430 $link->setAttr('height',$m[2]);
432 elseif (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
433 $link->setAttr('width',$m[1]);
434 elseif (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
435 $link->setAttr('height',$m[1]);
436 elseif (preg_match('/^border=(\d+)$/',$attr,$m))
437 $link->setAttr('border',$m[1]);
438 elseif (preg_match('/^align=(\w+)$/',$attr,$m))
439 $link->setAttr('align',$m[1]);
440 elseif (preg_match('/^hspace=(\d+)$/',$attr,$m))
441 $link->setAttr('hspace',$m[1]);
442 elseif (preg_match('/^vspace=(\d+)$/',$attr,$m))
443 $link->setAttr('vspace',$m[1]);
446 if(! IsSafeURL($url)) {
447 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
448 _("BAD URL -- remove all of <, >, \"")));
451 $link->setAttr('src', $url);
456 // Check width and height as spam countermeasure
457 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
458 //$width = (int) $width; // px or % or other suffix
459 //$height = (int) $height;
460 if (($width < 3 and $height < 10) or
461 ($height < 3 and $width < 20) or
462 ($height < 7 and $width < 7))
464 trigger_error(_("Invalid image size"), E_USER_WARNING);
469 // Prepare for getimagesize($url)
470 // $url only valid for external urls, otherwise local path
471 // Older php versions crash here with certain png's:
472 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
473 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
474 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
475 if (DISABLE_GETIMAGESIZE)
477 elseif (! preg_match("/\.$force_img$/i", $url))
478 ; // only valid image extensions or scripts assumed to generate images
479 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
480 ; // it's safe to assume that this will fail.
481 elseif (preg_match("/^http/",$url)) { // external url
482 $size = @getimagesize($url);
483 } else { // local file
484 if (file_exists($file = NormalizeLocalFileName($url))) { // here
485 $size = @getimagesize($file);
486 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
487 $size = @getimagesize($file);
488 $link->setAttr('src', rawurldecode($url));
489 } elseif (string_starts_with($url, getUploadDataPath())) { // there
490 $file = substr($file, strlen(getUploadDataPath()));
491 $size = @getimagesize(getUploadFilePath().rawurldecode($file));
492 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
493 } else { // elsewhere
494 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
500 if (($width < 3 and $height < 10)
501 or ($height < 3 and $width < 20)
502 or ($height < 7 and $width < 7))
504 trigger_error(_("Invalid image size"), E_USER_WARNING);
510 $link->setAttr('class', 'inlineimage');
512 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
513 * png|jpg|gif|jpeg|bmp|pl|cgi
514 * Note: Allow cgi's (pl,cgi) returning images.
516 if (!preg_match("/\.(".$force_img.")/i", $url)) {
517 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
518 // => HTML::object(array('src' => $url)) ...;
519 return ImgObject($link, $ori_url);
525 * <object> / <embed> tags instead of <img> for all non-image extensions
527 * Called by LinkImage(), not directly.
528 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
529 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
530 * $alt may be an alternate img
531 * TODO: Need to unify with WikiPluginCached::embedObject()
533 * Note that Safari 1.0 will crash with <object>, so use only <embed>
534 * http://www.alleged.org.uk/pdc/2002/svg-object.html
536 * Allowed object tags:
537 * DATA=URI (object data)
538 * CLASSID=URI (location of implementation)
539 * ARCHIVE=CDATA (archive files)
540 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
541 * WIDTH=Length (object width)
542 * HEIGHT=Length (object height)
543 * NAME=CDATA (name for form submission)
544 * USEMAP=URI (client-side image map)
545 * TYPE=ContentType (content-type of object)
546 * CODETYPE=ContentType (content-type of code)
547 * STANDBY=Text (message to show while loading)
548 * TABINDEX=NUMBER (position in tabbing order)
549 * DECLARE (do not instantiate object)
550 * The rest is added as <param name="" value="" /> tags
552 function ImgObject($img, $url) {
553 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
554 $args = split(' ', $url);
556 if (count($args) >= 1) {
557 $url = array_shift($args);
559 foreach ($args as $attr) {
560 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
561 "codetype,standby,tabindex,declare") as $param)
563 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
564 $img->setAttr($param, $m[1]);
570 // now all remaing args are added as <param> to the object
571 foreach ($args as $attr) {
572 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
573 $params[] = HTML::param(array('name' => $m[1],
578 $type = $img->getAttr('type');
580 // TODO: map extension to mime-types if type is not given and php < 4.3
581 if (function_exists('mime_content_type'))
582 $type = mime_content_type($url);
584 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
586 $object->setAttr('class', 'inlineobject');
588 foreach ($params as $param) $object->pushContent($param);
590 if (isBrowserSafari()) {
591 return HTML::embed($object->_attr, $object->_content);
593 $object->pushContent(HTML::embed($object->_attr));
600 // var in php5 deprecated
602 $this->items = array();
605 function push($item) {
606 $this->items[$this->size] = $item;
612 if ($this->size == 0) {
613 return false; // stack is empty
616 return $this->items[$this->size];
625 return $this->items[$this->size - 1];
631 // end class definition
633 function SplitQueryArgs ($query_args = '')
635 // FIXME: use the arg-seperator which might not be &
636 $split_args = split('&', $query_args);
638 while (list($key, $val) = each($split_args))
639 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
640 $args[$m[1]] = $m[2];
644 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
647 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
648 return HTML::strong(array('class' => 'rawurl'),
649 HTML::u(array('class' => 'baduri'),
650 _("BAD phpwiki: URL")));
654 $pagename = urldecode($m[1]);
657 if (empty($pagename) &&
658 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
659 // Convert old style links (to not break diff links in
661 $pagename = urldecode($m[2]);
662 $args = array("action" => $m[1]);
665 $args = SplitQueryArgs($qargs);
668 if (empty($pagename))
669 $pagename = $GLOBALS['request']->getArg('pagename');
671 if (isset($args['action']) && $args['action'] == 'browse')
672 unset($args['action']);
675 if (empty($args['action']))
677 else if (is_safe_action($args['action']))
678 $class = 'wikiaction';
680 if (empty($args['action']) || is_safe_action($args['action']))
681 $class = 'wikiaction';
683 // Don't allow administrative links on unlocked pages.
684 $dbi = $GLOBALS['request']->getDbh();
685 $page = $dbi->getPage($basepage ? $basepage : $pagename);
686 if (!$page->get('locked'))
687 return HTML::span(array('class' => 'wikiunsafe'),
688 HTML::u(_("Lock page to enable link")));
689 $class = 'wikiadmin';
693 $text = HTML::span(array('class' => 'rawurl'), $url);
695 $wikipage = new WikiPageName($pagename);
696 if (!$wikipage->isValid()) {
698 return $WikiTheme->linkBadWikiWord($wikipage, $url);
701 return HTML::a(array('href' => WikiURL($pagename, $args),
707 * A class to assist in parsing wiki pagenames.
709 * Now with subpages and anchors, parsing and passing around
710 * pagenames is more complicated. This should help.
714 /** Short name for page.
716 * This is the value of $name passed to the constructor.
717 * (For use, e.g. as a default label for links to the page.)
721 /** The full page name.
723 * This is the full name of the page (without anchor).
729 * This is the referenced anchor within the page, or the empty string.
735 * @param mixed $name Page name.
736 * WikiDB_Page, WikiDB_PageRevision, or string.
737 * This can be a relative subpage name (like '/SubPage'),
738 * or can be the empty string to refer to the $basename.
740 * @param string $anchor For links to anchors in page.
742 * @param mixed $basename Page name from which to interpret
743 * relative or other non-fully-specified page names.
745 function WikiPageName($name, $basename=false, $anchor=false) {
746 if (is_string($name)) {
747 $this->shortName = $name;
748 if (strstr($name, ':')) {
749 list($moniker, $shortName) = split (":", $name, 2);
750 $map = getInterwikiMap(); // allow overrides to custom maps
751 if (isset($map->_map[$moniker])) {
752 $url = $map->_map[$moniker];
753 if (strstr($url, '%s'))
754 $url = sprintf($url, $shortName);
758 // expand Talk or User, but not to absolute urls!
759 if (strstr($url, '//')) {
760 if ($moniker == 'Talk')
761 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
762 elseif ($moniker == 'User')
767 if (strstr($shortName, '?')) {
768 list($shortName, $dummy) = split("\?", $shortName, 2);
770 $this->shortName = $shortName;
773 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
774 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
776 $name = $this->_pagename($basename) . $name;
778 $name = $this->_normalize_bad_pagename($name);
779 $this->shortName = $name;
784 $name = $this->_pagename($name);
785 $this->shortName = $name;
788 $this->name = $this->_check($name);
789 $this->anchor = (string)$anchor;
796 function getParent() {
798 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
800 return substr($name, 0, -strlen($tail));
803 function isValid($strict = false) {
805 return !isset($this->_errors);
806 return (is_string($this->name) and $this->name != '');
809 function getWarnings() {
811 if (isset($this->_warnings))
812 $warnings = array_merge($warnings, $this->_warnings);
813 if (isset($this->_errors))
814 $warnings = array_merge($warnings, $this->_errors);
818 return sprintf(_("'%s': Bad page name: %s"),
819 $this->shortName, join(', ', $warnings));
822 function _pagename($page) {
823 if (isa($page, 'WikiDB_Page'))
824 return $page->getName();
825 elseif (isa($page, 'WikiDB_PageRevision'))
826 return $page->getPageName();
827 elseif (isa($page, 'WikiPageName'))
829 // '0' or e.g. '1984' should be allowed though
830 if (!is_string($page) and !is_integer($page)) {
831 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
832 $page, gettype($page), get_class($page)),
835 //assert(is_string($page));
839 function _normalize_bad_pagename($name) {
840 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
842 // Punt... You really shouldn't get here.
845 return $request->getArg('pagename');
847 assert($name[0] == SUBPAGE_SEPARATOR);
848 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
849 return substr($name, 1);
853 * Compress internal white-space to single space character.
855 * This leads to problems with loading a foreign charset pagename,
856 * which cannot be deleted anymore, because unknown chars are compressed.
857 * So BEFORE importing a file _check must be done !!!
859 function _check($pagename) {
860 // Compress internal white-space to single space character.
861 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
862 if ($pagename != $orig)
863 $this->_warnings[] = _("White space converted to single space");
865 // Delete any control characters.
866 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
867 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
868 if ($pagename != $orig)
869 $this->_errors[] = _("Control characters not allowed");
872 // Strip leading and trailing white-space.
873 $pagename = trim($pagename);
876 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
877 $pagename = substr($pagename, 1);
878 if ($pagename != $orig)
879 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
881 // ";" is urlencoded, so safe from php arg-delim problems
882 /*if (strstr($pagename, ';')) {
883 $this->_warnings[] = _("';' is deprecated");
884 $pagename = str_replace(';', '', $pagename);
887 // not only for SQL, also to restrict url length
888 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
889 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
890 $this->_errors[] = _("too long");
893 // disallow some chars only on file and cvs
894 if ((DATABASE_TYPE == 'cvs'
895 or DATABASE_TYPE == 'file'
896 or DATABASE_TYPE == 'flatfile')
897 and preg_match('/(:|\.\.)/', $pagename, $m))
899 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
900 $pagename = str_replace('..', '', $pagename);
901 $pagename = str_replace(':', '', $pagename);
909 * Convert old page markup to new-style markup.
911 * @param string $text Old-style wiki markup.
913 * @param string $markup_type
915 * <dt><code>"block"</code> <dd>Convert all markup.
916 * <dt><code>"inline"</code> <dd>Convert only inline markup.
917 * <dt><code>"links"</code> <dd>Convert only link markup.
920 * @return string New-style wiki markup.
922 * @bugs Footnotes don't work quite as before (esp if there are
923 * multiple references to the same footnote. But close enough,
924 * probably for now....
925 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
926 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
927 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
928 * also known to crash, even with Apache1.
930 function ConvertOldMarkup ($text, $markup_type = "block") {
936 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
937 // AnciennesR%E8glesDeFormatage crashes.
938 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
939 // also known to crash, even with Apache1.
941 // I suspect this only to crash with Apache2 and IIS.
942 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
943 and preg_match("/plugin CreateToc/", $text))
945 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
946 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
947 ._("Skipped."), E_USER_WARNING);
949 //if (!DEBUG) return $text;
954 /*****************************************************************
955 * Conversions for inline markup:
962 // escape escaped brackets
966 // change ! escapes to ~'s.
967 global $WikiNameRegexp, $request;
968 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
969 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
970 if (check_php_version(4,3,9)) {
971 $map = getInterwikiMap();
972 if ($map_regex = $map->getRegexp())
973 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
975 $bang_esc[] = $WikiNameRegexp;
976 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
979 $subs["links"] = array($orig, $repl);
981 // Temporarily URL-encode pairs of underscores in links to hide
982 // them from the re for bold markup.
983 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
984 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
987 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
990 // Convert footnote references.
991 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
992 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
994 // Convert old style emphases to HTML style emphasis.
995 $orig[] = '/__(.*?)__/';
996 $repl[] = '<strong>\\1</strong>';
997 $orig[] = "/''(.*?)''/";
998 $repl[] = '<em>\\1</em>';
1000 // Escape nestled markup.
1001 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1004 // in old markup headings only allowed at beginning of line
1008 // Convert URL-encoded pairs of underscores in links back to
1009 // real underscores after bold markup has been converted.
1010 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1011 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1013 $subs["inline"] = array($orig, $repl);
1015 /*****************************************************************
1016 * Patterns which match block markup constructs which take
1017 * special handling...
1021 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1023 $blockpats[] = '\|(?:.*\n\|)*';
1026 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1028 // Footnote definitions
1029 $blockpats[] = '\[\s*(\d+)\s*\]';
1033 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1037 $blockpats[] = '!{1,3}[^!]';
1039 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1040 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1042 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1043 . join("|", $blockpats)
1048 if ($markup_type != "block") {
1049 list ($orig, $repl) = $subs[$markup_type];
1050 return preg_replace($orig, $repl, $text);
1053 list ($orig, $repl) = $subs['inline'];
1056 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1057 // AnciennesR%E8glesDeFormatage and more
1058 // See http://www.pcre.org/pcre.txt LIMITATIONS
1059 while (preg_match($block_re, $text, $m)) {
1060 $text = substr($text, strlen($m[0]));
1061 list (,$leading_text, $block) = $m;
1064 if (strchr(" \t", $block[0])) {
1066 $prefix = "<pre>\n";
1067 $suffix = "\n</pre>\n";
1069 elseif ($block[0] == '|') {
1071 $prefix = "<?plugin OldStyleTable\n";
1074 elseif (strchr("#*;", $block[0])) {
1075 // Old-style list item
1076 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1077 list (,$ind,$bullet) = $m;
1078 $block = substr($block, strlen($m[0]));
1080 $indent = str_repeat(' ', strlen($ind));
1081 if ($bullet[0] == ';') {
1082 //$term = ltrim(substr($bullet, 1));
1083 //return $indent . $term . "\n" . $indent . ' ';
1084 $prefix = $ind . $bullet;
1087 $prefix = $indent . $bullet . ' ';
1089 elseif ($block[0] == '[') {
1090 // Footnote definition
1091 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1093 $block = substr($block, strlen($m[0]));
1094 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1096 elseif ($block[0] == '<') {
1098 // HACK: no inline markup...
1102 elseif ($block[0] == '!') {
1104 preg_match('/^!{1,3}/', $block, $m);
1106 $block = substr($block, strlen($m[0]));
1112 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1113 if ($block) $block = preg_replace($orig, $repl, $block);
1114 $out .= $leading_text;
1119 return $out . preg_replace($orig, $repl, $text);
1125 * Expand tabs in string.
1127 * Converts all tabs to (the appropriate number of) spaces.
1129 * @param string $str
1130 * @param integer $tab_width
1133 function expand_tabs($str, $tab_width = 8) {
1134 $split = split("\t", $str);
1135 $tail = array_pop($split);
1137 foreach ($split as $hunk) {
1139 $pos = strlen(strrchr($expanded, "\n")) - 1;
1140 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1142 return substr($expanded, 1) . $tail;
1146 * Split WikiWords in page names.
1148 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1149 * places like page titles. This is rumored to help search engines
1152 * @param $page string The page name.
1154 * @return string The split name.
1156 function SplitPagename ($page) {
1158 if (preg_match("/\s/", $page))
1159 return $page; // Already split --- don't split any more.
1161 // This algorithm is specialized for several languages.
1162 // (Thanks to Pierrick MEIGNEN)
1163 // Improvements for other languages welcome.
1166 // This mess splits between a lower-case letter followed by
1167 // either an upper-case or a numeral; except that it wont
1168 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1169 switch ($GLOBALS['LANG']) {
1174 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1177 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1180 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1181 // This the single-letter words 'I' and 'A' from any following
1182 // capitalized words.
1183 switch ($GLOBALS['LANG']) {
1185 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1188 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1191 // Split numerals from following letters.
1192 $RE[] = '/(\d)([[:alpha:]])/';
1193 // Split at subpage seperators. TBD in WikiTheme.php
1194 $RE[] = "/([^${sep}]+)(${sep})/";
1195 $RE[] = "/(${sep})([^${sep}]+)/";
1197 foreach ($RE as $key)
1198 $RE[$key] = pcre_fix_posix_classes($key);
1201 foreach ($RE as $regexp) {
1202 $page = preg_replace($regexp, '\\1 \\2', $page);
1207 function NoSuchRevision (&$request, $page, $version) {
1208 $html = HTML(HTML::h2(_("Revision Not Found")),
1209 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1210 $version, WikiLink($page, 'auto'))));
1211 include_once('lib/Template.php');
1212 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1218 * Get time offset for local time zone.
1220 * @param $time time_t Get offset for this time. Default: now.
1221 * @param $no_colon boolean Don't put colon between hours and minutes.
1222 * @return string Offset as a string in the format +HH:MM.
1224 function TimezoneOffset ($time = false, $no_colon = false) {
1225 if ($time === false)
1227 $secs = date('Z', $time);
1236 $colon = $no_colon ? '' : ':';
1237 $mins = intval(($secs + 30) / 60);
1238 return sprintf("%s%02d%s%02d",
1239 $sign, $mins / 60, $colon, $mins % 60);
1244 * Format time in ISO-8601 format.
1246 * @param $time time_t Time. Default: now.
1247 * @return string Date and time in ISO-8601 format.
1249 function Iso8601DateTime ($time = false) {
1250 if ($time === false)
1252 $tzoff = TimezoneOffset($time);
1253 $date = date('Y-m-d', $time);
1254 $time = date('H:i:s', $time);
1255 return $date . 'T' . $time . $tzoff;
1259 * Format time in RFC-2822 format.
1261 * @param $time time_t Time. Default: now.
1262 * @return string Date and time in RFC-2822 format.
1264 function Rfc2822DateTime ($time = false) {
1265 if ($time === false)
1267 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1271 * Format time in RFC-1123 format.
1273 * @param $time time_t Time. Default: now.
1274 * @return string Date and time in RFC-1123 format.
1276 function Rfc1123DateTime ($time = false) {
1277 if ($time === false)
1279 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1282 /** Parse date in RFC-1123 format.
1284 * According to RFC 1123 we must accept dates in the following
1287 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1288 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1289 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1291 * (Though we're only allowed to generate dates in the first format.)
1293 function ParseRfc1123DateTime ($timestr) {
1294 $timestr = trim($timestr);
1295 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1296 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1298 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1300 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1301 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1303 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1304 if ($year < 70) $year += 2000;
1305 elseif ($year < 100) $year += 1900;
1307 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1308 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1310 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1317 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1319 return false; // failed
1324 * Format time to standard 'ctime' format.
1326 * @param $time time_t Time. Default: now.
1327 * @return string Date and time.
1329 function CTime ($time = false)
1331 if ($time === false)
1333 return date("D M j H:i:s Y", $time);
1338 * Format number as kilobytes or bytes.
1339 * Short format is used for PageList
1340 * Long format is used in PageInfo
1342 * @param $bytes int. Default: 0.
1343 * @param $longformat bool. Default: false.
1344 * @return class FormattedText (XmlElement.php).
1346 function ByteFormatter ($bytes = 0, $longformat = false) {
1349 if ($bytes < 1024) {
1351 $size = fmt("%s b", $bytes);
1353 $size = fmt("%s bytes", $bytes);
1356 $kb = round($bytes / 1024, 1);
1358 $size = fmt("%s k", $kb);
1360 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1366 * Internationalized printf.
1368 * This is essentially the same as PHP's built-in printf
1369 * with the following exceptions:
1371 * <li> It passes the format string through gettext().
1372 * <li> It supports the argument reordering extensions.
1379 * __printf("Differences between versions %s and %s of %s",
1380 * $new_link, $old_link, $page_link);
1383 * Then in locale/po/de.po, one can reorder the printf arguments:
1386 * msgid "Differences between %s and %s of %s."
1387 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1390 * (Note that while PHP tries to expand $vars within double-quotes,
1391 * the values in msgstr undergo no such expansion, so the '$'s
1394 * One shouldn't use reordered arguments in the default format string.
1395 * Backslashes in the default string would be necessary to escape the
1396 * '$'s, and they'll cause all kinds of trouble....
1398 function __printf ($fmt) {
1399 $args = func_get_args();
1401 echo __vsprintf($fmt, $args);
1405 * Internationalized sprintf.
1407 * This is essentially the same as PHP's built-in printf with the
1408 * following exceptions:
1411 * <li> It passes the format string through gettext().
1412 * <li> It supports the argument reordering extensions.
1417 function __sprintf ($fmt) {
1418 $args = func_get_args();
1420 return __vsprintf($fmt, $args);
1424 * Internationalized vsprintf.
1426 * This is essentially the same as PHP's built-in printf with the
1427 * following exceptions:
1430 * <li> It passes the format string through gettext().
1431 * <li> It supports the argument reordering extensions.
1436 function __vsprintf ($fmt, $args) {
1437 $fmt = gettext($fmt);
1438 // PHP's sprintf doesn't support variable with specifiers,
1439 // like sprintf("%*s", 10, "x"); --- so we won't either.
1441 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1442 // Format string has '%2$s' style argument reordering.
1443 // PHP doesn't support this.
1444 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1445 // literal variable name substitution only to keep locale
1446 // strings uncluttered
1447 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1448 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1450 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1453 // Reorder arguments appropriately.
1454 foreach($m[1] as $argnum) {
1455 if ($argnum < 1 || $argnum > count($args))
1456 trigger_error(sprintf(_("%s: argument index out of range"),
1457 $argnum), E_USER_WARNING);
1458 $newargs[] = $args[$argnum - 1];
1463 // Not all PHP's have vsprintf, so...
1464 array_unshift($args, $fmt);
1465 return call_user_func_array('sprintf', $args);
1468 function file_mtime ($filename) {
1469 if ($stat = @stat($filename))
1475 function sort_file_mtime ($a, $b) {
1476 $ma = file_mtime($a);
1477 $mb = file_mtime($b);
1478 if (!$ma or !$mb or $ma == $mb) return 0;
1479 return ($ma > $mb) ? -1 : 1;
1484 * Build an array in $this->_fileList of files from $dirname.
1485 * Subdirectories are not traversed.
1487 * (This was a function LoadDir in lib/loadsave.php)
1488 * See also http://www.php.net/manual/en/function.readdir.php
1490 function getFiles($exclude='', $sortby='', $limit='') {
1491 $list = $this->_fileList;
1494 require_once('lib/PageList.php');
1495 switch (Pagelist::sortby($sortby, 'db')) {
1496 case 'pagename ASC': break;
1497 case 'pagename DESC':
1498 $list = array_reverse($list);
1501 usort($list,'sort_file_mtime');
1504 usort($list,'sort_file_mtime');
1505 $list = array_reverse($list);
1510 return array_splice($list, 0, $limit);
1514 function _filenameSelector($filename) {
1515 if (! $this->_pattern )
1518 if (! $this->_pcre_pattern )
1519 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1520 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1525 function fileSet($directory, $filepattern = false) {
1526 $this->_fileList = array();
1527 $this->_pattern = $filepattern;
1529 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1531 $this->_case = !isWindows();
1532 $this->_pathsep = '/';
1534 if (empty($directory)) {
1535 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1537 return; // early return
1540 @ $dir_handle = opendir($dir=$directory);
1541 if (empty($dir_handle)) {
1542 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1543 $dir), E_USER_NOTICE);
1544 return; // early return
1547 while ($filename = readdir($dir_handle)) {
1548 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1550 if ($this->_filenameSelector($filename)) {
1551 array_push($this->_fileList, "$filename");
1552 //trigger_error(sprintf(_("found file %s"), $filename),
1553 // E_USER_NOTICE); //debugging
1556 closedir($dir_handle);
1562 // expands a list containing regex's to its matching entries
1563 class ListRegexExpand {
1564 //var $match, $list, $index, $case_sensitive;
1565 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1566 $this->match = $match;
1567 $this->list = &$list;
1568 $this->case_sensitive = $case_sensitive;
1569 //$this->index = false;
1571 function listMatchCallback ($item, $key) {
1572 $quoted = str_replace('/','\/',$item);
1573 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1575 unset($this->list[$this->index]);
1576 $this->list[] = $item;
1579 function expandRegex ($index, &$pages) {
1580 $this->index = $index;
1581 array_walk($pages, array($this, 'listMatchCallback'));
1586 // Convert fileglob to regex style:
1587 // Convert some wildcards to pcre style, escape the rest
1588 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1589 // Fixed bug #994994: "/" in $glob.
1590 function glob_to_pcre ($glob) {
1591 // check simple case: no need to escape
1592 $escape = '\[](){}=!<>|:/';
1593 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1595 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1596 $glob = strtr($glob, "\\", "\xff");
1597 $glob = str_replace("/", "\\/", $glob);
1598 // first convert some unescaped expressions to pcre style: . => \.
1600 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1601 "\\1\xff\\2", $glob);
1604 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1605 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1606 if (!preg_match('/^[\?\*]/', $glob))
1608 if (!preg_match('/[\?\*]$/', $glob))
1611 // Fixes Bug 1182997
1612 // .*? handled above, now escape the rest
1613 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1614 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1616 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1618 $re = preg_replace('/\xff/', '', $re);
1622 function glob_match ($glob, $against, $case_sensitive = true) {
1623 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1627 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1628 $list = explode(',',$input);
1629 // expand wildcards from list of $allnames
1630 if (preg_match('/[\?\*]/',$input)) {
1631 // Optimizing loop invariants:
1632 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1633 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1635 if (preg_match('/[\?\*]/',$f)) {
1637 $expand = new ListRegexExpand($list,
1638 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1639 $expand->expandRegex($i, $allnames);
1646 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1647 function explodePageList($input, $include_empty=false, $sortby='pagename',
1648 $limit='', $exclude='') {
1649 include_once("lib/PageList.php");
1650 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1653 // Class introspections
1656 * Determine whether object is of a specified type.
1657 * In PHP builtin since 4.2.0 as is_a()
1658 * is_a() deprecated in PHP 5, in favor of instanceof operator
1660 * @param $object object An object.
1661 * @param $class string Class name.
1662 * @return bool True iff $object is a $class
1663 * or a sub-type of $class.
1665 function isa ($object, $class) {
1666 //if (check_php_version(5))
1667 // return $object instanceof $class;
1668 if (check_php_version(4,2) and !check_php_version(5))
1669 return is_a($object, $class);
1671 $lclass = check_php_version(5) ? $class : strtolower($class);
1672 return is_object($object)
1673 && ( strtolower(get_class($object)) == strtolower($class)
1674 || is_subclass_of($object, $lclass) );
1677 /** Determine whether (possible) object has method.
1679 * @param $object mixed Object
1680 * @param $method string Method name
1681 * @return bool True iff $object is an object with has method $method.
1683 function can ($object, $method) {
1684 return is_object($object) && method_exists($object, strtolower($method));
1687 /** Determine whether a function is okay to use.
1689 * Some providers (e.g. Lycos) disable some of PHP functions for
1690 * "security reasons." This makes those functions, of course,
1691 * unusable, despite the fact the function_exists() says they
1694 * This function test to see if a function exists and is not
1695 * disallowed by PHP's disable_functions config setting.
1697 * @param string $function_name Function name
1698 * @return bool True iff function can be used.
1700 function function_usable($function_name) {
1702 if (!is_array($disabled)) {
1703 $disabled = array();
1704 // Use get_cfg_var since ini_get() is one of the disabled functions
1705 // (on Lycos, at least.)
1706 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1707 foreach ($split as $f)
1708 $disabled[strtolower($f)] = true;
1711 return ( function_exists($function_name)
1712 and ! isset($disabled[strtolower($function_name)])
1719 * This is used for generating ETags.
1721 function wikihash ($x) {
1722 if (is_scalar($x)) {
1725 elseif (is_array($x)) {
1727 return md5(serialize($x));
1729 elseif (is_object($x)) {
1732 trigger_error("Can't hash $x", E_USER_ERROR);
1737 * Seed the random number generator.
1739 * better_srand() ensures the randomizer is seeded only once.
1741 * How random do you want it? See:
1742 * http://www.php.net/manual/en/function.srand.php
1743 * http://www.php.net/manual/en/function.mt-srand.php
1745 function better_srand($seed = '') {
1746 static $wascalled = FALSE;
1748 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1749 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1751 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1755 function rand_ascii($length = 1) {
1758 for ($i = 1; $i <= $length; $i++) {
1759 // return only typeable 7 bit ascii, avoid quotes
1760 if (function_exists('mt_rand'))
1761 $s .= chr(mt_rand(40, 126));
1763 // the usually bad glibc srand()
1764 $s .= chr(rand(40, 126));
1769 /* by Dan Frankowski.
1771 function rand_ascii_readable ($length = 6) {
1772 // Pick a few random letters or numbers
1775 // Don't use 1lI0O, because they're hard to read
1776 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1777 $letter_len = strlen($letters);
1778 for ($i=0; $i < $length; $i++) {
1779 if (function_exists('mt_rand'))
1780 $word .= $letters[mt_rand(0, $letter_len-1)];
1782 $word .= $letters[rand(0, $letter_len-1)];
1788 * Recursively count all non-empty elements
1789 * in array of any dimension or mixed - i.e.
1790 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1791 * See http://www.php.net/manual/en/function.count.php
1793 function count_all($arg) {
1794 // skip if argument is empty
1796 //print_r($arg); //debugging
1798 // not an array, return 1 (base case)
1801 // else call recursively for all elements $arg
1802 foreach($arg as $key => $val)
1803 $count += count_all($val);
1808 function isSubPage($pagename) {
1809 return (strstr($pagename, SUBPAGE_SEPARATOR));
1812 function subPageSlice($pagename, $pos) {
1813 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1814 $pages = array_slice($pages,$pos,1);
1821 * Class for "popping up" and alert box. (Except that right now, it doesn't
1825 * This is a hackish and needs to be refactored. However it would be nice to
1826 * unify all the different methods we use for showing Alerts and Dialogs.
1827 * (E.g. "Page deleted", login form, ...)
1832 * @param object $request
1833 * @param mixed $head Header ("title") for alert box.
1834 * @param mixed $body The text in the alert box.
1835 * @param hash $buttons An array mapping button labels to URLs.
1836 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1838 function Alert($head, $body, $buttons=false) {
1839 if ($buttons === false)
1842 if (is_array($body)) {
1844 foreach ($body as $li) {
1845 $html->pushContent(HTML::li($li));
1849 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1850 $this->_buttons = $buttons;
1854 * Show the alert box.
1859 $tokens = $this->_tokens;
1860 $tokens['BUTTONS'] = $this->_getButtons();
1862 $request->discardOutput();
1863 $tmpl = new Template('dialog', $request, $tokens);
1869 function _getButtons() {
1872 $buttons = $this->_buttons;
1874 $buttons = array(_("Okay") => $request->getURLtoSelf());
1877 foreach ($buttons as $label => $url)
1878 print "$label $url\n";
1879 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1880 return new XmlContent($out);
1885 // 1.3.9-p1 => 1030.091
1886 // 1.3.10pre => 1030.099
1887 // 1.3.11pre-20041120 => 1030.1120041120
1888 // 1.3.12-rc1 => 1030.119
1889 function phpwiki_version() {
1890 static $PHPWIKI_VERSION;
1891 if (!isset($PHPWIKI_VERSION)) {
1892 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1893 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1894 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1895 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1896 $PHPWIKI_VERSION -= 0.01;
1898 return $PHPWIKI_VERSION;
1901 function phpwiki_gzhandler($ob) {
1902 if (function_exists('gzencode'))
1903 $ob = gzencode($ob);
1904 $GLOBALS['request']->_ob_get_length = strlen($ob);
1905 if (!headers_sent()) {
1906 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1911 function isWikiWord($word) {
1912 global $WikiNameRegexp;
1913 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1914 return preg_match("/^$WikiNameRegexp\$/",$word);
1917 // needed to store serialized objects-values only (perm, pref)
1918 function obj2hash ($obj, $exclude = false, $fields = false) {
1920 if (! $fields ) $fields = get_object_vars($obj);
1921 foreach ($fields as $key => $val) {
1922 if (is_array($exclude)) {
1923 if (in_array($key, $exclude)) continue;
1931 * isUtf8String($string) - cheap utf-8 detection
1933 * segfaults for strings longer than 10kb!
1934 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1935 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1937 function isUtf8String( $s ) {
1938 $ptrASCII = '[\x00-\x7F]';
1939 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1940 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1941 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1942 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1943 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1944 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1948 * Check for UTF-8 URLs; Internet Explorer produces these if you
1949 * type non-ASCII chars in the URL bar or follow unescaped links.
1950 * Requires urldecoded pagename.
1951 * Fixes sf.net bug #953949
1953 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1955 function fixTitleEncoding( $s ) {
1960 if (empty($s)) return $s;
1962 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1964 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1965 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1967 $isutf = ($ishigh ? isUtf8String($s) : true);
1968 $locharset = strtolower($charset);
1970 if( $locharset != "utf-8" and $ishigh and $isutf )
1971 $s = charset_convert('UTF-8', $locharset, $s);
1972 if ($locharset == "utf-8" and $ishigh and !$isutf )
1973 return utf8_encode( $s );
1975 // Other languages can safely leave this function, or replace
1976 // it with one to detect and convert another legacy encoding.
1981 * MySQL fulltext index doesn't grok utf-8, so we
1982 * need to fold cases and convert to hex.
1983 * src: languages/Language.php:stripForSearch() from mediawiki
1986 function stripForSearch( $string ) {
1987 global $wikiLowerChars;
1988 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1989 return preg_replace(
1990 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1991 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1997 * Workaround for allow_url_fopen, to get the content of an external URI.
1998 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1999 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2001 function url_get_contents( $uri ) {
2002 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2003 return @file_get_contents($uri);
2005 require_once("lib/HttpClient.php");
2006 $bits = parse_url($uri);
2007 $host = $bits['host'];
2008 $port = isset($bits['port']) ? $bits['port'] : 80;
2009 $path = isset($bits['path']) ? $bits['path'] : '/';
2010 if (isset($bits['query'])) {
2011 $path .= '?'.$bits['query'];
2013 $client = new HttpClient($host, $port);
2014 $client->use_gzip = false;
2015 if (!$client->get($path)) {
2018 return $client->getContent();
2024 * Generate consecutively named strings:
2025 * Name, Name2, Name3, ...
2027 function GenerateId($name) {
2028 static $ids = array();
2029 if (empty($ids[$name])) {
2034 return $name . $ids[$name];
2038 // from IncludePage. To be of general use.
2039 // content: string or array of strings
2040 function firstNWordsOfContent( $n, $content ) {
2041 if ($content and $n > 0) {
2042 if (is_array($content)) {
2043 // fixme: return a list of lines then?
2044 //$content = join("\n", $content);
2045 //$return_array = true;
2047 foreach ($content as $line) {
2048 $words = explode(' ', $line);
2049 if ($wordcount + count($words) > $n) {
2050 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2051 . sprintf(_("... (first %s words)"), $n);
2054 $wordcount += count($words);
2060 // fixme: use better whitespace/word seperators
2061 $words = explode(' ', $content);
2062 if (count($words) > $n) {
2063 return join(' ', array_slice($words, 0, $n))
2064 . sprintf(_("... (first %s words)"), $n);
2074 // moved from lib/plugin/IncludePage.php
2075 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2076 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2078 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2079 . " \\s*$\\n?" // possible blank lines
2080 . " ( (?: ^.*\\n? )*? )" // some lines
2081 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2082 implode("\n", $content),
2084 // Strip trailing blanks lines and ---- <hr>s
2085 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2087 $text = $match[1] . $section ."\n". $text;
2088 return explode("\n", $text);
2091 $mesg = $page ." ". $section;
2094 return array(sprintf(_("<%s: no such section>"), $mesg));
2097 // Extract the first $sections sections of the page
2098 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2100 $mycontent = $content;
2103 while ($sections > 0) {
2105 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2106 . " \\s*$\\n?" // possible blank lines
2107 . " ( (?: ^.*\\n? )*? )" // some lines
2108 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2109 implode("\n", $mycontent),
2111 $section = $match[2];
2112 // Strip trailing blanks lines and ---- <hr>s
2113 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2115 $text = $match[1] . $section ."\n". $text;
2118 $mycontent = explode("\n", $match[4]);
2120 if ($sections === 0) {
2121 return explode("\n", $result);
2127 // use this faster version: only load ExternalReferrer if we came from an external referrer
2128 function isExternalReferrer(&$request) {
2129 if ($referrer = $request->get('HTTP_REFERER')) {
2130 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2131 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2132 require_once("lib/ExternalReferrer.php");
2133 $se = new SearchEngines();
2134 return $se->parseSearchQuery($referrer);
2136 //if (DEBUG) return array('query' => 'wiki');
2141 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2143 function loadPhpExtension($extension) {
2144 if (!extension_loaded($extension)) {
2145 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2146 $soname = ($isWindows ? 'php_' : '')
2148 . ($isWindows ? '.dll' : '.so');
2152 return extension_loaded($extension);
2155 function charset_convert($from, $to, $data) {
2157 //$wikicharset = strtolower($CHARSET);
2158 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2159 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2160 return utf8_decode($data);
2161 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2162 return utf8_encode($data);
2164 if (loadPhpExtension("iconv")) {
2165 $tmpdata = iconv($from, $to, $data);
2167 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2171 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2176 function string_starts_with($string, $prefix) {
2177 return (substr($string, 0, strlen($prefix)) == $prefix);
2179 function string_ends_with($string, $suffix) {
2180 return (substr($string, -strlen($suffix)) == $suffix);
2182 function array_remove($arr,$value) {
2183 return array_values(array_diff($arr,array($value)));
2187 * Ensure that the script will have another $secs time left.
2188 * Works only if safe_mode is off.
2189 * For example not to timeout on waiting socket connections.
2190 * Use the socket timeout as arg.
2192 function longer_timeout($secs = 30) {
2193 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2194 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2195 if ($timeleft < $secs)
2196 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2199 function printSimpleTrace($bt) {
2201 echo "\nTraceback:\n";
2202 if (function_exists('debug_print_backtrace')) { // >= 5
2203 debug_print_backtrace();
2205 foreach ($bt as $i => $elem) {
2206 if (!array_key_exists('file', $elem)) {
2209 //echo join(" ",array_values($elem)),"\n";
2210 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2216 * Return the used process memory, in bytes.
2217 * Enable the section which will work for you. They are very slow.
2218 * Special quirks for Windows: Requires cygwin.
2220 function getMemoryUsage() {
2221 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2222 if (function_exists('memory_get_usage') and memory_get_usage()) {
2223 return memory_get_usage();
2224 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2225 $mem = $u['ru_maxrss'];
2226 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2227 // what we want is the process memory only: apache or php (if CGI)
2230 // win32_ps_stat_proc, win32_ps_stat_mem
2231 if (function_exists('win32_ps_list_procs')) {
2232 $info = win32_ps_stat_proc($pid);
2233 $memstr = $info['mem']['working_set_size'];
2235 // This works only if it's a cygwin process (apache or php).
2236 // Requires a newer cygwin
2237 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2239 // if it's native windows use something like this:
2240 // (requires pslist from sysinternals.com, grep, sed and perl)
2241 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2243 return (integer) trim($memstr);
2246 //%MEM: Percentage of total memory in use by this process
2247 //VSZ: Total virtual memory size, in 1K blocks.
2248 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2249 //CPU time used by process since it started.
2250 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2251 $memstr = exec("ps -orss -p $pid|sed 1d");
2252 return (integer) trim($memstr);
2257 * @param var $needle
2258 * @param array $haystack one-dimensional numeric array only, no hash
2260 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2261 It will return false if not found or the index where it was found.
2262 From dennis.decoene@moveit.be http://www.php.net/array_search
2264 function binary_search($needle, $haystack) {
2265 $high = count($haystack);
2268 while (($high - $low) > 1) {
2269 $probe = floor(($high + $low) / 2);
2270 if ($haystack[$probe] < $needle) {
2272 } elseif ($haystack[$probe] == $needle) {
2273 $high = $low = $probe;
2279 if ($high == count($haystack) || $haystack[$high] != $needle) {
2286 function is_localhost($url = false) {
2288 global $HTTP_SERVER_VARS;
2289 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2294 * Take a string and quote it sufficiently to be passed as a Javascript
2295 * string between ''s
2297 function javascript_quote_string($s) {
2298 return str_replace("'", "\'", $s);
2301 function isSerialized($s) {
2302 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2306 * Take a string and return an array of pairs (attribute name, attribute value)
2308 * We allow attributes with or without double quotes (")
2309 * Attribute-value pairs may be separated by space or comma
2310 * border=1, cellpadding="5"
2311 * border=1 cellpadding="5"
2312 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2313 * What will not work is style with comma inside, e. g.
2314 / style="font-family: Verdana, Arial, Helvetica, sans-serif"
2316 function parse_attributes($line) {
2317 $line = strtolower($line);
2318 $line = str_replace(",", "", $line);
2319 $attr_chunks = preg_split("/\s* \s*/", $line);
2321 foreach ($attr_chunks as $attr_pair) {
2322 if (empty($attr_pair)) continue;
2323 $key_val = preg_split("/\s*=\s*/", $attr_pair);
2324 if (!empty($key_val[1]))
2325 $options[trim($key_val[0])] = trim(str_replace("\"", "", $key_val[1]));
2331 * Returns true if the filename ends with an image suffix.
2332 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2334 function is_image ($filename) {
2336 if (defined('INLINE_IMAGES')) {
2337 $inline_images = INLINE_IMAGES;
2339 $inline_images = "png|jpg|jpeg|gif";
2342 foreach (explode("|", $inline_images) as $suffix) {
2343 if (string_ends_with($filename, "." . $suffix)) {
2350 // (c-file-style: "gnu")
2354 // c-basic-offset: 4
2355 // c-hanging-comment-ender-p: nil
2356 // indent-tabs-mode: nil