3 * Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4 * Copyright 2008-2009 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 along
19 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 MangleXmlIdentifier($str)
38 class Stack { push($item), pop(), cnt(), top() }
39 class Alert { show() }
40 class WikiPageName {getParent(),isValid(),getWarnings() }
42 expand_tabs($str, $tab_width = 8)
44 NoSuchRevision ($request, $page, $version)
45 TimezoneOffset ($time, $no_colon)
46 Iso8601DateTime ($time)
47 Rfc2822DateTime ($time)
48 ParseRfc1123DateTime ($timestr)
50 ByteFormatter ($bytes = 0, $longformat = false)
53 __vsprintf ($fmt, $args)
55 file_mtime ($filename)
56 sort_file_mtime ($a, $b)
57 class fileSet {fileSet($directory, $filepattern = false),
58 getFiles($exclude='', $sortby='', $limit='') }
59 class ListRegexExpand { listMatchCallback($item, $key),
60 expandRegex ($index, &$pages) }
63 glob_match ($glob, $against, $case_sensitive = true)
64 explodePageList ($input, $perm = false)
65 function_usable ($function_name)
69 subPageSlice ($pagename, $pos)
70 isActionPage ($filename)
74 obj2hash ($obj, $exclude = false, $fields = false)
75 url_get_contents ($uri)
77 firstNWordsOfContent ($n, $content)
78 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
81 string_starts_with($string, $prefix)
82 string_ends_with($string, $suffix)
83 array_remove($arr,$value)
84 longer_timeout($secs=30)
86 binary_search($needle, $haystack)
88 javascript_quote_string($s)
91 parse_attributes($line)
95 function: linkExistingWikiWord($wikiword, $linktext, $version)
96 moved to: lib/WikiTheme.php
98 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
99 else define('_PHPWIKI_STDLIB_LOADED', true);
101 if (!defined('MAX_PAGENAME_LENGTH')) {
102 define('MAX_PAGENAME_LENGTH', 100);
106 * Convert string to a valid XML identifier.
108 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
110 * We would like to have, e.g. named anchors within wiki pages
111 * names like "Table of Contents" --- clearly not a valid XML
112 * fragment identifier.
114 * This function implements a one-to-one map from {any string}
115 * to {valid XML identifiers}.
118 * converting all bytes not in [A-Za-z0-9:_-],
119 * and any leading byte not in [A-Za-z] to '.bb',
120 * where 'bb' is the hexadecimal representation of the
123 * As a special case, the empty string is converted to 'empty.'
128 function MangleXmlIdentifier($str)
133 return preg_replace_callback(
134 '/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/',
136 return '.' . sprintf('%02x', ord('$m'));
142 * Returns a name for the WIKI_ID cookie that should be unique on the host.
143 * But for it to be unique you must have set a unique WIKI_NAME in your
144 * configuration file.
145 * @return string The name of the WIKI_ID cookie to use for this wiki.
147 function getCookieName()
149 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
153 * Generates a valid URL for a given Wiki pagename.
154 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
155 * If a WikiDB_Page object function will extract the name to link to.
156 * If a WikiDB_PageRevision object function will extract the name to link to.
158 * @param bool $get_abs_url Default value is false.
159 * @return string The absolute URL to the page passed as $pagename.
161 function WikiURL($pagename, $args = array(), $get_abs_url = false)
163 global $request, $WikiTheme;
166 if (is_object($pagename)) {
167 if (is_a($pagename, 'WikiDB_Page')) {
168 $pagename = $pagename->getName();
169 } elseif (is_a($pagename, 'WikiDB_PageRevision')) {
170 $page = $pagename->getPage();
171 $args['version'] = $pagename->getVersion();
172 $pagename = $page->getName();
173 } elseif (is_a($pagename, 'WikiPageName')) {
174 $anchor = $pagename->anchor;
175 $pagename = $pagename->name;
177 $anchor = $pagename->anchor;
178 $pagename = $pagename->name;
181 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
183 $args = 'start_debug=' . $request->getArg('start_debug');
184 elseif (is_array($args))
185 $args['start_debug'] = $request->getArg('start_debug'); else
186 $args .= '&start_debug=' . $request->getArg('start_debug');
188 if (is_array($args)) {
190 foreach ($args as $key => $val) {
191 // avoid default args
192 if (USE_PATH_INFO and $key == 'pagename')
194 elseif ($key == 'action' and $val == 'browse')
195 ; elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
196 $enc_args[] = urlencode($key) . '=' . urlencode($val);
198 $args = join('&', $enc_args);
201 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
202 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
203 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
205 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
206 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
207 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
210 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
212 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
221 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
222 $url .= "?pagename=" . rawurlencode($pagename);
227 $url .= "#" . MangleXmlIdentifier($anchor);
231 /** Convert relative URL to absolute URL.
233 * This converts a relative URL to one of PhpWiki's support files
234 * to an absolute one.
237 * @return string Absolute URL
239 function AbsoluteURL($url)
241 if (preg_match('/^https?:/', $url))
243 if ($url[0] != '/') {
244 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
245 while ($base != '/' and substr($url, 0, 3) == "../") {
246 $url = substr($url, 3);
247 $base = dirname($base);
253 return SERVER_URL . $url;
256 function DataURL($url)
258 if (preg_match('/^https?:/', $url))
260 $url = NormalizeWebFileName($url);
261 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url, -4, 4) == '.php')
262 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
263 return AbsoluteURL($url);
267 * Generates icon in front of links.
269 * @param string $protocol_or_url URL or protocol to determine which icon to use.
271 * @return HtmlElement HtmlElement object that contains data to create img link to
272 * icon for use with url or protocol passed to the function. False if no img to be
275 function IconForLink($protocol_or_url)
279 if (0 and $filename_suffix == false) {
280 // display apache style icon for file type instead of protocol icon
281 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
282 // - document: html, htm, text, txt, rtf, pdf, doc
283 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
284 // - audio: mp3,mp2,aiff,aif,au
285 // - multimedia: mpeg,mpg,mov,qt
288 list ($proto) = explode(':', $protocol_or_url, 2);
289 $src = $WikiTheme->getLinkIconURL($proto);
291 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon'));
298 * Glue icon in front of or after text.
299 * Pref: 'noLinkIcons' - ignore icon if set
300 * WikiTheme: 'LinkIcons' - 'yes' at front
301 * - 'no' display no icon
302 * - 'front' display at left
303 * - 'after' display at right
305 * @param string $proto_or_url Protocol or URL. Used to determine the
307 * @param string $text The text.
308 * @return XmlContent.
310 function PossiblyGlueIconToText($proto_or_url, $text)
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;
334 $text = HTML::span(array('style' => 'white-space: nowrap'),
335 $last_word, HTML::Raw(' '), $icon);
337 $text = HTML($prefix, $text);
340 // span the icon only to the first word (tie them together),
341 // to let the next words wrap on line breaks
342 if (!is_object($text)) {
343 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
344 list (, $first_word, $tail) = $m;
349 $text = HTML::span(array('style' => 'white-space: nowrap'),
352 $text = HTML($text, $tail);
357 * Determines if the url passed to function is safe, by detecting if the characters
358 * '<', '>', or '"' are present.
359 * Check against their urlencoded values also.
361 * @param string $url URL to check for unsafe characters.
362 * @return boolean True if same, false else.
364 function IsSafeURL($url)
366 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
370 * Generates an HtmlElement object to store data for a link.
372 * @param string $url URL that the link will point to.
373 * @param string $linktext Text to be displayed as link.
374 * @return HtmlElement HtmlElement object that contains data to construct an html link.
376 function LinkURL($url, $linktext = '')
378 // FIXME: Is this needed (or sufficient?)
379 if (!IsSafeURL($url)) {
380 $link = HTML::span(array('class' => 'error'), _('Bad URL -- remove all of <, >, "'));
384 $linktext = preg_replace("/mailto:/A", "", $url);
385 $args = array('href' => $url);
386 if (defined('EXTERNAL_LINK_TARGET')) // can also be set in the css
387 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
388 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
390 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
397 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
398 * Disallows sizes which are too small.
399 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
401 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
403 function LinkImage($url, $alt = "")
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 // support new syntax: [prefix/image.jpg size=50% border=n]
415 $arr = explode(' ', $url);
416 if (!empty($arr)) $url = $arr[0];
417 if (!IsSafeURL($url)) {
418 $link = HTML::span(array('class' => 'error'), _('Bad URL for image -- remove all of <, >, "'));
421 // spaces in inline images must be %20 encoded!
422 $link = HTML::img(array('src' => $url));
424 // Extract attributes
425 $arr = parse_attributes(strstr($ori_url, " "));
426 foreach ($arr as $attr => $value) {
427 // These attributes take strings: lang, id, title, alt
428 if (($attr == "lang")
430 || ($attr == "title")
433 $link->setAttr($attr, $value);
434 } // align = bottom|middle|top|left|right
435 // we allow "center" as synonym for "middle"
436 elseif (($attr == "align")
437 && (($value == "bottom")
438 || ($value == "middle")
439 || ($value == "center")
441 || ($value == "left")
442 || ($value == "right"))
444 if ($value == "center") {
447 $link->setAttr($attr, $value);
448 } // These attributes take a number (pixels): border, hspace, vspace
449 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
450 && (is_numeric($value))
452 $link->setAttr($attr, (int)$value);
453 } // These attributes take a number (pixels) or a percentage: height, width
454 elseif ((($attr == "height") || ($attr == "width"))
455 && (preg_match('/\d+[%p]?x?/', $value))
457 $link->setAttr($attr, $value);
458 } // We allow size=50% and size=20x30
459 // We replace this with "width" and "height" HTML attributes
460 elseif ($attr == "size") {
461 if (preg_match('/(\d+%)/', $value, $m)) {
462 $link->setAttr('width', $m[1]);
463 $link->setAttr('height', $m[1]);
464 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
465 $link->setAttr('width', $m[1]);
466 $link->setAttr('height', $m[2]);
469 $url = substr(strrchr($ori_url, "/"), 1);
470 $link = HTML::span(array('class' => 'error'),
471 sprintf(_("Invalid attribute %s=%s for image %s"),
472 $attr, $value, $url));
476 // Correct silently the most common error
477 if ($url != $ori_url and empty($arr) and !preg_match("/^http/", $url)) {
478 // space belongs to the path
479 $file = NormalizeLocalFileName($ori_url);
480 if (file_exists($file)) {
481 $link = HTML::img(array('src' => $ori_url));
483 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
484 $url, $ori_url), E_USER_WARNING);
485 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
486 $file = substr($file, strlen(getUploadDataPath()));
487 $path = getUploadFilePath() . $file;
488 if (file_exists($path)) {
489 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
490 $url, $ori_url), E_USER_WARNING);
491 $link->setAttr('src', getUploadDataPath() . $file);
496 if (!$link->getAttr('alt')) {
497 $link->setAttr('alt', $alt);
499 // Check width and height as spam countermeasure
500 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
501 //$width = (int) $width; // px or % or other suffix
502 //$height = (int) $height;
503 if (($width < 3 and $height < 10) or
504 ($height < 3 and $width < 20) or
505 ($height < 7 and $width < 7)
507 $link = HTML::span(array('class' => 'error'),
508 _("Invalid image size"));
513 // Prepare for getimagesize($url)
514 // $url only valid for external urls, otherwise local path
515 if (DISABLE_GETIMAGESIZE)
517 elseif (!preg_match("/\.$force_img$/i", $url))
518 ; // only valid image extensions or scripts assumed to generate images
519 elseif (preg_match("/^http/", $url)) { // external url
520 $size = @getimagesize($url);
521 } else { // local file
522 if (file_exists($file = NormalizeLocalFileName($url))) { // here
523 $size = @getimagesize($file);
524 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
525 $size = @getimagesize($file);
526 $link->setAttr('src', rawurldecode($url));
527 } elseif (string_starts_with($url, getUploadDataPath())) { // there
528 $file = substr($file, strlen(getUploadDataPath()));
529 $path = getUploadFilePath() . rawurldecode($file);
530 $size = @getimagesize($path);
531 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
532 } else { // elsewhere
534 $size = @getimagesize($request->get('DOCUMENT_ROOT') . urldecode($url));
540 if (($width < 3 and $height < 10)
541 or ($height < 3 and $width < 20)
542 or ($height < 7 and $width < 7)
544 $link = HTML::span(array('class' => 'error'),
545 _("Invalid image size"));
550 $link->setAttr('class', 'inlineimage');
552 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
553 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
554 * Note: Allow cgi's (pl,cgi) returning images.
556 if (!preg_match("/\.(" . $force_img . ")/i", $ori_url)) {
557 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
558 // => HTML::object(array('src' => $url)) ...;
559 return ImgObject($link, $ori_url);
565 * <object> / <embed> tags instead of <img> for all non-image extensions
567 * Called by LinkImage(), not directly.
568 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
569 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
570 * $alt may be an alternate img
571 * TODO: Need to unify with WikiPluginCached::embedObject()
573 * Note that Safari 1.0 will crash with <object>, so use only <embed>
574 * http://www.alleged.org.uk/pdc/2002/svg-object.html
576 * Allowed object tags:
578 * DATA=URI (object data)
579 * CLASSID=URI (location of implementation)
580 * ARCHIVE=CDATA (archive files)
581 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
582 * WIDTH=Length (object width)
583 * HEIGHT=Length (object height)
584 * NAME=CDATA (name for form submission)
585 * USEMAP=URI (client-side image map)
586 * TYPE=ContentType (content-type of object)
587 * CODETYPE=ContentType (content-type of code)
588 * STANDBY=Text (message to show while loading)
589 * TABINDEX=NUMBER (position in tabbing order)
590 * DECLARE (do not instantiate object)
591 * The rest is added as <param name="" value="" /> tags
593 function ImgObject($img, $url)
595 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
596 $params = explode(",", "id,width,height,data,classid,archive,codebase,name,usemap,type," .
597 "codetype,standby,tabindex,declare");
598 if (is_array($url)) {
601 foreach ($args as $attr => $value) {
602 foreach ($params as $param) {
603 if ($param == $attr) {
604 $img->setAttr($param, $value);
605 if (isset($found[$param])) $found[$param]++;
606 else $found[$param] = 1;
611 // now all remaining args are added as <param> to the object
613 foreach ($args as $attr => $value) {
614 if (!isset($found[$attr])) {
615 $params[] = HTML::param(array('name' => $attr,
619 $url = $img->getAttr('src');
620 $force_img = "png|jpg|gif|jpeg|bmp";
621 if (!preg_match("/\.(" . $force_img . ")/i", $url)) {
622 $img->setAttr('src', false);
625 $args = explode(' ', $url);
626 if (count($args) >= 1) {
627 $url = array_shift($args);
629 foreach ($args as $attr) {
630 foreach ($params as $param) {
631 if (preg_match("/^$param=(\S+)$/i", $attr, $m)) {
632 $img->setAttr($param, $m[1]);
633 if (isset($found[$param])) $found[$param]++;
634 else $found[$param] = 1;
639 // now all remaining args are added as <param> to the object
641 foreach ($args as $attr) {
642 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i", $attr, $m)) {
643 $params[] = HTML::param(array('name' => $m[1],
649 $type = $img->getAttr('type');
651 if (file_exists($url)) {
652 $type = mime_content_type($url);
655 $object = HTML::object(array_merge($img->_attr,
656 array('type' => $type)), //'src' => $url
658 $object->setAttr('class', 'inlineobject');
660 foreach ($params as $param) $object->pushContent($param);
662 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
663 return HTML::embed($object->_attr, $object->_content);
665 $object->pushContent(HTML::embed($object->_attr));
673 $this->items = array();
679 $this->items[$this->size] = $item;
686 if ($this->size == 0) {
687 return false; // stack is empty
690 return $this->items[$this->size];
701 return $this->items[$this->size - 1];
708 // end class definition
710 function SplitQueryArgs($query_args = '')
712 // FIXME: use the arg-seperator which might not be &
713 $split_args = explode('&', $query_args);
715 while (list($key, $val) = each($split_args))
716 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
717 $args[$m[1]] = $m[2];
721 function LinkPhpwikiURL($url, $text = '', $basepage = false)
725 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
726 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
730 $pagename = urldecode($m[1]);
733 if (empty($pagename) &&
734 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)
736 // Convert old style links (to not break diff links in
738 $pagename = urldecode($m[2]);
739 $args = array("action" => $m[1]);
741 $args = SplitQueryArgs($qargs);
744 if (empty($pagename))
745 $pagename = $GLOBALS['request']->getArg('pagename');
747 if (isset($args['action']) && $args['action'] == 'browse')
748 unset($args['action']);
751 if (empty($args['action']))
753 else if (is_safe_action($args['action']))
754 $class = 'wikiaction';
756 if (empty($args['action']) || is_safe_action($args['action']))
757 $class = 'wikiaction';
759 // Don't allow administrative links on unlocked pages.
760 $dbi = $GLOBALS['request']->getDbh();
761 $page = $dbi->getPage($basepage ? $basepage : $pagename);
762 if (!$page->get('locked'))
763 return HTML::span(array('class' => 'wikiunsafe'),
764 HTML::u(_("Lock page to enable link")));
765 $class = 'wikiadmin';
769 $text = HTML::span(array('class' => 'rawurl'), $url);
771 $wikipage = new WikiPageName($pagename);
772 if (!$wikipage->isValid()) {
774 return $WikiTheme->linkBadWikiWord($wikipage, $url);
777 return HTML::a(array('href' => WikiURL($pagename, $args),
783 * A class to assist in parsing wiki pagenames.
785 * Now with subpages and anchors, parsing and passing around
786 * pagenames is more complicated. This should help.
790 /** Short name for page.
792 * This is the value of $name passed to the constructor.
793 * (For use, e.g. as a default label for links to the page.)
797 /** The full page name.
799 * This is the full name of the page (without anchor).
805 * This is the referenced anchor within the page, or the empty string.
810 * @param mixed $name Page name.
811 * WikiDB_Page, WikiDB_PageRevision, or string.
812 * This can be a relative subpage name (like '/SubPage'),
813 * or can be the empty string to refer to the $basename.
815 * @param mixed $basename Page name from which to interpret
816 * relative or other non-fully-specified page names.
818 * @param mixed $anchor For links to anchors in page.
820 function __construct($name, $basename = false, $anchor = false)
822 if (is_string($name)) {
823 $this->shortName = $name;
824 if (strstr($name, ':')) {
825 list($moniker, $shortName) = explode(":", $name, 2);
826 $map = getInterwikiMap(); // allow overrides to custom maps
827 if (isset($map->_map[$moniker])) {
828 $url = $map->_map[$moniker];
829 if (strstr($url, '%s'))
830 $url = sprintf($url, $shortName);
834 // expand Talk or User, but not to absolute urls!
835 if (strstr($url, '//')) {
836 if ($moniker == 'Talk')
837 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
838 elseif ($moniker == 'User')
843 $this->shortName = $shortName;
846 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
847 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
849 $name = $this->_pagename($basename) . $name;
851 $name = $this->_normalize_bad_pagename($name);
852 $this->shortName = $name;
856 $name = $this->_pagename($name);
857 $this->shortName = $name;
860 $this->name = $this->_check($name);
861 $this->anchor = (string)$anchor;
872 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
874 return substr($name, 0, -strlen($tail));
877 function isValid($strict = false)
880 return !isset($this->_errors);
881 return (is_string($this->name) and $this->name != '');
884 function getWarnings()
887 if (isset($this->_warnings))
888 $warnings = array_merge($warnings, $this->_warnings);
889 if (isset($this->_errors))
890 $warnings = array_merge($warnings, $this->_errors);
894 return sprintf(_("“%s”: Bad page name: %s"),
895 $this->shortName, join(', ', $warnings));
898 function _pagename($page)
900 if (is_a($page, 'WikiDB_Page'))
901 return $page->getName();
902 elseif (is_a($page, 'WikiDB_PageRevision'))
903 return $page->getPageName();
904 elseif (is_a($page, 'WikiPageName'))
909 function _normalize_bad_pagename($name)
911 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
913 // Punt... You really shouldn't get here.
916 return $request->getArg('pagename');
918 assert($name[0] == SUBPAGE_SEPARATOR);
919 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
920 return substr($name, 1);
924 * Compress internal white-space to single space character.
926 * This leads to problems with loading a foreign charset pagename,
927 * which cannot be deleted anymore, because unknown chars are compressed.
928 * So BEFORE importing a file _check must be done !!!
930 function _check($pagename)
932 // Compress internal white-space to single space character.
933 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
934 if ($pagename != $orig)
935 $this->_warnings[] = _("White space converted to single space");
937 // Delete any control characters.
938 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
939 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
940 if ($pagename != $orig)
941 $this->_errors[] = _("Control characters not allowed");
944 // Strip leading and trailing white-space.
945 $pagename = trim($pagename);
948 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
949 $pagename = substr($pagename, 1);
950 if ($pagename != $orig)
951 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
953 // ";" is urlencoded, so safe from php arg-delim problems
954 /*if (strstr($pagename, ';')) {
955 $this->_warnings[] = _("';' is deprecated");
956 $pagename = str_replace(';', '', $pagename);
959 // not only for SQL, also to restrict url length
960 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
961 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
962 $this->_errors[] = _("Page name too long");
965 // disallow some chars only on file and cvs
966 if ((DATABASE_TYPE == 'cvs'
967 or DATABASE_TYPE == 'file'
968 or DATABASE_TYPE == 'flatfile')
969 and preg_match('/(:|\.\.)/', $pagename, $m)
971 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
972 $pagename = str_replace('..', '', $pagename);
973 $pagename = str_replace(':', '', $pagename);
981 * Expand tabs in string.
983 * Converts all tabs to (the appropriate number of) spaces.
986 * @param integer $tab_width
989 function expand_tabs($str, $tab_width = 8)
991 $split = explode("\t", $str);
992 $tail = array_pop($split);
994 foreach ($split as $hunk) {
996 $pos = strlen(strrchr($expanded, "\n")) - 1;
997 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
999 return substr($expanded, 1) . $tail;
1003 * Split WikiWords in page names.
1005 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1006 * places like page titles. This is rumored to help search engines
1009 * @param $page string The page name.
1011 * @return string The split name.
1013 function SplitPagename($page)
1016 if (preg_match("/\s/", $page))
1017 return $page; // Already split --- don't split any more.
1019 // This algorithm is specialized for several languages.
1020 // (Thanks to Pierrick MEIGNEN)
1021 // Improvements for other languages welcome.
1024 // This mess splits between a lower-case letter followed by
1025 // either an upper-case or a numeral; except that it wont
1026 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1027 switch ($GLOBALS['LANG']) {
1032 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1035 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1038 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1039 // This the single-letter words 'I' and 'A' from any following
1040 // capitalized words.
1041 switch ($GLOBALS['LANG']) {
1043 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1046 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1049 // Split at underscore
1050 $RE[] = '/(_)([[:alpha:]])/';
1051 $RE[] = '/([[:alpha:]])(_)/';
1052 // Split numerals from following letters.
1053 $RE[] = '/(\d)([[:alpha:]])/';
1054 // Split at subpage seperators. TBD in WikiTheme.php
1055 $RE[] = "/([^${sep}]+)(${sep})/";
1056 $RE[] = "/(${sep})([^${sep}]+)/";
1058 foreach ($RE as $key)
1062 foreach ($RE as $regexp) {
1063 $page = preg_replace($regexp, '\\1 \\2', $page);
1068 function NoSuchRevision(&$request, $page, $version)
1070 $html = HTML(HTML::h2(_("Revision Not Found")),
1071 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1072 $version, WikiLink($page, 'auto'))));
1073 include_once 'lib/Template.php';
1074 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1079 * Get time offset for local time zone.
1081 * @param int $time Get offset for this time. Default: now.
1082 * @param bool $no_colon Don't put colon between hours and minutes.
1083 * @return string Offset as a string in the format +HH:MM.
1085 function TimezoneOffset($time = 0, $no_colon = false)
1089 $secs = date('Z', $time);
1097 $colon = $no_colon ? '' : ':';
1098 $mins = intval(($secs + 30) / 60);
1099 return sprintf("%s%02d%s%02d",
1100 $sign, $mins / 60, $colon, $mins % 60);
1104 * Format time in ISO-8601 format.
1106 * @param int $time Time. Default: now.
1107 * @return string Date and time in ISO-8601 format.
1109 function Iso8601DateTime($time = 0)
1113 $tzoff = TimezoneOffset($time);
1114 $date = date('Y-m-d', $time);
1115 $time = date('H:i:s', $time);
1116 return $date . 'T' . $time . $tzoff;
1120 * Format time in RFC-2822 format.
1122 * @param int $time Time. Default: now.
1123 * @return string Date and time in RFC-2822 format.
1125 function Rfc2822DateTime($time = 0)
1129 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1133 * Format time in RFC-1123 format.
1135 * @param int $time Time. Default: now.
1136 * @return string Date and time in RFC-1123 format.
1138 function Rfc1123DateTime($time = 0)
1142 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1145 /** Parse date in RFC-1123 format.
1147 * According to RFC 1123 we must accept dates in the following
1150 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1151 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1152 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1154 * (Though we're only allowed to generate dates in the first format.)
1156 function ParseRfc1123DateTime($timestr)
1158 $timestr = trim($timestr);
1159 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1160 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1163 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1164 } elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1165 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1168 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1169 if ($year < 70) $year += 2000;
1170 elseif ($year < 100) $year += 1900;
1171 } elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1172 . '(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1175 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1181 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1183 return false; // failed
1188 * Format time to standard 'ctime' format.
1190 * @param int $time Time. Default: now.
1191 * @return string Date and time.
1193 function CTime($time = 0)
1197 return date("D M j H:i:s Y", $time);
1201 * Format number as kibibytes or bytes.
1202 * Short format is used for PageList
1203 * Long format is used in PageInfo
1205 * @param $bytes int. Default: 0.
1206 * @param $longformat bool. Default: false.
1207 * @return FormattedText (XmlElement.php).
1209 function ByteFormatter($bytes = 0, $longformat = false)
1213 if ($bytes < 1024) {
1215 $size = fmt("%s B", $bytes);
1217 $size = fmt("%s bytes", $bytes);
1219 $kb = round($bytes / 1024, 1);
1221 $size = fmt("%s KiB", $kb);
1223 $size = fmt("%s KiB (%s bytes)", $kb, $bytes);
1229 * Internationalized printf.
1231 * This is essentially the same as PHP's built-in printf
1232 * with the following exceptions:
1234 * <li> It passes the format string through gettext().
1235 * <li> It supports the argument reordering extensions.
1242 * __printf("Differences between versions %s and %s of %s",
1243 * $new_link, $old_link, $page_link);
1246 * Then in locale/po/de.po, one can reorder the printf arguments:
1249 * msgid "Differences between %s and %s of %s."
1250 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1253 * (Note that while PHP tries to expand $vars within double-quotes,
1254 * the values in msgstr undergo no such expansion, so the '$'s
1257 * One shouldn't use reordered arguments in the default format string.
1258 * Backslashes in the default string would be necessary to escape the
1259 * '$'s, and they'll cause all kinds of trouble....
1261 function __printf($fmt)
1263 $args = func_get_args();
1265 echo __vsprintf($fmt, $args);
1269 * Internationalized sprintf.
1271 * This is essentially the same as PHP's built-in printf with the
1272 * following exceptions:
1275 * <li> It passes the format string through gettext().
1276 * <li> It supports the argument reordering extensions.
1281 function __sprintf($fmt)
1283 $args = func_get_args();
1285 return __vsprintf($fmt, $args);
1289 * Internationalized vsprintf.
1291 * This is essentially the same as PHP's built-in printf with the
1292 * following exceptions:
1295 * <li> It passes the format string through gettext().
1296 * <li> It supports the argument reordering extensions.
1301 function __vsprintf($fmt, $args)
1303 $fmt = gettext($fmt);
1304 // PHP's sprintf doesn't support variable with specifiers,
1305 // like sprintf("%*s", 10, "x"); --- so we won't either.
1307 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1308 // Format string has '%2$s' style argument reordering.
1309 // PHP doesn't support this.
1310 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1311 // literal variable name substitution only to keep locale
1312 // strings uncluttered
1313 trigger_error(sprintf(_("Can't mix “%s” with “%s” type format strings"),
1314 '%1\$s', '%s'), E_USER_WARNING); //php+locale error
1316 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1319 // Reorder arguments appropriately.
1320 foreach ($m[1] as $argnum) {
1321 if ($argnum < 1 || $argnum > count($args))
1322 trigger_error(sprintf(_("%s: argument index out of range"),
1323 $argnum), E_USER_WARNING);
1324 $newargs[] = $args[$argnum - 1];
1329 // Not all PHP's have vsprintf, so...
1330 array_unshift($args, $fmt);
1331 return call_user_func_array('sprintf', $args);
1334 function file_mtime($filename)
1336 if ($stat = @stat($filename))
1342 function sort_file_mtime($a, $b)
1344 $ma = file_mtime($a);
1345 $mb = file_mtime($b);
1346 if (!$ma or !$mb or $ma == $mb) return 0;
1347 return ($ma > $mb) ? -1 : 1;
1353 * Build an array in $this->_fileList of files from $dirname.
1354 * Subdirectories are not traversed.
1356 * (This was a function LoadDir in lib/loadsave.php)
1357 * See also http://www.php.net/manual/en/function.readdir.php
1359 function getFiles($exclude = '', $sortby = '', $limit = '')
1361 $list = $this->_fileList;
1364 require_once 'lib/PageList.php';
1365 switch (Pagelist::sortby($sortby, 'db')) {
1366 case 'pagename ASC':
1368 case 'pagename DESC':
1369 $list = array_reverse($list);
1372 usort($list, 'sort_file_mtime');
1375 usort($list, 'sort_file_mtime');
1376 $list = array_reverse($list);
1381 return array_splice($list, 0, $limit);
1385 function _filenameSelector($filename)
1387 if (!$this->_pattern)
1390 if (!$this->_pcre_pattern)
1391 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1392 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1397 function fileSet($directory, $filepattern = false)
1399 $this->_fileList = array();
1400 $this->_pattern = $filepattern;
1402 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1404 $this->_case = !isWindows();
1405 $this->_pathsep = '/';
1407 if (empty($directory)) {
1408 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1410 return; // early return
1413 @ $dir_handle = opendir($dir = $directory);
1414 if (empty($dir_handle)) {
1415 trigger_error(sprintf(_("Unable to open directory “%s” for reading"),
1416 $dir), E_USER_NOTICE);
1417 return; // early return
1420 while ($filename = readdir($dir_handle)) {
1421 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1423 if ($this->_filenameSelector($filename)) {
1424 array_push($this->_fileList, "$filename");
1425 //trigger_error(sprintf(_("found file %s"), $filename),
1426 // E_USER_NOTICE); //debugging
1429 closedir($dir_handle);
1435 // expands a list containing regex's to its matching entries
1436 class ListRegexExpand
1438 public $match, $list, $index, $case_sensitive;
1439 function ListRegexExpand(&$list, $match, $case_sensitive = true)
1441 $this->match = $match;
1442 $this->list = &$list;
1443 $this->case_sensitive = $case_sensitive;
1444 //$this->index = false;
1447 function listMatchCallback($item, $key)
1449 $quoted = str_replace('/', '\/', $item);
1450 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1453 unset($this->list[$this->index]);
1454 $this->list[] = $item;
1458 function expandRegex($index, &$pages)
1460 $this->index = $index;
1461 array_walk($pages, array($this, 'listMatchCallback'));
1466 // Convert fileglob to regex style:
1467 // Convert some wildcards to pcre style, escape the rest
1468 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1469 // Fixed bug #994994: "/" in $glob.
1470 function glob_to_pcre($glob)
1472 // check simple case: no need to escape
1473 $escape = '\[](){}=!<>|:/';
1474 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1476 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1477 $glob = strtr($glob, "\\", "\xff");
1478 $glob = str_replace("/", "\\/", $glob);
1479 // first convert some unescaped expressions to pcre style: . => \.
1481 $re = preg_replace('/([^\xff])?([' . preg_quote($special) . '])/',
1482 "\\1\xff\\2", $glob);
1485 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1486 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1487 if (!preg_match('/^[\?\*]/', $glob))
1489 if (!preg_match('/[\?\*]$/', $glob))
1492 // Fixes Bug 1182997
1493 // .*? handled above, now escape the rest
1494 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1495 $re = preg_replace('/([^\xff])([' . preg_quote($escape, "/") . '])/',
1497 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1499 $re = preg_replace('/\xff/', '', $re);
1503 function glob_match($glob, $against, $case_sensitive = true)
1505 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1509 function explodePageList($input, $include_empty = false, $sortby = 'pagename',
1510 $limit = '', $exclude = '')
1512 include_once 'lib/PageList.php';
1513 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1516 // Class introspections
1518 /** Determine whether a function is okay to use.
1520 * Some providers (e.g. Lycos) disable some of PHP functions for
1521 * "security reasons." This makes those functions, of course,
1522 * unusable, despite the fact the function_exists() says they
1525 * This function test to see if a function exists and is not
1526 * disallowed by PHP's disable_functions config setting.
1528 * @param string $function_name Function name
1529 * @return bool True iff function can be used.
1531 function function_usable($function_name)
1534 if (!is_array($disabled)) {
1535 $disabled = array();
1536 // Use get_cfg_var since ini_get() is one of the disabled functions
1537 // (on Lycos, at least.)
1538 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1539 foreach ($split as $f)
1540 $disabled[strtolower($f)] = true;
1543 return (function_exists($function_name)
1544 and !isset($disabled[strtolower($function_name)])
1550 * This is used for generating ETags.
1552 function wikihash($x)
1554 if (is_scalar($x)) {
1556 } elseif (is_array($x)) {
1558 return md5(serialize($x));
1559 } elseif (is_object($x)) {
1562 trigger_error("Can't hash $x", E_USER_ERROR);
1566 function rand_ascii($length = 1)
1569 for ($i = 1; $i <= $length; $i++) {
1570 // return only typeable 7 bit ascii, avoid quotes
1571 $s .= chr(mt_rand(40, 126));
1576 /* by Dan Frankowski.
1578 function rand_ascii_readable($length = 6)
1580 // Pick a few random letters or numbers
1582 // Don't use 1lI0O, because they're hard to read
1583 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1584 $letter_len = strlen($letters);
1585 for ($i = 0; $i < $length; $i++) {
1586 $word .= $letters[mt_rand(0, $letter_len - 1)];
1592 * Recursively count all non-empty elements
1593 * in array of any dimension or mixed - i.e.
1594 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1595 * See http://www.php.net/manual/en/function.count.php
1597 function count_all($arg)
1599 // skip if argument is empty
1601 //print_r($arg); //debugging
1603 // not an array, return 1 (base case)
1604 if (!is_array($arg))
1606 // else call recursively for all elements $arg
1607 foreach ($arg as $key => $val)
1608 $count += count_all($val);
1614 function isSubPage($pagename)
1616 return (strstr($pagename, SUBPAGE_SEPARATOR));
1619 function subPageSlice($pagename, $pos)
1621 $pages = explode(SUBPAGE_SEPARATOR, $pagename);
1622 $pages = array_slice($pages, $pos, 1);
1626 function isActionPage($filename)
1629 global $AllActionPages;
1631 $localizedAllActionPages = array_map("__", $AllActionPages);
1633 return (in_array($filename, $localizedAllActionPages));
1639 * Class for "popping up" and alert box. (Except that right now, it doesn't
1643 * This is a hackish and needs to be refactored. However it would be nice to
1644 * unify all the different methods we use for showing Alerts and Dialogs.
1645 * (E.g. "Page deleted", login form, ...)
1650 * @param mixed $head Header ("title") for alert box.
1651 * @param mixed $body The text in the alert box.
1652 * @param array $buttons An array mapping button labels to URLs.
1653 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1655 function __construct($head, $body, $buttons = array())
1657 if (is_array($body)) {
1659 foreach ($body as $li) {
1660 $html->pushContent(HTML::li($li));
1664 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1665 $this->_buttons = $buttons;
1669 * Show the alert box.
1675 $tokens = $this->_tokens;
1676 $tokens['BUTTONS'] = $this->_getButtons();
1678 $request->discardOutput();
1679 $tmpl = new Template('dialog', $request, $tokens);
1684 function _getButtons()
1688 $buttons = $this->_buttons;
1690 $buttons = array(_("OK") => $request->getURLtoSelf());
1693 foreach ($buttons as $label => $url)
1694 print "$label $url\n";
1695 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1696 return new XmlContent($out);
1701 // 1.3.9-p1 => 1030.091
1702 // 1.3.10pre => 1030.099
1703 // 1.3.11pre-20041120 => 1030.1120041120
1704 // 1.3.12-rc1 => 1030.119
1705 function phpwiki_version()
1707 static $PHPWIKI_VERSION;
1708 if (!isset($PHPWIKI_VERSION)) {
1709 $arr = explode('.', preg_replace('/\D+$/', '', PHPWIKI_VERSION)); // remove the pre
1710 $arr[2] = preg_replace('/\.+/', '.', preg_replace('/\D/', '.', $arr[2]));
1711 $PHPWIKI_VERSION = $arr[0] * 1000 + $arr[1] * 10 + 0.01 * $arr[2];
1712 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1713 $PHPWIKI_VERSION -= 0.01;
1715 return $PHPWIKI_VERSION;
1718 function phpwiki_gzhandler($ob)
1720 $ob = gzencode($ob);
1721 $GLOBALS['request']->_ob_get_length = strlen($ob);
1722 if (!headers_sent()) {
1723 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1728 function isWikiWord($word)
1730 global $WikiNameRegexp;
1731 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1732 return preg_match("/^$WikiNameRegexp\$/", $word);
1735 // needed to store serialized objects-values only (perm, pref)
1736 function obj2hash($obj, $exclude = false, $fields = false)
1739 if (!$fields) $fields = get_object_vars($obj);
1740 foreach ($fields as $key => $val) {
1741 if (is_array($exclude)) {
1742 if (in_array($key, $exclude)) continue;
1750 * isAsciiString($string)
1752 function isAsciiString($s)
1754 $ptrASCII = '[\x00-\x7F]';
1755 return preg_match("/^($ptrASCII)*$/s", $s);
1759 * Workaround for allow_url_fopen, to get the content of an external URI.
1760 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1761 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1763 function url_get_contents($uri)
1765 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1766 return @file_get_contents($uri);
1768 require_once 'lib/HttpClient.php';
1769 $bits = parse_url($uri);
1770 $host = $bits['host'];
1771 $port = isset($bits['port']) ? $bits['port'] : 80;
1772 $path = isset($bits['path']) ? $bits['path'] : '/';
1773 if (isset($bits['query'])) {
1774 $path .= '?' . $bits['query'];
1776 $client = new HttpClient($host, $port);
1777 $client->use_gzip = false;
1778 if (!$client->get($path)) {
1781 return $client->getContent();
1787 * Generate consecutively named strings:
1788 * Name, Name2, Name3, ...
1790 function GenerateId($name)
1792 static $ids = array();
1793 if (empty($ids[$name])) {
1798 return $name . $ids[$name];
1802 // from IncludePage. To be of general use.
1803 // content: string or array of strings
1804 function firstNWordsOfContent($n, $content)
1806 if ($content and $n > 0) {
1807 if (is_array($content)) {
1808 // fixme: return a list of lines then?
1809 //$content = join("\n", $content);
1810 //$return_array = true;
1812 foreach ($content as $line) {
1813 $words = explode(' ', $line);
1814 if ($wordcount + count($words) > $n) {
1815 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1816 . sprintf(_("... (first %s words)"), $n);
1819 $wordcount += count($words);
1825 // fixme: use better whitespace/word seperators
1826 $words = explode(' ', $content);
1827 if (count($words) > $n) {
1828 return join(' ', array_slice($words, 0, $n))
1829 . sprintf(_("... (first %s words)"), $n);
1839 // moved from lib/plugin/IncludePage.php
1840 function extractSection($section, $content, $page, $quiet = false, $sectionhead = false)
1842 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1844 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
1845 . " \\s*$\\n?" // possible blank lines
1846 . " ( (?: ^.*\\n? )*? )" // some lines
1847 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1848 implode("\n", $content),
1851 // Strip trailing blanks lines and ---- <hr>s
1852 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1854 $text = $match[1] . $section . "\n" . $text;
1855 return explode("\n", $text);
1858 $mesg = $page . " " . $section;
1861 return array(sprintf(_("<%s: no such section>"), $mesg));
1864 // Extract the first $sections sections of the page
1865 function extractSections($sections, $content, $page, $quiet = false, $sectionhead = false)
1868 $mycontent = $content;
1871 while ($sections > 0) {
1873 if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
1874 . " \\s*$\\n?" // possible blank lines
1875 . " ( (?: ^.*\\n? )*? )" // some lines
1876 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
1877 implode("\n", $mycontent),
1880 $section = $match[2];
1881 // Strip trailing blanks lines and ---- <hr>s
1882 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
1884 $text = $match[1] . $section . "\n" . $text;
1887 $mycontent = explode("\n", $match[4]);
1889 if ($sections === 0) {
1890 return explode("\n", $result);
1897 // use this faster version: only load ExternalReferrer if we came from an external referrer
1898 function isExternalReferrer(&$request)
1900 if ($referrer = $request->get('HTTP_REFERER')) {
1901 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
1902 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
1903 require_once 'lib/ExternalReferrer.php';
1904 $se = new SearchEngines();
1905 return $se->parseSearchQuery($referrer);
1907 //if (DEBUG) return array('query' => 'wiki');
1912 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
1914 function loadPhpExtension($extension)
1916 if (!extension_loaded($extension)) {
1917 $isWindows = (substr(PHP_OS, 0, 3) == 'WIN');
1918 $soname = ($isWindows ? 'php_' : '')
1920 . ($isWindows ? '.dll' : '.so');
1924 return extension_loaded($extension);
1927 function string_starts_with($string, $prefix)
1929 return (substr($string, 0, strlen($prefix)) == $prefix);
1932 function string_ends_with($string, $suffix)
1934 return (substr($string, -strlen($suffix)) == $suffix);
1937 function array_remove($arr, $value)
1939 return array_values(array_diff($arr, array($value)));
1943 * Ensure that the script will have another $secs time left.
1944 * Works only if safe_mode is off.
1945 * For example not to timeout on waiting socket connections.
1946 * Use the socket timeout as arg.
1948 function longer_timeout($secs = 30)
1950 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
1951 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
1952 if ($timeleft < $secs)
1953 @set_time_limit(max($timeout, (integer)($secs + $timeleft)));
1956 function printSimpleTrace($bt)
1958 echo "\nTraceback:\n";
1959 debug_print_backtrace();
1963 * @param var $needle
1964 * @param array $haystack one-dimensional numeric array only, no hash
1966 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
1967 It will return false if not found or the index where it was found.
1968 From dennis.decoene@moveit.be http://www.php.net/array_search
1970 function binary_search($needle, $haystack)
1972 $high = count($haystack);
1975 while (($high - $low) > 1) {
1976 $probe = floor(($high + $low) / 2);
1977 if ($haystack[$probe] < $needle) {
1979 } elseif ($haystack[$probe] == $needle) {
1980 $high = $low = $probe;
1986 if ($high == count($haystack) || $haystack[$high] != $needle) {
1993 function is_localhost()
1995 return $_SERVER['SERVER_ADDR'] == '127.0.0.1';
1999 * Take a string and quote it sufficiently to be passed as a Javascript
2000 * string between ''s
2002 function javascript_quote_string($s)
2004 return str_replace("'", "\'", $s);
2007 function isSerialized($s)
2009 return (!empty($s) and (strlen($s) > 3) and (substr($s, 1, 1) == ':'));
2013 * Determine if a variable represents a whole number
2016 function is_whole_number($var)
2018 return (is_numeric($var) && (intval($var) == floatval($var)));
2022 * Take a string and return an array of pairs (attribute name, attribute value)
2024 * We allow attributes with or without double quotes (")
2025 * Attribute-value pairs may be separated by space or comma
2026 * Space is normal HTML attributes, comma is for RichTable compatibility
2027 * border=1, cellpadding="5"
2028 * border=1 cellpadding="5"
2029 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2030 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2032 function parse_attributes($line)
2037 if (empty($line)) return $options;
2038 $line = trim($line);
2039 if (empty($line)) return $options;
2040 $line = trim($line, ",");
2041 if (empty($line)) return $options;
2043 // First we have an attribute name.
2048 while (($i < strlen($line)) && ($line[$i] != '=')) {
2051 $attribute = substr($line, 0, $i);
2052 $attribute = strtolower($attribute);
2054 $line = substr($line, $i + 1);
2055 $line = trim($line);
2056 $line = trim($line, "=");
2057 $line = trim($line);
2059 if (empty($line)) return $options;
2061 // Then we have the attribute value.
2064 // Attribute value might be between double quotes
2065 // In that case we have to find the closing double quote
2066 if ($line[0] == '"') {
2067 $i++; // skip first '"'
2068 while (($i < strlen($line)) && ($line[$i] != '"')) {
2071 $value = substr($line, 0, $i);
2072 $value = trim($value, '"');
2073 $value = trim($value);
2075 // If there are no double quotes, we have to find the next space or comma
2077 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2080 $value = substr($line, 0, $i);
2081 $value = trim($value);
2082 $value = trim($value, ",");
2083 $value = trim($value);
2086 $options[$attribute] = $value;
2088 $line = substr($line, $i + 1);
2089 $line = trim($line);
2090 $line = trim($line, ",");
2091 $line = trim($line);
2093 return $options + parse_attributes($line);
2097 * Returns true if the filename ends with an image suffix.
2098 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif|swf"
2100 function is_image($filename)
2103 if (defined('INLINE_IMAGES')) {
2104 $inline_images = INLINE_IMAGES;
2106 $inline_images = "png|jpg|jpeg|gif|swf";
2109 foreach (explode("|", $inline_images) as $suffix) {
2110 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2118 * Returns true if the filename ends with an video suffix.
2119 * Currently only FLV and OGG
2121 function is_video($filename)
2124 return string_ends_with(strtolower($filename), ".flv")
2125 or string_ends_with(strtolower($filename), ".ogg");
2129 * Remove accents from given text.
2131 function strip_accents($text)
2133 $res = utf8_decode($text);
2135 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2136 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2137 return utf8_encode($res);
2143 // c-basic-offset: 4
2144 // c-hanging-comment-ender-p: nil
2145 // indent-tabs-mode: nil