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 = "") {
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 = "";
418 $arr = split(' ',$url);
420 $link = HTML::img(array('src' => $url, 'alt' => $alt));
422 $link = HTML::img(array('src' => $url,
423 'alt' => $alt, 'title' => $alt));
425 if (count($arr) > 1) {
428 foreach ($arr as $attr) {
429 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
430 $link->setAttr('width',$m[1]);
431 $link->setAttr('height',$m[1]);
433 elseif (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
434 $link->setAttr('width',$m[1]);
435 $link->setAttr('height',$m[2]);
437 elseif (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
438 $link->setAttr('width',$m[1]);
439 elseif (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
440 $link->setAttr('height',$m[1]);
441 elseif (preg_match('/^border=(\d+)$/',$attr,$m))
442 $link->setAttr('border',$m[1]);
443 elseif (preg_match('/^align=(\w+)$/',$attr,$m))
444 $link->setAttr('align',$m[1]);
445 elseif (preg_match('/^hspace=(\d+)$/',$attr,$m))
446 $link->setAttr('hspace',$m[1]);
447 elseif (preg_match('/^vspace=(\d+)$/',$attr,$m))
448 $link->setAttr('vspace',$m[1]);
451 if(! IsSafeURL($url)) {
452 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
453 _("BAD URL -- remove all of <, >, \"")));
456 $link->setAttr('src', $url);
461 // Check width and height as spam countermeasure
462 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
463 //$width = (int) $width; // px or % or other suffix
464 //$height = (int) $height;
465 if (($width < 3 and $height < 10) or
466 ($height < 3 and $width < 20) or
467 ($height < 7 and $width < 7))
469 trigger_error(_("Invalid image size"), E_USER_WARNING);
474 // Prepare for getimagesize($url)
475 // $url only valid for external urls, otherwise local path
476 // Older php versions crash here with certain png's:
477 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
478 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
479 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
480 if (DISABLE_GETIMAGESIZE)
482 elseif (! preg_match("/\.$force_img$/i", $url))
483 ; // only valid image extensions or scripts assumed to generate images
484 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
485 ; // it's safe to assume that this will fail.
486 elseif (preg_match("/^http/",$url)) { // external url
487 $size = @getimagesize($url);
488 } else { // local file
489 if (file_exists($file = NormalizeLocalFileName($url))) { // here
490 $size = @getimagesize($file);
491 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
492 $size = @getimagesize($file);
493 $link->setAttr('src', rawurldecode($url));
494 } elseif (string_starts_with($url, getUploadDataPath())) { // there
495 $file = substr($file, strlen(getUploadDataPath()));
496 $size = @getimagesize(getUploadFilePath().rawurldecode($file));
497 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
498 } else { // elsewhere
499 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
505 if (($width < 3 and $height < 10)
506 or ($height < 3 and $width < 20)
507 or ($height < 7 and $width < 7))
509 trigger_error(_("Invalid image size"), E_USER_WARNING);
515 $link->setAttr('class', 'inlineimage');
517 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
518 * png|jpg|gif|jpeg|bmp|pl|cgi
519 * Note: Allow cgi's (pl,cgi) returning images.
521 if (!preg_match("/\.(".$force_img.")/i", $url)) {
522 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
523 // => HTML::object(array('src' => $url)) ...;
524 return ImgObject($link, $ori_url);
530 * <object> / <embed> tags instead of <img> for all non-image extensions
532 * Called by LinkImage(), not directly.
533 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
534 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
535 * $alt may be an alternate img
536 * TODO: Need to unify with WikiPluginCached::embedObject()
538 * Note that Safari 1.0 will crash with <object>, so use only <embed>
539 * http://www.alleged.org.uk/pdc/2002/svg-object.html
541 * Allowed object tags:
542 * DATA=URI (object data)
543 * CLASSID=URI (location of implementation)
544 * ARCHIVE=CDATA (archive files)
545 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
546 * WIDTH=Length (object width)
547 * HEIGHT=Length (object height)
548 * NAME=CDATA (name for form submission)
549 * USEMAP=URI (client-side image map)
550 * TYPE=ContentType (content-type of object)
551 * CODETYPE=ContentType (content-type of code)
552 * STANDBY=Text (message to show while loading)
553 * TABINDEX=NUMBER (position in tabbing order)
554 * DECLARE (do not instantiate object)
555 * The rest is added as <param name="" value="" /> tags
557 function ImgObject($img, $url) {
558 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
559 $args = split(' ', $url);
561 if (count($args) >= 1) {
562 $url = array_shift($args);
564 foreach ($args as $attr) {
565 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
566 "codetype,standby,tabindex,declare") as $param)
568 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
569 $img->setAttr($param, $m[1]);
575 // now all remaing args are added as <param> to the object
576 foreach ($args as $attr) {
577 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
578 $params[] = HTML::param(array('name' => $m[1],
583 $type = $img->getAttr('type');
585 // TODO: map extension to mime-types if type is not given and php < 4.3
586 if (function_exists('mime_content_type'))
587 $type = mime_content_type($url);
589 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
591 $object->setAttr('class', 'inlineobject');
593 foreach ($params as $param) $object->pushContent($param);
595 if (isBrowserSafari()) {
596 return HTML::embed($object->_attr, $object->_content);
598 $object->pushContent(HTML::embed($object->_attr));
605 // var in php5 deprecated
607 $this->items = array();
610 function push($item) {
611 $this->items[$this->size] = $item;
617 if ($this->size == 0) {
618 return false; // stack is empty
621 return $this->items[$this->size];
630 return $this->items[$this->size - 1];
636 // end class definition
638 function SplitQueryArgs ($query_args = '')
640 // FIXME: use the arg-seperator which might not be &
641 $split_args = split('&', $query_args);
643 while (list($key, $val) = each($split_args))
644 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
645 $args[$m[1]] = $m[2];
649 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
652 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
653 return HTML::strong(array('class' => 'rawurl'),
654 HTML::u(array('class' => 'baduri'),
655 _("BAD phpwiki: URL")));
659 $pagename = urldecode($m[1]);
662 if (empty($pagename) &&
663 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
664 // Convert old style links (to not break diff links in
666 $pagename = urldecode($m[2]);
667 $args = array("action" => $m[1]);
670 $args = SplitQueryArgs($qargs);
673 if (empty($pagename))
674 $pagename = $GLOBALS['request']->getArg('pagename');
676 if (isset($args['action']) && $args['action'] == 'browse')
677 unset($args['action']);
680 if (empty($args['action']))
682 else if (is_safe_action($args['action']))
683 $class = 'wikiaction';
685 if (empty($args['action']) || is_safe_action($args['action']))
686 $class = 'wikiaction';
688 // Don't allow administrative links on unlocked pages.
689 $dbi = $GLOBALS['request']->getDbh();
690 $page = $dbi->getPage($basepage ? $basepage : $pagename);
691 if (!$page->get('locked'))
692 return HTML::span(array('class' => 'wikiunsafe'),
693 HTML::u(_("Lock page to enable link")));
694 $class = 'wikiadmin';
698 $text = HTML::span(array('class' => 'rawurl'), $url);
700 $wikipage = new WikiPageName($pagename);
701 if (!$wikipage->isValid()) {
703 return $WikiTheme->linkBadWikiWord($wikipage, $url);
706 return HTML::a(array('href' => WikiURL($pagename, $args),
712 * A class to assist in parsing wiki pagenames.
714 * Now with subpages and anchors, parsing and passing around
715 * pagenames is more complicated. This should help.
719 /** Short name for page.
721 * This is the value of $name passed to the constructor.
722 * (For use, e.g. as a default label for links to the page.)
726 /** The full page name.
728 * This is the full name of the page (without anchor).
734 * This is the referenced anchor within the page, or the empty string.
740 * @param mixed $name Page name.
741 * WikiDB_Page, WikiDB_PageRevision, or string.
742 * This can be a relative subpage name (like '/SubPage'),
743 * or can be the empty string to refer to the $basename.
745 * @param string $anchor For links to anchors in page.
747 * @param mixed $basename Page name from which to interpret
748 * relative or other non-fully-specified page names.
750 function WikiPageName($name, $basename=false, $anchor=false) {
751 if (is_string($name)) {
752 $this->shortName = $name;
753 if (strstr($name, ':')) {
754 list($moniker, $shortName) = split (":", $name, 2);
755 $map = getInterwikiMap(); // allow overrides to custom maps
756 if (isset($map->_map[$moniker])) {
757 $url = $map->_map[$moniker];
758 if (strstr($url, '%s'))
759 $url = sprintf($url, $shortName);
763 // expand Talk or User, but not to absolute urls!
764 if (strstr($url, '//')) {
765 if ($moniker == 'Talk')
766 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
767 elseif ($moniker == 'User')
772 if (strstr($shortName, '?')) {
773 list($shortName, $dummy) = split("\?", $shortName, 2);
775 $this->shortName = $shortName;
778 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
779 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
781 $name = $this->_pagename($basename) . $name;
783 $name = $this->_normalize_bad_pagename($name);
784 $this->shortName = $name;
789 $name = $this->_pagename($name);
790 $this->shortName = $name;
793 $this->name = $this->_check($name);
794 $this->anchor = (string)$anchor;
801 function getParent() {
803 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
805 return substr($name, 0, -strlen($tail));
808 function isValid($strict = false) {
810 return !isset($this->_errors);
811 return (is_string($this->name) and $this->name != '');
814 function getWarnings() {
816 if (isset($this->_warnings))
817 $warnings = array_merge($warnings, $this->_warnings);
818 if (isset($this->_errors))
819 $warnings = array_merge($warnings, $this->_errors);
823 return sprintf(_("'%s': Bad page name: %s"),
824 $this->shortName, join(', ', $warnings));
827 function _pagename($page) {
828 if (isa($page, 'WikiDB_Page'))
829 return $page->getName();
830 elseif (isa($page, 'WikiDB_PageRevision'))
831 return $page->getPageName();
832 elseif (isa($page, 'WikiPageName'))
834 // '0' or e.g. '1984' should be allowed though
835 if (!is_string($page) and !is_integer($page)) {
836 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
837 $page, gettype($page), get_class($page)),
840 //assert(is_string($page));
844 function _normalize_bad_pagename($name) {
845 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
847 // Punt... You really shouldn't get here.
850 return $request->getArg('pagename');
852 assert($name[0] == SUBPAGE_SEPARATOR);
853 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
854 return substr($name, 1);
858 * Compress internal white-space to single space character.
860 * This leads to problems with loading a foreign charset pagename,
861 * which cannot be deleted anymore, because unknown chars are compressed.
862 * So BEFORE importing a file _check must be done !!!
864 function _check($pagename) {
865 // Compress internal white-space to single space character.
866 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
867 if ($pagename != $orig)
868 $this->_warnings[] = _("White space converted to single space");
870 // Delete any control characters.
871 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
872 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
873 if ($pagename != $orig)
874 $this->_errors[] = _("Control characters not allowed");
877 // Strip leading and trailing white-space.
878 $pagename = trim($pagename);
881 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
882 $pagename = substr($pagename, 1);
883 if ($pagename != $orig)
884 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
886 // ";" is urlencoded, so safe from php arg-delim problems
887 /*if (strstr($pagename, ';')) {
888 $this->_warnings[] = _("';' is deprecated");
889 $pagename = str_replace(';', '', $pagename);
892 // not only for SQL, also to restrict url length
893 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
894 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
895 $this->_errors[] = _("too long");
898 // disallow some chars only on file and cvs
899 if ((DATABASE_TYPE == 'cvs'
900 or DATABASE_TYPE == 'file'
901 or DATABASE_TYPE == 'flatfile')
902 and preg_match('/(:|\.\.)/', $pagename, $m))
904 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
905 $pagename = str_replace('..', '', $pagename);
906 $pagename = str_replace(':', '', $pagename);
914 * Convert old page markup to new-style markup.
916 * @param string $text Old-style wiki markup.
918 * @param string $markup_type
920 * <dt><code>"block"</code> <dd>Convert all markup.
921 * <dt><code>"inline"</code> <dd>Convert only inline markup.
922 * <dt><code>"links"</code> <dd>Convert only link markup.
925 * @return string New-style wiki markup.
927 * @bugs Footnotes don't work quite as before (esp if there are
928 * multiple references to the same footnote. But close enough,
929 * probably for now....
930 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
931 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
932 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
933 * also known to crash, even with Apache1.
935 function ConvertOldMarkup ($text, $markup_type = "block") {
941 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
942 // AnciennesR%E8glesDeFormatage crashes.
943 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
944 // also known to crash, even with Apache1.
946 // I suspect this only to crash with Apache2 and IIS.
947 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
948 and preg_match("/plugin CreateToc/", $text))
950 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
951 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
952 ._("Skipped."), E_USER_WARNING);
954 //if (!DEBUG) return $text;
959 /*****************************************************************
960 * Conversions for inline markup:
967 // escape escaped brackets
971 // change ! escapes to ~'s.
972 global $WikiNameRegexp, $request;
973 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
974 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
975 if (check_php_version(4,3,9)) {
976 $map = getInterwikiMap();
977 if ($map_regex = $map->getRegexp())
978 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
980 $bang_esc[] = $WikiNameRegexp;
981 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
984 $subs["links"] = array($orig, $repl);
986 // Temporarily URL-encode pairs of underscores in links to hide
987 // them from the re for bold markup.
988 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
989 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
992 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
995 // Convert footnote references.
996 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
997 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
999 // Convert old style emphases to HTML style emphasis.
1000 $orig[] = '/__(.*?)__/';
1001 $repl[] = '<strong>\\1</strong>';
1002 $orig[] = "/''(.*?)''/";
1003 $repl[] = '<em>\\1</em>';
1005 // Escape nestled markup.
1006 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1009 // in old markup headings only allowed at beginning of line
1013 // Convert URL-encoded pairs of underscores in links back to
1014 // real underscores after bold markup has been converted.
1015 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1016 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1018 $subs["inline"] = array($orig, $repl);
1020 /*****************************************************************
1021 * Patterns which match block markup constructs which take
1022 * special handling...
1026 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1028 $blockpats[] = '\|(?:.*\n\|)*';
1031 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1033 // Footnote definitions
1034 $blockpats[] = '\[\s*(\d+)\s*\]';
1038 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1042 $blockpats[] = '!{1,3}[^!]';
1044 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1045 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1047 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1048 . join("|", $blockpats)
1053 if ($markup_type != "block") {
1054 list ($orig, $repl) = $subs[$markup_type];
1055 return preg_replace($orig, $repl, $text);
1058 list ($orig, $repl) = $subs['inline'];
1061 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1062 // AnciennesR%E8glesDeFormatage and more
1063 // See http://www.pcre.org/pcre.txt LIMITATIONS
1064 while (preg_match($block_re, $text, $m)) {
1065 $text = substr($text, strlen($m[0]));
1066 list (,$leading_text, $block) = $m;
1069 if (strchr(" \t", $block[0])) {
1071 $prefix = "<pre>\n";
1072 $suffix = "\n</pre>\n";
1074 elseif ($block[0] == '|') {
1076 $prefix = "<?plugin OldStyleTable\n";
1079 elseif (strchr("#*;", $block[0])) {
1080 // Old-style list item
1081 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1082 list (,$ind,$bullet) = $m;
1083 $block = substr($block, strlen($m[0]));
1085 $indent = str_repeat(' ', strlen($ind));
1086 if ($bullet[0] == ';') {
1087 //$term = ltrim(substr($bullet, 1));
1088 //return $indent . $term . "\n" . $indent . ' ';
1089 $prefix = $ind . $bullet;
1092 $prefix = $indent . $bullet . ' ';
1094 elseif ($block[0] == '[') {
1095 // Footnote definition
1096 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1098 $block = substr($block, strlen($m[0]));
1099 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1101 elseif ($block[0] == '<') {
1103 // HACK: no inline markup...
1107 elseif ($block[0] == '!') {
1109 preg_match('/^!{1,3}/', $block, $m);
1111 $block = substr($block, strlen($m[0]));
1117 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1118 if ($block) $block = preg_replace($orig, $repl, $block);
1119 $out .= $leading_text;
1124 return $out . preg_replace($orig, $repl, $text);
1130 * Expand tabs in string.
1132 * Converts all tabs to (the appropriate number of) spaces.
1134 * @param string $str
1135 * @param integer $tab_width
1138 function expand_tabs($str, $tab_width = 8) {
1139 $split = split("\t", $str);
1140 $tail = array_pop($split);
1142 foreach ($split as $hunk) {
1144 $pos = strlen(strrchr($expanded, "\n")) - 1;
1145 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1147 return substr($expanded, 1) . $tail;
1151 * Split WikiWords in page names.
1153 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1154 * places like page titles. This is rumored to help search engines
1157 * @param $page string The page name.
1159 * @return string The split name.
1161 function SplitPagename ($page) {
1163 if (preg_match("/\s/", $page))
1164 return $page; // Already split --- don't split any more.
1166 // This algorithm is specialized for several languages.
1167 // (Thanks to Pierrick MEIGNEN)
1168 // Improvements for other languages welcome.
1171 // This mess splits between a lower-case letter followed by
1172 // either an upper-case or a numeral; except that it wont
1173 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1174 switch ($GLOBALS['LANG']) {
1179 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1182 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1185 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1186 // This the single-letter words 'I' and 'A' from any following
1187 // capitalized words.
1188 switch ($GLOBALS['LANG']) {
1190 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1193 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1196 // Split numerals from following letters.
1197 $RE[] = '/(\d)([[:alpha:]])/';
1198 // Split at subpage seperators. TBD in WikiTheme.php
1199 $RE[] = "/([^${sep}]+)(${sep})/";
1200 $RE[] = "/(${sep})([^${sep}]+)/";
1202 foreach ($RE as $key)
1203 $RE[$key] = pcre_fix_posix_classes($key);
1206 foreach ($RE as $regexp) {
1207 $page = preg_replace($regexp, '\\1 \\2', $page);
1212 function NoSuchRevision (&$request, $page, $version) {
1213 $html = HTML(HTML::h2(_("Revision Not Found")),
1214 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1215 $version, WikiLink($page, 'auto'))));
1216 include_once('lib/Template.php');
1217 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1223 * Get time offset for local time zone.
1225 * @param $time time_t Get offset for this time. Default: now.
1226 * @param $no_colon boolean Don't put colon between hours and minutes.
1227 * @return string Offset as a string in the format +HH:MM.
1229 function TimezoneOffset ($time = false, $no_colon = false) {
1230 if ($time === false)
1232 $secs = date('Z', $time);
1241 $colon = $no_colon ? '' : ':';
1242 $mins = intval(($secs + 30) / 60);
1243 return sprintf("%s%02d%s%02d",
1244 $sign, $mins / 60, $colon, $mins % 60);
1249 * Format time in ISO-8601 format.
1251 * @param $time time_t Time. Default: now.
1252 * @return string Date and time in ISO-8601 format.
1254 function Iso8601DateTime ($time = false) {
1255 if ($time === false)
1257 $tzoff = TimezoneOffset($time);
1258 $date = date('Y-m-d', $time);
1259 $time = date('H:i:s', $time);
1260 return $date . 'T' . $time . $tzoff;
1264 * Format time in RFC-2822 format.
1266 * @param $time time_t Time. Default: now.
1267 * @return string Date and time in RFC-2822 format.
1269 function Rfc2822DateTime ($time = false) {
1270 if ($time === false)
1272 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1276 * Format time in RFC-1123 format.
1278 * @param $time time_t Time. Default: now.
1279 * @return string Date and time in RFC-1123 format.
1281 function Rfc1123DateTime ($time = false) {
1282 if ($time === false)
1284 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1287 /** Parse date in RFC-1123 format.
1289 * According to RFC 1123 we must accept dates in the following
1292 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1293 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1294 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1296 * (Though we're only allowed to generate dates in the first format.)
1298 function ParseRfc1123DateTime ($timestr) {
1299 $timestr = trim($timestr);
1300 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1301 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1303 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1305 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1306 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1308 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1309 if ($year < 70) $year += 2000;
1310 elseif ($year < 100) $year += 1900;
1312 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1313 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1315 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1322 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1324 return false; // failed
1329 * Format time to standard 'ctime' format.
1331 * @param $time time_t Time. Default: now.
1332 * @return string Date and time.
1334 function CTime ($time = false)
1336 if ($time === false)
1338 return date("D M j H:i:s Y", $time);
1343 * Format number as kilobytes or bytes.
1344 * Short format is used for PageList
1345 * Long format is used in PageInfo
1347 * @param $bytes int. Default: 0.
1348 * @param $longformat bool. Default: false.
1349 * @return class FormattedText (XmlElement.php).
1351 function ByteFormatter ($bytes = 0, $longformat = false) {
1354 if ($bytes < 1024) {
1356 $size = fmt("%s b", $bytes);
1358 $size = fmt("%s bytes", $bytes);
1361 $kb = round($bytes / 1024, 1);
1363 $size = fmt("%s k", $kb);
1365 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1371 * Internationalized printf.
1373 * This is essentially the same as PHP's built-in printf
1374 * with the following exceptions:
1376 * <li> It passes the format string through gettext().
1377 * <li> It supports the argument reordering extensions.
1384 * __printf("Differences between versions %s and %s of %s",
1385 * $new_link, $old_link, $page_link);
1388 * Then in locale/po/de.po, one can reorder the printf arguments:
1391 * msgid "Differences between %s and %s of %s."
1392 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1395 * (Note that while PHP tries to expand $vars within double-quotes,
1396 * the values in msgstr undergo no such expansion, so the '$'s
1399 * One shouldn't use reordered arguments in the default format string.
1400 * Backslashes in the default string would be necessary to escape the
1401 * '$'s, and they'll cause all kinds of trouble....
1403 function __printf ($fmt) {
1404 $args = func_get_args();
1406 echo __vsprintf($fmt, $args);
1410 * Internationalized sprintf.
1412 * This is essentially the same as PHP's built-in printf with the
1413 * following exceptions:
1416 * <li> It passes the format string through gettext().
1417 * <li> It supports the argument reordering extensions.
1422 function __sprintf ($fmt) {
1423 $args = func_get_args();
1425 return __vsprintf($fmt, $args);
1429 * Internationalized vsprintf.
1431 * This is essentially the same as PHP's built-in printf with the
1432 * following exceptions:
1435 * <li> It passes the format string through gettext().
1436 * <li> It supports the argument reordering extensions.
1441 function __vsprintf ($fmt, $args) {
1442 $fmt = gettext($fmt);
1443 // PHP's sprintf doesn't support variable with specifiers,
1444 // like sprintf("%*s", 10, "x"); --- so we won't either.
1446 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1447 // Format string has '%2$s' style argument reordering.
1448 // PHP doesn't support this.
1449 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1450 // literal variable name substitution only to keep locale
1451 // strings uncluttered
1452 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1453 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1455 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1458 // Reorder arguments appropriately.
1459 foreach($m[1] as $argnum) {
1460 if ($argnum < 1 || $argnum > count($args))
1461 trigger_error(sprintf(_("%s: argument index out of range"),
1462 $argnum), E_USER_WARNING);
1463 $newargs[] = $args[$argnum - 1];
1468 // Not all PHP's have vsprintf, so...
1469 array_unshift($args, $fmt);
1470 return call_user_func_array('sprintf', $args);
1473 function file_mtime ($filename) {
1474 if ($stat = @stat($filename))
1480 function sort_file_mtime ($a, $b) {
1481 $ma = file_mtime($a);
1482 $mb = file_mtime($b);
1483 if (!$ma or !$mb or $ma == $mb) return 0;
1484 return ($ma > $mb) ? -1 : 1;
1489 * Build an array in $this->_fileList of files from $dirname.
1490 * Subdirectories are not traversed.
1492 * (This was a function LoadDir in lib/loadsave.php)
1493 * See also http://www.php.net/manual/en/function.readdir.php
1495 function getFiles($exclude='', $sortby='', $limit='') {
1496 $list = $this->_fileList;
1499 require_once('lib/PageList.php');
1500 switch (Pagelist::sortby($sortby, 'db')) {
1501 case 'pagename ASC': break;
1502 case 'pagename DESC':
1503 $list = array_reverse($list);
1506 usort($list,'sort_file_mtime');
1509 usort($list,'sort_file_mtime');
1510 $list = array_reverse($list);
1515 return array_splice($list, 0, $limit);
1519 function _filenameSelector($filename) {
1520 if (! $this->_pattern )
1523 if (! $this->_pcre_pattern )
1524 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1525 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1530 function fileSet($directory, $filepattern = false) {
1531 $this->_fileList = array();
1532 $this->_pattern = $filepattern;
1534 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1536 $this->_case = !isWindows();
1537 $this->_pathsep = '/';
1539 if (empty($directory)) {
1540 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1542 return; // early return
1545 @ $dir_handle = opendir($dir=$directory);
1546 if (empty($dir_handle)) {
1547 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1548 $dir), E_USER_NOTICE);
1549 return; // early return
1552 while ($filename = readdir($dir_handle)) {
1553 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1555 if ($this->_filenameSelector($filename)) {
1556 array_push($this->_fileList, "$filename");
1557 //trigger_error(sprintf(_("found file %s"), $filename),
1558 // E_USER_NOTICE); //debugging
1561 closedir($dir_handle);
1567 // expands a list containing regex's to its matching entries
1568 class ListRegexExpand {
1569 //var $match, $list, $index, $case_sensitive;
1570 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1571 $this->match = $match;
1572 $this->list = &$list;
1573 $this->case_sensitive = $case_sensitive;
1574 //$this->index = false;
1576 function listMatchCallback ($item, $key) {
1577 $quoted = str_replace('/','\/',$item);
1578 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1580 unset($this->list[$this->index]);
1581 $this->list[] = $item;
1584 function expandRegex ($index, &$pages) {
1585 $this->index = $index;
1586 array_walk($pages, array($this, 'listMatchCallback'));
1591 // Convert fileglob to regex style:
1592 // Convert some wildcards to pcre style, escape the rest
1593 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1594 // Fixed bug #994994: "/" in $glob.
1595 function glob_to_pcre ($glob) {
1596 // check simple case: no need to escape
1597 $escape = '\[](){}=!<>|:/';
1598 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1600 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1601 $glob = strtr($glob, "\\", "\xff");
1602 $glob = str_replace("/", "\\/", $glob);
1603 // first convert some unescaped expressions to pcre style: . => \.
1605 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1606 "\\1\xff\\2", $glob);
1609 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1610 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1611 if (!preg_match('/^[\?\*]/', $glob))
1613 if (!preg_match('/[\?\*]$/', $glob))
1616 // Fixes Bug 1182997
1617 // .*? handled above, now escape the rest
1618 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1619 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1621 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1623 $re = preg_replace('/\xff/', '', $re);
1627 function glob_match ($glob, $against, $case_sensitive = true) {
1628 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1632 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1633 $list = explode(',',$input);
1634 // expand wildcards from list of $allnames
1635 if (preg_match('/[\?\*]/',$input)) {
1636 // Optimizing loop invariants:
1637 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1638 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1640 if (preg_match('/[\?\*]/',$f)) {
1642 $expand = new ListRegexExpand($list,
1643 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1644 $expand->expandRegex($i, $allnames);
1651 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1652 function explodePageList($input, $include_empty=false, $sortby='pagename',
1653 $limit='', $exclude='') {
1654 include_once("lib/PageList.php");
1655 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1658 // Class introspections
1661 * Determine whether object is of a specified type.
1662 * In PHP builtin since 4.2.0 as is_a()
1663 * is_a() deprecated in PHP 5, in favor of instanceof operator
1665 * @param $object object An object.
1666 * @param $class string Class name.
1667 * @return bool True iff $object is a $class
1668 * or a sub-type of $class.
1670 function isa ($object, $class) {
1671 //if (check_php_version(5))
1672 // return $object instanceof $class;
1673 if (check_php_version(4,2) and !check_php_version(5))
1674 return is_a($object, $class);
1676 $lclass = check_php_version(5) ? $class : strtolower($class);
1677 return is_object($object)
1678 && ( strtolower(get_class($object)) == strtolower($class)
1679 || is_subclass_of($object, $lclass) );
1682 /** Determine whether (possible) object has method.
1684 * @param $object mixed Object
1685 * @param $method string Method name
1686 * @return bool True iff $object is an object with has method $method.
1688 function can ($object, $method) {
1689 return is_object($object) && method_exists($object, strtolower($method));
1692 /** Determine whether a function is okay to use.
1694 * Some providers (e.g. Lycos) disable some of PHP functions for
1695 * "security reasons." This makes those functions, of course,
1696 * unusable, despite the fact the function_exists() says they
1699 * This function test to see if a function exists and is not
1700 * disallowed by PHP's disable_functions config setting.
1702 * @param string $function_name Function name
1703 * @return bool True iff function can be used.
1705 function function_usable($function_name) {
1707 if (!is_array($disabled)) {
1708 $disabled = array();
1709 // Use get_cfg_var since ini_get() is one of the disabled functions
1710 // (on Lycos, at least.)
1711 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1712 foreach ($split as $f)
1713 $disabled[strtolower($f)] = true;
1716 return ( function_exists($function_name)
1717 and ! isset($disabled[strtolower($function_name)])
1724 * This is used for generating ETags.
1726 function wikihash ($x) {
1727 if (is_scalar($x)) {
1730 elseif (is_array($x)) {
1732 return md5(serialize($x));
1734 elseif (is_object($x)) {
1737 trigger_error("Can't hash $x", E_USER_ERROR);
1742 * Seed the random number generator.
1744 * better_srand() ensures the randomizer is seeded only once.
1746 * How random do you want it? See:
1747 * http://www.php.net/manual/en/function.srand.php
1748 * http://www.php.net/manual/en/function.mt-srand.php
1750 function better_srand($seed = '') {
1751 static $wascalled = FALSE;
1753 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1754 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1756 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1760 function rand_ascii($length = 1) {
1763 for ($i = 1; $i <= $length; $i++) {
1764 // return only typeable 7 bit ascii, avoid quotes
1765 if (function_exists('mt_rand'))
1766 $s .= chr(mt_rand(40, 126));
1768 // the usually bad glibc srand()
1769 $s .= chr(rand(40, 126));
1774 /* by Dan Frankowski.
1776 function rand_ascii_readable ($length = 6) {
1777 // Pick a few random letters or numbers
1780 // Don't use 1lI0O, because they're hard to read
1781 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1782 $letter_len = strlen($letters);
1783 for ($i=0; $i < $length; $i++) {
1784 if (function_exists('mt_rand'))
1785 $word .= $letters[mt_rand(0, $letter_len-1)];
1787 $word .= $letters[rand(0, $letter_len-1)];
1793 * Recursively count all non-empty elements
1794 * in array of any dimension or mixed - i.e.
1795 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1796 * See http://www.php.net/manual/en/function.count.php
1798 function count_all($arg) {
1799 // skip if argument is empty
1801 //print_r($arg); //debugging
1803 // not an array, return 1 (base case)
1806 // else call recursively for all elements $arg
1807 foreach($arg as $key => $val)
1808 $count += count_all($val);
1813 function isSubPage($pagename) {
1814 return (strstr($pagename, SUBPAGE_SEPARATOR));
1817 function subPageSlice($pagename, $pos) {
1818 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1819 $pages = array_slice($pages,$pos,1);
1826 * Class for "popping up" and alert box. (Except that right now, it doesn't
1830 * This is a hackish and needs to be refactored. However it would be nice to
1831 * unify all the different methods we use for showing Alerts and Dialogs.
1832 * (E.g. "Page deleted", login form, ...)
1837 * @param object $request
1838 * @param mixed $head Header ("title") for alert box.
1839 * @param mixed $body The text in the alert box.
1840 * @param hash $buttons An array mapping button labels to URLs.
1841 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1843 function Alert($head, $body, $buttons=false) {
1844 if ($buttons === false)
1847 if (is_array($body)) {
1849 foreach ($body as $li) {
1850 $html->pushContent(HTML::li($li));
1854 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1855 $this->_buttons = $buttons;
1859 * Show the alert box.
1864 $tokens = $this->_tokens;
1865 $tokens['BUTTONS'] = $this->_getButtons();
1867 $request->discardOutput();
1868 $tmpl = new Template('dialog', $request, $tokens);
1874 function _getButtons() {
1877 $buttons = $this->_buttons;
1879 $buttons = array(_("Okay") => $request->getURLtoSelf());
1882 foreach ($buttons as $label => $url)
1883 print "$label $url\n";
1884 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1885 return new XmlContent($out);
1890 // 1.3.9-p1 => 1030.091
1891 // 1.3.10pre => 1030.099
1892 // 1.3.11pre-20041120 => 1030.1120041120
1893 // 1.3.12-rc1 => 1030.119
1894 function phpwiki_version() {
1895 static $PHPWIKI_VERSION;
1896 if (!isset($PHPWIKI_VERSION)) {
1897 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1898 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1899 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1900 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1901 $PHPWIKI_VERSION -= 0.01;
1903 return $PHPWIKI_VERSION;
1906 function phpwiki_gzhandler($ob) {
1907 if (function_exists('gzencode'))
1908 $ob = gzencode($ob);
1909 $GLOBALS['request']->_ob_get_length = strlen($ob);
1910 if (!headers_sent()) {
1911 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1916 function isWikiWord($word) {
1917 global $WikiNameRegexp;
1918 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1919 return preg_match("/^$WikiNameRegexp\$/",$word);
1922 // needed to store serialized objects-values only (perm, pref)
1923 function obj2hash ($obj, $exclude = false, $fields = false) {
1925 if (! $fields ) $fields = get_object_vars($obj);
1926 foreach ($fields as $key => $val) {
1927 if (is_array($exclude)) {
1928 if (in_array($key, $exclude)) continue;
1936 * isUtf8String($string) - cheap utf-8 detection
1938 * segfaults for strings longer than 10kb!
1939 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1940 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1942 function isUtf8String( $s ) {
1943 $ptrASCII = '[\x00-\x7F]';
1944 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1945 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1946 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1947 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1948 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1949 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1953 * Check for UTF-8 URLs; Internet Explorer produces these if you
1954 * type non-ASCII chars in the URL bar or follow unescaped links.
1955 * Requires urldecoded pagename.
1956 * Fixes sf.net bug #953949
1958 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1960 function fixTitleEncoding( $s ) {
1965 if (empty($s)) return $s;
1967 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1969 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1970 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1972 $isutf = ($ishigh ? isUtf8String($s) : true);
1973 $locharset = strtolower($charset);
1975 if( $locharset != "utf-8" and $ishigh and $isutf )
1976 $s = charset_convert('UTF-8', $locharset, $s);
1977 if ($locharset == "utf-8" and $ishigh and !$isutf )
1978 return utf8_encode( $s );
1980 // Other languages can safely leave this function, or replace
1981 // it with one to detect and convert another legacy encoding.
1986 * MySQL fulltext index doesn't grok utf-8, so we
1987 * need to fold cases and convert to hex.
1988 * src: languages/Language.php:stripForSearch() from mediawiki
1991 function stripForSearch( $string ) {
1992 global $wikiLowerChars;
1993 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1994 return preg_replace(
1995 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1996 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2002 * Workaround for allow_url_fopen, to get the content of an external URI.
2003 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2004 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2006 function url_get_contents( $uri ) {
2007 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2008 return @file_get_contents($uri);
2010 require_once("lib/HttpClient.php");
2011 $bits = parse_url($uri);
2012 $host = $bits['host'];
2013 $port = isset($bits['port']) ? $bits['port'] : 80;
2014 $path = isset($bits['path']) ? $bits['path'] : '/';
2015 if (isset($bits['query'])) {
2016 $path .= '?'.$bits['query'];
2018 $client = new HttpClient($host, $port);
2019 $client->use_gzip = false;
2020 if (!$client->get($path)) {
2023 return $client->getContent();
2029 * Generate consecutively named strings:
2030 * Name, Name2, Name3, ...
2032 function GenerateId($name) {
2033 static $ids = array();
2034 if (empty($ids[$name])) {
2039 return $name . $ids[$name];
2043 // from IncludePage. To be of general use.
2044 // content: string or array of strings
2045 function firstNWordsOfContent( $n, $content ) {
2046 if ($content and $n > 0) {
2047 if (is_array($content)) {
2048 // fixme: return a list of lines then?
2049 //$content = join("\n", $content);
2050 //$return_array = true;
2052 foreach ($content as $line) {
2053 $words = explode(' ', $line);
2054 if ($wordcount + count($words) > $n) {
2055 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2056 . sprintf(_("... (first %s words)"), $n);
2059 $wordcount += count($words);
2065 // fixme: use better whitespace/word seperators
2066 $words = explode(' ', $content);
2067 if (count($words) > $n) {
2068 return join(' ', array_slice($words, 0, $n))
2069 . sprintf(_("... (first %s words)"), $n);
2079 // moved from lib/plugin/IncludePage.php
2080 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2081 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2083 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2084 . " \\s*$\\n?" // possible blank lines
2085 . " ( (?: ^.*\\n? )*? )" // some lines
2086 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2087 implode("\n", $content),
2089 // Strip trailing blanks lines and ---- <hr>s
2090 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2092 $text = $match[1] . $section ."\n". $text;
2093 return explode("\n", $text);
2096 $mesg = $page ." ". $section;
2099 return array(sprintf(_("<%s: no such section>"), $mesg));
2102 // Extract the first $sections sections of the page
2103 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2105 $mycontent = $content;
2108 while ($sections > 0) {
2110 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2111 . " \\s*$\\n?" // possible blank lines
2112 . " ( (?: ^.*\\n? )*? )" // some lines
2113 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2114 implode("\n", $mycontent),
2116 $section = $match[2];
2117 // Strip trailing blanks lines and ---- <hr>s
2118 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2120 $text = $match[1] . $section ."\n". $text;
2123 $mycontent = explode("\n", $match[4]);
2125 if ($sections === 0) {
2126 return explode("\n", $result);
2132 // use this faster version: only load ExternalReferrer if we came from an external referrer
2133 function isExternalReferrer(&$request) {
2134 if ($referrer = $request->get('HTTP_REFERER')) {
2135 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2136 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2137 require_once("lib/ExternalReferrer.php");
2138 $se = new SearchEngines();
2139 return $se->parseSearchQuery($referrer);
2141 //if (DEBUG) return array('query' => 'wiki');
2146 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2148 function loadPhpExtension($extension) {
2149 if (!extension_loaded($extension)) {
2150 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2151 $soname = ($isWindows ? 'php_' : '')
2153 . ($isWindows ? '.dll' : '.so');
2157 return extension_loaded($extension);
2160 function charset_convert($from, $to, $data) {
2162 //$wikicharset = strtolower($CHARSET);
2163 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2164 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2165 return utf8_decode($data);
2166 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2167 return utf8_encode($data);
2169 if (loadPhpExtension("iconv")) {
2170 $tmpdata = iconv($from, $to, $data);
2172 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2176 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2181 function string_starts_with($string, $prefix) {
2182 return (substr($string, 0, strlen($prefix)) == $prefix);
2184 function string_ends_with($string, $suffix) {
2185 return (substr($string, -strlen($suffix)) == $suffix);
2187 function array_remove($arr,$value) {
2188 return array_values(array_diff($arr,array($value)));
2192 * Ensure that the script will have another $secs time left.
2193 * Works only if safe_mode is off.
2194 * For example not to timeout on waiting socket connections.
2195 * Use the socket timeout as arg.
2197 function longer_timeout($secs = 30) {
2198 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2199 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2200 if ($timeleft < $secs)
2201 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2204 function printSimpleTrace($bt) {
2206 echo "\nTraceback:\n";
2207 if (function_exists('debug_print_backtrace')) { // >= 5
2208 debug_print_backtrace();
2210 foreach ($bt as $i => $elem) {
2211 if (!array_key_exists('file', $elem)) {
2214 //echo join(" ",array_values($elem)),"\n";
2215 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2221 * Return the used process memory, in bytes.
2222 * Enable the section which will work for you. They are very slow.
2223 * Special quirks for Windows: Requires cygwin.
2225 function getMemoryUsage() {
2226 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2227 if (function_exists('memory_get_usage') and memory_get_usage()) {
2228 return memory_get_usage();
2229 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2230 $mem = $u['ru_maxrss'];
2231 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2232 // what we want is the process memory only: apache or php (if CGI)
2235 // win32_ps_stat_proc, win32_ps_stat_mem
2236 if (function_exists('win32_ps_list_procs')) {
2237 $info = win32_ps_stat_proc($pid);
2238 $memstr = $info['mem']['working_set_size'];
2240 // This works only if it's a cygwin process (apache or php).
2241 // Requires a newer cygwin
2242 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2244 // if it's native windows use something like this:
2245 // (requires pslist from sysinternals.com, grep, sed and perl)
2246 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2248 return (integer) trim($memstr);
2251 //%MEM: Percentage of total memory in use by this process
2252 //VSZ: Total virtual memory size, in 1K blocks.
2253 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2254 //CPU time used by process since it started.
2255 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2256 $memstr = exec("ps -orss -p $pid|sed 1d");
2257 return (integer) trim($memstr);
2262 * @param var $needle
2263 * @param array $haystack one-dimensional numeric array only, no hash
2265 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2266 It will return false if not found or the index where it was found.
2267 From dennis.decoene@moveit.be http://www.php.net/array_search
2269 function binary_search($needle, $haystack) {
2270 $high = count($haystack);
2273 while (($high - $low) > 1) {
2274 $probe = floor(($high + $low) / 2);
2275 if ($haystack[$probe] < $needle) {
2277 } elseif ($haystack[$probe] == $needle) {
2278 $high = $low = $probe;
2284 if ($high == count($haystack) || $haystack[$high] != $needle) {
2291 function is_localhost($url = false) {
2293 global $HTTP_SERVER_VARS;
2294 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2299 * Take a string and quote it sufficiently to be passed as a Javascript
2300 * string between ''s
2302 function javascript_quote_string($s) {
2303 return str_replace("'", "\'", $s);
2306 function isSerialized($s) {
2307 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2311 * Take a string and return an array of pairs (attribute name, attribute value)
2313 * We allow attributes with or without double quotes (")
2314 * Attribute-value pairs may be separated by space or comma
2315 * border=1, cellpadding="5"
2316 * border=1 cellpadding="5"
2317 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2318 * What will not work is style with comma inside, e. g.
2319 / style="font-family: Verdana, Arial, Helvetica, sans-serif"
2321 function parse_attributes($line) {
2322 $line = strtolower($line);
2323 $line = str_replace(",", "", $line);
2324 $attr_chunks = preg_split("/\s* \s*/", $line);
2326 foreach ($attr_chunks as $attr_pair) {
2327 if (empty($attr_pair)) continue;
2328 $key_val = preg_split("/\s*=\s*/", $attr_pair);
2329 if (!empty($key_val[1]))
2330 $options[trim($key_val[0])] = trim(str_replace("\"", "", $key_val[1]));
2336 * Returns true if the filename ends with an image suffix.
2337 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2339 function is_image ($filename) {
2341 if (defined('INLINE_IMAGES')) {
2342 $inline_images = INLINE_IMAGES;
2344 $inline_images = "png|jpg|jpeg|gif";
2347 foreach (explode("|", $inline_images) as $suffix) {
2348 if (string_ends_with($filename, "." . $suffix)) {
2356 * Compute cell in spreadsheet table
2357 * $table: two-dimensional table
2358 * $i and $j: indexes of cell to compute
2359 * $imax and $jmax: table dimensions
2361 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2363 // What is implemented:
2364 // @@SUM(R)@@ : sum of cells in current row
2365 // @@SUM(C)@@ : sum of cells in current column
2368 if (trim($table[$i][$j]) == "@@SUM(C)@@") {
2369 for ($index=0; $index<$imax; $index++) {
2370 $result += $table[$index][$j];
2373 if (trim($table[$i][$j]) == "@@SUM(R)@@") {
2374 for ($index=0; $index<$jmax; $index++) {
2375 $result += $table[$i][$index];
2381 // (c-file-style: "gnu")
2385 // c-basic-offset: 4
2386 // c-hanging-comment-ender-p: nil
2387 // indent-tabs-mode: nil