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 imageSet extends fileSet
60 class imageOrVideoSet extends fileSet
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;
257 * Generates icon in front of links.
259 * @param string $protocol_or_url URL or protocol to determine which icon to use.
261 * @return HtmlElement HtmlElement object that contains data to create img link to
262 * icon for use with url or protocol passed to the function. False if no img to be
265 function IconForLink($protocol_or_url)
269 if (0 and $filename_suffix == false) {
270 // display apache style icon for file type instead of protocol icon
271 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
272 // - document: html, htm, text, txt, rtf, pdf, doc
273 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
274 // - audio: mp3,mp2,aiff,aif,au
275 // - multimedia: mpeg,mpg,mov,qt
278 list ($proto) = explode(':', $protocol_or_url, 2);
279 $src = $WikiTheme->getLinkIconURL($proto);
281 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon'));
288 * Glue icon in front of or after text.
289 * Pref: 'noLinkIcons' - ignore icon if set
290 * WikiTheme: 'LinkIcons' - 'yes' at front
291 * - 'no' display no icon
292 * - 'front' display at left
293 * - 'after' display at right
295 * @param string $proto_or_url Protocol or URL. Used to determine the
297 * @param string $text The text.
298 * @return XmlContent.
300 function PossiblyGlueIconToText($proto_or_url, $text)
302 global $request, $WikiTheme;
303 if ($request->getPref('noLinkIcons'))
305 $icon = IconForLink($proto_or_url);
308 if ($where = $WikiTheme->getLinkIconAttr()) {
309 if ($where == 'no') return $text;
310 if ($where != 'after') $where = 'front';
314 if ($where == 'after') {
315 // span the icon only to the last word (tie them together),
316 // to let the previous words wrap on line breaks.
317 if (!is_object($text)) {
318 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
319 list (, $prefix, $last_word) = $m;
324 $text = HTML::span(array('style' => 'white-space: nowrap'),
325 $last_word, HTML::Raw(' '), $icon);
327 $text = HTML($prefix, $text);
330 // span the icon only to the first word (tie them together),
331 // to let the next words wrap on line breaks
332 if (!is_object($text)) {
333 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
334 list (, $first_word, $tail) = $m;
339 $text = HTML::span(array('style' => 'white-space: nowrap'),
342 $text = HTML($text, $tail);
347 * Determines if the url passed to function is safe, by detecting if the characters
348 * '<', '>', or '"' are present.
349 * Check against their urlencoded values also.
351 * @param string $url URL to check for unsafe characters.
352 * @return boolean True if same, false else.
354 function IsSafeURL($url)
356 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
360 * Generates an HtmlElement object to store data for a link.
362 * @param string $url URL that the link will point to.
363 * @param string $linktext Text to be displayed as link.
364 * @return HtmlElement HtmlElement object that contains data to construct an html link.
366 function LinkURL($url, $linktext = '')
368 // FIXME: Is this needed (or sufficient?)
369 if (!IsSafeURL($url)) {
370 $link = HTML::span(array('class' => 'error'), _('Bad URL -- remove all of <, >, "'));
374 $linktext = preg_replace("/mailto:/A", "", $url);
375 $args = array('href' => $url);
376 if (defined('EXTERNAL_LINK_TARGET')) // can also be set in the css
377 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
378 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
380 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
387 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
388 * Disallows sizes which are too small.
389 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
391 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
393 function LinkImage($url, $alt = "")
395 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
396 // Disallow tags in img src urls. Typical CSS attacks.
397 // FIXME: Is this needed (or sufficient?)
398 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
400 // support new syntax: [prefix/image.jpg size=50% border=n]
405 $arr = explode(' ', $url);
406 if (!empty($arr)) $url = $arr[0];
407 if (!IsSafeURL($url)) {
408 $link = HTML::span(array('class' => 'error'), _('Bad URL for image -- remove all of <, >, "'));
411 // spaces in inline images must be %20 encoded!
412 $link = HTML::img(array('src' => $url));
414 // Extract attributes
415 $arr = parse_attributes(strstr($ori_url, " "));
416 foreach ($arr as $attr => $value) {
417 // These attributes take strings: lang, id, title, alt
418 if (($attr == "lang")
420 || ($attr == "title")
423 $link->setAttr($attr, $value);
424 } // align = bottom|middle|top|left|right
425 // we allow "center" as synonym for "middle"
426 elseif (($attr == "align")
427 && (($value == "bottom")
428 || ($value == "middle")
429 || ($value == "center")
431 || ($value == "left")
432 || ($value == "right"))
434 if ($value == "center") {
437 $link->setAttr($attr, $value);
438 } // These attributes take a number (pixels): border, hspace, vspace
439 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
440 && (is_numeric($value))
442 $link->setAttr($attr, (int)$value);
443 } // These attributes take a number (pixels) or a percentage: height, width
444 elseif ((($attr == "height") || ($attr == "width"))
445 && (preg_match('/\d+[%p]?x?/', $value))
447 $link->setAttr($attr, $value);
448 } // We allow size=50% and size=20x30
449 // We replace this with "width" and "height" HTML attributes
450 elseif ($attr == "size") {
451 if (preg_match('/(\d+%)/', $value, $m)) {
452 $link->setAttr('width', $m[1]);
453 $link->setAttr('height', $m[1]);
454 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
455 $link->setAttr('width', $m[1]);
456 $link->setAttr('height', $m[2]);
459 $url = substr(strrchr($ori_url, "/"), 1);
460 $link = HTML::span(array('class' => 'error'),
461 sprintf(_("Invalid attribute %s=%s for image %s"),
462 $attr, $value, $url));
466 // Correct silently the most common error
467 if ($url != $ori_url and empty($arr) and !preg_match("/^http/", $url)) {
468 // space belongs to the path
469 $file = NormalizeLocalFileName($ori_url);
470 if (file_exists($file)) {
471 $link = HTML::img(array('src' => $ori_url));
473 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
474 $url, $ori_url), E_USER_WARNING);
475 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
476 $file = substr($file, strlen(getUploadDataPath()));
477 $path = getUploadFilePath() . $file;
478 if (file_exists($path)) {
479 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
480 $url, $ori_url), E_USER_WARNING);
481 $link->setAttr('src', getUploadDataPath() . $file);
486 if (!$link->getAttr('alt')) {
487 $link->setAttr('alt', $alt);
489 // Check width and height as spam countermeasure
490 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
491 //$width = (int) $width; // px or % or other suffix
492 //$height = (int) $height;
493 if (($width < 3 and $height < 10) or
494 ($height < 3 and $width < 20) or
495 ($height < 7 and $width < 7)
497 $link = HTML::span(array('class' => 'error'),
498 _("Invalid image size"));
503 // Prepare for getimagesize($url)
504 // $url only valid for external urls, otherwise local path
505 if (DISABLE_GETIMAGESIZE)
507 elseif (!preg_match("/\.$force_img$/i", $url))
508 ; // only valid image extensions or scripts assumed to generate images
509 elseif (preg_match("/^http/", $url)) { // external url
510 $size = @getimagesize($url);
511 } else { // local file
512 if (file_exists($file = NormalizeLocalFileName($url))) { // here
513 $size = @getimagesize($file);
514 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
515 $size = @getimagesize($file);
516 $link->setAttr('src', rawurldecode($url));
517 } elseif (string_starts_with($url, getUploadDataPath())) { // there
518 $file = substr($file, strlen(getUploadDataPath()));
519 $path = getUploadFilePath() . rawurldecode($file);
520 $size = @getimagesize($path);
521 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
522 } else { // elsewhere
524 $size = @getimagesize($request->get('DOCUMENT_ROOT') . urldecode($url));
530 if (($width < 3 and $height < 10)
531 or ($height < 3 and $width < 20)
532 or ($height < 7 and $width < 7)
534 $link = HTML::span(array('class' => 'error'),
535 _("Invalid image size"));
540 $link->setAttr('class', 'inlineimage');
542 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
543 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
544 * Note: Allow cgi's (pl,cgi) returning images.
546 if (!preg_match("/\.(" . $force_img . ")/i", $ori_url)) {
547 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
548 // => HTML::object(array('src' => $url)) ...;
549 return ImgObject($link, $ori_url);
555 * <object> / <embed> tags instead of <img> for all non-image extensions
557 * Called by LinkImage(), not directly.
558 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
559 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
560 * $alt may be an alternate img
561 * TODO: Need to unify with WikiPluginCached::embedObject()
563 * Note that Safari 1.0 will crash with <object>, so use only <embed>
564 * http://www.alleged.org.uk/pdc/2002/svg-object.html
566 * Allowed object tags:
568 * DATA=URI (object data)
569 * CLASSID=URI (location of implementation)
570 * ARCHIVE=CDATA (archive files)
571 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
572 * WIDTH=Length (object width)
573 * HEIGHT=Length (object height)
574 * NAME=CDATA (name for form submission)
575 * USEMAP=URI (client-side image map)
576 * TYPE=ContentType (content-type of object)
577 * CODETYPE=ContentType (content-type of code)
578 * STANDBY=Text (message to show while loading)
579 * TABINDEX=NUMBER (position in tabbing order)
580 * DECLARE (do not instantiate object)
581 * The rest is added as <param name="" value="" /> tags
583 function ImgObject($img, $url)
585 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
586 $params = explode(",", "id,width,height,data,classid,archive,codebase,name,usemap,type," .
587 "codetype,standby,tabindex,declare");
588 if (is_array($url)) {
591 foreach ($args as $attr => $value) {
592 foreach ($params as $param) {
593 if ($param == $attr) {
594 $img->setAttr($param, $value);
595 if (isset($found[$param])) $found[$param]++;
596 else $found[$param] = 1;
601 // now all remaining args are added as <param> to the object
603 foreach ($args as $attr => $value) {
604 if (!isset($found[$attr])) {
605 $params[] = HTML::param(array('name' => $attr,
609 $url = $img->getAttr('src');
610 $force_img = "png|jpg|gif|jpeg|bmp";
611 if (!preg_match("/\.(" . $force_img . ")/i", $url)) {
612 $img->setAttr('src', false);
615 $args = explode(' ', $url);
616 if (count($args) >= 1) {
617 $url = array_shift($args);
619 foreach ($args as $attr) {
620 foreach ($params as $param) {
621 if (preg_match("/^$param=(\S+)$/i", $attr, $m)) {
622 $img->setAttr($param, $m[1]);
623 if (isset($found[$param])) $found[$param]++;
624 else $found[$param] = 1;
629 // now all remaining args are added as <param> to the object
631 foreach ($args as $attr) {
632 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i", $attr, $m)) {
633 $params[] = HTML::param(array('name' => $m[1],
639 $type = $img->getAttr('type');
641 if (file_exists($url)) {
642 $type = mime_content_type($url);
645 $object = HTML::object(array_merge($img->_attr,
646 array('type' => $type)), //'src' => $url
648 $object->setAttr('class', 'inlineobject');
650 foreach ($params as $param) $object->pushContent($param);
652 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
653 return HTML::embed($object->_attr, $object->_content);
655 $object->pushContent(HTML::embed($object->_attr));
663 $this->items = array();
669 $this->items[$this->size] = $item;
676 if ($this->size == 0) {
677 return false; // stack is empty
680 return $this->items[$this->size];
691 return $this->items[$this->size - 1];
698 // end class definition
700 function SplitQueryArgs($query_args = '')
702 // FIXME: use the arg-seperator which might not be &
703 $split_args = explode('&', $query_args);
705 while (list($key, $val) = each($split_args))
706 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
707 $args[$m[1]] = $m[2];
711 function LinkPhpwikiURL($url, $text = '', $basepage = false)
715 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
716 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
720 $pagename = urldecode($m[1]);
723 if (empty($pagename) &&
724 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)
726 // Convert old style links (to not break diff links in
728 $pagename = urldecode($m[2]);
729 $args = array("action" => $m[1]);
731 $args = SplitQueryArgs($qargs);
734 if (empty($pagename))
735 $pagename = $GLOBALS['request']->getArg('pagename');
737 if (isset($args['action']) && $args['action'] == 'browse')
738 unset($args['action']);
741 if (empty($args['action']))
743 else if (is_safe_action($args['action']))
744 $class = 'wikiaction';
746 if (empty($args['action']) || is_safe_action($args['action']))
747 $class = 'wikiaction';
749 // Don't allow administrative links on unlocked pages.
750 $dbi = $GLOBALS['request']->getDbh();
751 $page = $dbi->getPage($basepage ? $basepage : $pagename);
752 if (!$page->get('locked'))
753 return HTML::span(array('class' => 'wikiunsafe'),
754 HTML::u(_("Lock page to enable link")));
755 $class = 'wikiadmin';
759 $text = HTML::span(array('class' => 'rawurl'), $url);
761 $wikipage = new WikiPageName($pagename);
762 if (!$wikipage->isValid()) {
764 return $WikiTheme->linkBadWikiWord($wikipage, $url);
767 return HTML::a(array('href' => WikiURL($pagename, $args),
773 * A class to assist in parsing wiki pagenames.
775 * Now with subpages and anchors, parsing and passing around
776 * pagenames is more complicated. This should help.
780 /** Short name for page.
782 * This is the value of $name passed to the constructor.
783 * (For use, e.g. as a default label for links to the page.)
787 /** The full page name.
789 * This is the full name of the page (without anchor).
795 * This is the referenced anchor within the page, or the empty string.
803 * @param mixed $name Page name.
804 * WikiDB_Page, WikiDB_PageRevision, or string.
805 * This can be a relative subpage name (like '/SubPage'),
806 * or can be the empty string to refer to the $basename.
808 * @param mixed $basename Page name from which to interpret
809 * relative or other non-fully-specified page names.
811 * @param mixed $anchor For links to anchors in page.
813 function __construct($name, $basename = false, $anchor = false)
815 if (is_string($name)) {
816 $this->shortName = $name;
817 if (strstr($name, ':')) {
818 list($moniker, $shortName) = explode(":", $name, 2);
819 $map = getInterwikiMap(); // allow overrides to custom maps
820 if (isset($map->_map[$moniker])) {
821 $url = $map->_map[$moniker];
822 if (strstr($url, '%s'))
823 $url = sprintf($url, $shortName);
827 // expand Talk or User, but not to absolute urls!
828 if (strstr($url, '//')) {
829 if ($moniker == 'Talk')
830 $name = $name . '/' . _("Discussion");
834 $this->shortName = $shortName;
837 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
838 if ($name == '' or $name[0] == '/') {
840 $name = $this->_pagename($basename) . $name;
842 $name = $this->_normalize_bad_pagename($name);
843 $this->shortName = $name;
847 $name = $this->_pagename($name);
848 $this->shortName = $name;
851 $this->name = $this->_check($name);
852 $this->anchor = (string)$anchor;
863 if (!($tail = strrchr($name, '/')))
865 return substr($name, 0, -strlen($tail));
868 function isValid($strict = false)
871 return !isset($this->_errors);
872 return (is_string($this->name) and $this->name != '');
875 function getWarnings()
878 if (isset($this->_warnings))
879 $warnings = array_merge($warnings, $this->_warnings);
880 if (isset($this->_errors))
881 $warnings = array_merge($warnings, $this->_errors);
885 return sprintf(_("“%s”: Bad page name: %s"),
886 $this->shortName, join(', ', $warnings));
889 function _pagename($page)
891 if (is_a($page, 'WikiDB_Page'))
892 return $page->getName();
893 elseif (is_a($page, 'WikiDB_PageRevision'))
894 return $page->getPageName();
895 elseif (is_a($page, 'WikiPageName'))
900 function _normalize_bad_pagename($name)
902 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
904 // Punt... You really shouldn't get here.
907 return $request->getArg('pagename');
909 assert($name[0] == '/');
910 $this->_errors[] = _("Leading “/” not allowed");
911 return substr($name, 1);
915 * Compress internal white-space to single space character.
917 * This leads to problems with loading a foreign charset pagename,
918 * which cannot be deleted anymore, because unknown chars are compressed.
919 * So BEFORE importing a file _check must be done !!!
921 function _check($pagename)
923 // Compress internal white-space to single space character.
924 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
925 if ($pagename != $orig)
926 $this->_warnings[] = _("White space converted to single space");
928 // Delete any control characters.
929 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
930 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
931 if ($pagename != $orig)
932 $this->_errors[] = _("Control characters not allowed");
935 // Strip leading and trailing white-space.
936 $pagename = trim($pagename);
939 while ($pagename and $pagename[0] == '/')
940 $pagename = substr($pagename, 1);
941 if ($pagename != $orig)
942 $this->_errors[] = _("Leading “/” not allowed");
944 // not only for SQL, also to restrict url length
945 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
946 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
947 $this->_errors[] = _("Page name too long");
950 // disallow some chars only on file and cvs
951 if ((DATABASE_TYPE == 'cvs'
952 or DATABASE_TYPE == 'file'
953 or DATABASE_TYPE == 'flatfile')
954 and preg_match('/(:|\.\.)/', $pagename, $m)
956 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
957 $pagename = str_replace('..', '', $pagename);
958 $pagename = str_replace(':', '', $pagename);
966 * Expand tabs in string.
968 * Converts all tabs to (the appropriate number of) spaces.
971 * @param integer $tab_width
974 function expand_tabs($str, $tab_width = 8)
976 $split = explode("\t", $str);
977 $tail = array_pop($split);
979 foreach ($split as $hunk) {
981 $pos = strlen(strrchr($expanded, "\n")) - 1;
982 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
984 return substr($expanded, 1) . $tail;
988 * Split WikiWords in page names.
990 * It has been deemed useful to split WikiWords (into "Wiki Words") in
991 * places like page titles. This is rumored to help search engines
994 * @param $page string The page name.
996 * @return string The split name.
998 function SplitPagename($page)
1001 if (preg_match("/\s/", $page))
1002 return $page; // Already split --- don't split any more.
1004 // This algorithm is specialized for several languages.
1005 // (Thanks to Pierrick MEIGNEN)
1006 // Improvements for other languages welcome.
1009 // This mess splits between a lower-case letter followed by
1010 // either an upper-case or a numeral; except that it wont
1011 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1012 switch ($GLOBALS['LANG']) {
1017 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1020 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1023 $sep = preg_quote('/', '/');
1024 // This the single-letter words 'I' and 'A' from any following
1025 // capitalized words.
1026 switch ($GLOBALS['LANG']) {
1028 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1031 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1034 // Split at underscore
1035 $RE[] = '/(_)([[:alpha:]])/';
1036 $RE[] = '/([[:alpha:]])(_)/';
1037 // Split numerals from following letters.
1038 $RE[] = '/(\d)([[:alpha:]])/';
1039 // Split at subpage seperators. TBD in WikiTheme.php
1040 $RE[] = "/([^${sep}]+)(${sep})/";
1041 $RE[] = "/(${sep})([^${sep}]+)/";
1043 foreach ($RE as $key)
1047 foreach ($RE as $regexp) {
1048 $page = preg_replace($regexp, '\\1 \\2', $page);
1053 function NoSuchRevision(&$request, $page, $version)
1055 $html = HTML(HTML::h2(_("Revision Not Found")),
1056 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1057 $version, WikiLink($page, 'auto'))));
1058 include_once 'lib/Template.php';
1059 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1064 * Get time offset for local time zone.
1066 * @param int $time Get offset for this time. Default: now.
1067 * @param bool $no_colon Don't put colon between hours and minutes.
1068 * @return string Offset as a string in the format +HH:MM.
1070 function TimezoneOffset($time = 0, $no_colon = false)
1074 $secs = date('Z', $time);
1082 $colon = $no_colon ? '' : ':';
1083 $mins = intval(($secs + 30) / 60);
1084 return sprintf("%s%02d%s%02d",
1085 $sign, $mins / 60, $colon, $mins % 60);
1089 * Format time in ISO-8601 format.
1091 * @param int $time Time. Default: now.
1092 * @return string Date and time in ISO-8601 format.
1094 function Iso8601DateTime($time = 0)
1098 $tzoff = TimezoneOffset($time);
1099 $date = date('Y-m-d', $time);
1100 $time = date('H:i:s', $time);
1101 return $date . 'T' . $time . $tzoff;
1105 * Format time in RFC-2822 format.
1107 * @param int $time Time. Default: now.
1108 * @return string Date and time in RFC-2822 format.
1110 function Rfc2822DateTime($time = 0)
1114 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1118 * Format time in RFC-1123 format.
1120 * @param int $time Time. Default: now.
1121 * @return string Date and time in RFC-1123 format.
1123 function Rfc1123DateTime($time = 0)
1127 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1130 /** Parse date in RFC-1123 format.
1132 * According to RFC 1123 we must accept dates in the following
1135 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1136 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1137 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1139 * (Though we're only allowed to generate dates in the first format.)
1141 function ParseRfc1123DateTime($timestr)
1143 $timestr = trim($timestr);
1144 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1145 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1148 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1149 } elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1150 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1153 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1154 if ($year < 70) $year += 2000;
1155 elseif ($year < 100) $year += 1900;
1156 } elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1157 . '(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1160 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1166 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1168 return false; // failed
1173 * Format time to standard 'ctime' format.
1175 * @param int $time Time. Default: now.
1176 * @return string Date and time.
1178 function CTime($time = 0)
1182 return date("D M j H:i:s Y", $time);
1186 * Format number as kibibytes or bytes.
1187 * Short format is used for PageList
1188 * Long format is used in PageInfo
1190 * @param $bytes int. Default: 0.
1191 * @param $longformat bool. Default: false.
1192 * @return FormattedText (XmlElement.php).
1194 function ByteFormatter($bytes = 0, $longformat = false)
1198 if ($bytes < 1024) {
1200 $size = fmt("%s B", $bytes);
1202 $size = fmt("%s bytes", $bytes);
1204 $kb = round($bytes / 1024, 1);
1206 $size = fmt("%s KiB", $kb);
1208 $size = fmt("%s KiB (%s bytes)", $kb, $bytes);
1214 * Internationalized printf.
1216 * This is essentially the same as PHP's built-in printf
1217 * with the following exceptions:
1219 * <li> It passes the format string through gettext().
1220 * <li> It supports the argument reordering extensions.
1227 * __printf("Differences between versions %s and %s of %s",
1228 * $new_link, $old_link, $page_link);
1231 * Then in locale/po/de.po, one can reorder the printf arguments:
1234 * msgid "Differences between %s and %s of %s."
1235 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1238 * (Note that while PHP tries to expand $vars within double-quotes,
1239 * the values in msgstr undergo no such expansion, so the '$'s
1242 * One shouldn't use reordered arguments in the default format string.
1243 * Backslashes in the default string would be necessary to escape the
1244 * '$'s, and they'll cause all kinds of trouble....
1246 function __printf($fmt)
1248 $args = func_get_args();
1250 echo __vsprintf($fmt, $args);
1254 * Internationalized sprintf.
1256 * This is essentially the same as PHP's built-in printf with the
1257 * following exceptions:
1260 * <li> It passes the format string through gettext().
1261 * <li> It supports the argument reordering extensions.
1266 function __sprintf($fmt)
1268 $args = func_get_args();
1270 return __vsprintf($fmt, $args);
1274 * Internationalized vsprintf.
1276 * This is essentially the same as PHP's built-in printf with the
1277 * following exceptions:
1280 * <li> It passes the format string through gettext().
1281 * <li> It supports the argument reordering extensions.
1286 function __vsprintf($fmt, $args)
1288 $fmt = gettext($fmt);
1289 // PHP's sprintf doesn't support variable with specifiers,
1290 // like sprintf("%*s", 10, "x"); --- so we won't either.
1292 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1293 // Format string has '%2$s' style argument reordering.
1294 // PHP doesn't support this.
1295 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1296 // literal variable name substitution only to keep locale
1297 // strings uncluttered
1298 trigger_error(sprintf(_("Can't mix “%s” with “%s” type format strings"),
1299 '%1\$s', '%s'), E_USER_WARNING); //php+locale error
1301 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1304 // Reorder arguments appropriately.
1305 foreach ($m[1] as $argnum) {
1306 if ($argnum < 1 || $argnum > count($args))
1307 trigger_error(sprintf(_("%s: argument index out of range"),
1308 $argnum), E_USER_WARNING);
1309 $newargs[] = $args[$argnum - 1];
1314 // Not all PHP's have vsprintf, so...
1315 array_unshift($args, $fmt);
1316 return call_user_func_array('sprintf', $args);
1319 function file_mtime($filename)
1321 if ($stat = @stat($filename))
1327 function sort_file_mtime($a, $b)
1329 $ma = file_mtime($a);
1330 $mb = file_mtime($b);
1331 if (!$ma or !$mb or $ma == $mb) return 0;
1332 return ($ma > $mb) ? -1 : 1;
1337 function fileSet($directory, $filepattern = false)
1339 $this->_fileList = array();
1340 $this->_pattern = $filepattern;
1342 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1344 $this->_case = !isWindows();
1345 $this->_pathsep = '/';
1347 if (empty($directory) or !file_exists($directory) or !is_dir($directory)) {
1348 return; // early return
1351 $dir_handle = opendir($dir = $directory);
1352 if (empty($dir_handle)) {
1353 return; // early return
1356 while ($filename = readdir($dir_handle)) {
1357 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1359 if ($this->_filenameSelector($filename)) {
1360 array_push($this->_fileList, "$filename");
1363 closedir($dir_handle);
1367 * Build an array in $this->_fileList of files from $dirname.
1368 * Subdirectories are not traversed.
1370 * (This was a function LoadDir in lib/loadsave.php)
1371 * See also http://www.php.net/manual/en/function.readdir.php
1373 function getFiles($exclude = '', $sortby = '', $limit = '')
1375 $list = $this->_fileList;
1378 require_once 'lib/PageList.php';
1379 switch (Pagelist::sortby($sortby, 'db')) {
1380 case 'pagename ASC':
1382 case 'pagename DESC':
1383 $list = array_reverse($list);
1386 usort($list, 'sort_file_mtime');
1389 usort($list, 'sort_file_mtime');
1390 $list = array_reverse($list);
1395 return array_splice($list, 0, $limit);
1399 function _filenameSelector($filename)
1401 if (!$this->_pattern)
1404 if (!$this->_pcre_pattern)
1405 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1406 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1412 class imageSet extends fileSet
1415 * A file is considered an image when the suffix matches one from
1418 function _filenameSelector($filename)
1420 return is_image($filename);
1424 class imageOrVideoSet extends fileSet
1426 function _filenameSelector($filename)
1428 return is_image($filename) or is_video($filename);
1432 // Convert fileglob to regex style:
1433 // Convert some wildcards to pcre style, escape the rest
1434 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1435 // Fixed bug #994994: "/" in $glob.
1436 function glob_to_pcre($glob)
1438 // check simple case: no need to escape
1439 $escape = '\[](){}=!<>|:/';
1440 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1442 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1443 $glob = strtr($glob, "\\", "\xff");
1444 $glob = str_replace("/", "\\/", $glob);
1445 // first convert some unescaped expressions to pcre style: . => \.
1447 $re = preg_replace('/([^\xff])?([' . preg_quote($special) . '])/',
1448 "\\1\xff\\2", $glob);
1451 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1452 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1453 if (!preg_match('/^[\?\*]/', $glob))
1455 if (!preg_match('/[\?\*]$/', $glob))
1458 // Fixes Bug 1182997
1459 // .*? handled above, now escape the rest
1460 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1461 $re = preg_replace('/([^\xff])([' . preg_quote($escape, "/") . '])/',
1463 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1465 $re = preg_replace('/\xff/', '', $re);
1469 function glob_match($glob, $against, $case_sensitive = true)
1471 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1475 function explodePageList($input, $include_empty = false, $sortby = 'pagename',
1476 $limit = '', $exclude = '')
1478 include_once 'lib/PageList.php';
1479 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1482 // Class introspections
1484 /** Determine whether a function is okay to use.
1486 * Some providers (e.g. Lycos) disable some of PHP functions for
1487 * "security reasons." This makes those functions, of course,
1488 * unusable, despite the fact the function_exists() says they
1491 * This function test to see if a function exists and is not
1492 * disallowed by PHP's disable_functions config setting.
1494 * @param string $function_name Function name
1495 * @return bool True iff function can be used.
1497 function function_usable($function_name)
1500 if (!is_array($disabled)) {
1501 $disabled = array();
1502 // Use get_cfg_var since ini_get() is one of the disabled functions
1503 // (on Lycos, at least.)
1504 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1505 foreach ($split as $f)
1506 $disabled[strtolower($f)] = true;
1509 return (function_exists($function_name)
1510 and !isset($disabled[strtolower($function_name)])
1516 * This is used for generating ETags.
1518 function wikihash($x)
1520 if (is_scalar($x)) {
1522 } elseif (is_array($x)) {
1524 return md5(serialize($x));
1525 } elseif (is_object($x)) {
1528 trigger_error("Can't hash $x", E_USER_ERROR);
1532 function rand_ascii($length = 1)
1535 for ($i = 1; $i <= $length; $i++) {
1536 // return only typeable 7 bit ascii, avoid quotes
1537 $s .= chr(mt_rand(40, 126));
1542 /* by Dan Frankowski.
1544 function rand_ascii_readable($length = 6)
1546 // Pick a few random letters or numbers
1548 // Don't use 1lI0O, because they're hard to read
1549 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1550 $letter_len = strlen($letters);
1551 for ($i = 0; $i < $length; $i++) {
1552 $word .= $letters[mt_rand(0, $letter_len - 1)];
1558 * Recursively count all non-empty elements
1559 * in array of any dimension or mixed - i.e.
1560 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1561 * See http://www.php.net/manual/en/function.count.php
1563 function count_all($arg)
1565 // skip if argument is empty
1567 //print_r($arg); //debugging
1569 // not an array, return 1 (base case)
1570 if (!is_array($arg))
1572 // else call recursively for all elements $arg
1573 foreach ($arg as $key => $val)
1574 $count += count_all($val);
1580 function isSubPage($pagename)
1582 return (strstr($pagename, '/'));
1585 function subPageSlice($pagename, $pos)
1587 $pages = explode('/', $pagename);
1588 $pages = array_slice($pages, $pos, 1);
1592 function isActionPage($filename)
1595 global $AllActionPages;
1597 $localizedAllActionPages = array_map("__", $AllActionPages);
1599 return (in_array($filename, $localizedAllActionPages));
1605 * Class for "popping up" and alert box. (Except that right now, it doesn't
1609 * This is a hackish and needs to be refactored. However it would be nice to
1610 * unify all the different methods we use for showing Alerts and Dialogs.
1611 * (E.g. "Page deleted", login form, ...)
1616 * @param mixed $head Header ("title") for alert box.
1617 * @param mixed $body The text in the alert box.
1618 * @param array $buttons An array mapping button labels to URLs.
1619 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1621 function __construct($head, $body, $buttons = array())
1623 if (is_array($body)) {
1625 foreach ($body as $li) {
1626 $html->pushContent(HTML::li($li));
1630 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1631 $this->_buttons = $buttons;
1635 * Show the alert box.
1641 $tokens = $this->_tokens;
1642 $tokens['BUTTONS'] = $this->_getButtons();
1644 $request->discardOutput();
1645 $tmpl = new Template('dialog', $request, $tokens);
1650 function _getButtons()
1654 $buttons = $this->_buttons;
1656 $buttons = array(_("OK") => $request->getURLtoSelf());
1659 foreach ($buttons as $label => $url)
1660 print "$label $url\n";
1661 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1662 return new XmlContent($out);
1667 // 1.3.9-p1 => 1030.091
1668 // 1.3.10pre => 1030.099
1669 // 1.3.11pre-20041120 => 1030.1120041120
1670 // 1.3.12-rc1 => 1030.119
1671 function phpwiki_version()
1673 static $PHPWIKI_VERSION;
1674 if (!isset($PHPWIKI_VERSION)) {
1675 $arr = explode('.', preg_replace('/\D+$/', '', PHPWIKI_VERSION)); // remove the pre
1676 $arr[2] = preg_replace('/\.+/', '.', preg_replace('/\D/', '.', $arr[2]));
1677 $PHPWIKI_VERSION = $arr[0] * 1000 + $arr[1] * 10 + 0.01 * $arr[2];
1678 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1679 $PHPWIKI_VERSION -= 0.01;
1681 return $PHPWIKI_VERSION;
1684 function phpwiki_gzhandler($ob)
1686 $ob = gzencode($ob);
1687 $GLOBALS['request']->_ob_get_length = strlen($ob);
1688 if (!headers_sent()) {
1689 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1694 function isWikiWord($word)
1696 global $WikiNameRegexp;
1697 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1698 return preg_match("/^$WikiNameRegexp\$/", $word);
1701 // needed to store serialized objects-values only (perm, pref)
1702 function obj2hash($obj, $exclude = false, $fields = false)
1705 if (!$fields) $fields = get_object_vars($obj);
1706 foreach ($fields as $key => $val) {
1707 if (is_array($exclude)) {
1708 if (in_array($key, $exclude)) continue;
1716 * isAsciiString($string)
1718 function isAsciiString($s)
1720 $ptrASCII = '[\x00-\x7F]';
1721 return preg_match("/^($ptrASCII)*$/s", $s);
1725 * Workaround for allow_url_fopen, to get the content of an external URI.
1726 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1727 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1729 function url_get_contents($uri)
1731 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1732 return @file_get_contents($uri);
1734 require_once 'lib/HttpClient.php';
1735 $bits = parse_url($uri);
1736 $host = $bits['host'];
1737 $port = isset($bits['port']) ? $bits['port'] : 80;
1738 $path = isset($bits['path']) ? $bits['path'] : '/';
1739 if (isset($bits['query'])) {
1740 $path .= '?' . $bits['query'];
1742 $client = new HttpClient($host, $port);
1743 $client->use_gzip = false;
1744 if (!$client->get($path)) {
1747 return $client->getContent();
1753 * Generate consecutively named strings:
1754 * Name, Name2, Name3, ...
1756 function GenerateId($name)
1758 static $ids = array();
1759 if (empty($ids[$name])) {
1764 return $name . $ids[$name];
1768 // from IncludePage. To be of general use.
1769 // content: string or array of strings
1770 function firstNWordsOfContent($n, $content)
1772 if ($content and $n > 0) {
1773 if (is_array($content)) {
1774 // fixme: return a list of lines then?
1775 //$content = join("\n", $content);
1776 //$return_array = true;
1779 foreach ($content as $line) {
1780 $words = explode(' ', $line);
1781 if ($wordcount + count($words) > $n) {
1782 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1783 . sprintf(_("... (first %s words)"), $n);
1786 $wordcount += count($words);
1792 // fixme: use better whitespace/word seperators
1793 $words = explode(' ', $content);
1794 if (count($words) > $n) {
1795 return join(' ', array_slice($words, 0, $n))
1796 . sprintf(_("... (first %s words)"), $n);
1806 // moved from lib/plugin/IncludePage.php
1807 function extractSection($section, $content, $page, $quiet = false, $sectionhead = false)
1809 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1811 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
1812 . " \\s*$\\n?" // possible blank lines
1813 . " ( (?: ^.*\\n? )*? )" // some lines
1814 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1815 implode("\n", $content),
1818 // Strip trailing blanks lines and ---- <hr>s
1819 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1821 $text = $match[1] . $section . "\n" . $text;
1822 return explode("\n", $text);
1825 $mesg = $page . " " . $section;
1828 return array(sprintf(_("<%s: no such section>"), $mesg));
1831 // Extract the first $sections sections of the page
1832 function extractSections($sections, $content, $page, $quiet = false, $sectionhead = false)
1835 $mycontent = $content;
1838 while ($sections > 0) {
1840 if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
1841 . " \\s*$\\n?" // possible blank lines
1842 . " ( (?: ^.*\\n? )*? )" // some lines
1843 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
1844 implode("\n", $mycontent),
1847 $section = $match[2];
1848 // Strip trailing blanks lines and ---- <hr>s
1849 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
1851 $text = $match[1] . $section . "\n" . $text;
1854 $mycontent = explode("\n", $match[4]);
1856 if ($sections === 0) {
1857 return explode("\n", $result);
1864 // use this faster version: only load ExternalReferrer if we came from an external referrer
1865 function isExternalReferrer(&$request)
1867 if ($referrer = $request->get('HTTP_REFERER')) {
1868 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
1869 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
1870 require_once 'lib/ExternalReferrer.php';
1871 $se = new SearchEngines();
1872 return $se->parseSearchQuery($referrer);
1874 //if (DEBUG) return array('query' => 'wiki');
1879 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
1881 function loadPhpExtension($extension)
1883 if (!extension_loaded($extension)) {
1884 $isWindows = (substr(PHP_OS, 0, 3) == 'WIN');
1885 $soname = ($isWindows ? 'php_' : '')
1887 . ($isWindows ? '.dll' : '.so');
1891 return extension_loaded($extension);
1894 function string_starts_with($string, $prefix)
1896 return (substr($string, 0, strlen($prefix)) == $prefix);
1899 function string_ends_with($string, $suffix)
1901 return (substr($string, -strlen($suffix)) == $suffix);
1904 function array_remove($arr, $value)
1906 return array_values(array_diff($arr, array($value)));
1910 * Ensure that the script will have another $secs time left.
1911 * Works only if safe_mode is off.
1912 * For example not to timeout on waiting socket connections.
1913 * Use the socket timeout as arg.
1915 function longer_timeout($secs = 30)
1917 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
1918 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
1919 if ($timeleft < $secs)
1920 @set_time_limit(max($timeout, (integer)($secs + $timeleft)));
1923 function printSimpleTrace($bt)
1925 echo "\nTraceback:\n";
1926 debug_print_backtrace();
1930 * @param mixed $needle
1931 * @param array $haystack one-dimensional numeric array only, no hash
1933 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
1934 It will return false if not found or the index where it was found.
1935 From dennis.decoene@moveit.be http://www.php.net/array_search
1937 function binary_search($needle, $haystack)
1939 $high = count($haystack);
1942 while (($high - $low) > 1) {
1943 $probe = floor(($high + $low) / 2);
1944 if ($haystack[$probe] < $needle) {
1946 } elseif ($haystack[$probe] == $needle) {
1947 $high = $low = $probe;
1953 if ($high == count($haystack) || $haystack[$high] != $needle) {
1960 function is_localhost()
1962 return $_SERVER['SERVER_ADDR'] == '127.0.0.1';
1966 * Take a string and quote it sufficiently to be passed as a Javascript
1967 * string between ''s
1969 function javascript_quote_string($s)
1971 return str_replace("'", "\'", $s);
1974 function isSerialized($s)
1976 return (!empty($s) and (strlen($s) > 3) and (substr($s, 1, 1) == ':'));
1980 * Determine if a variable represents a whole number
1983 function is_whole_number($var)
1985 return (is_numeric($var) && (intval($var) == floatval($var)));
1989 * Take a string and return an array of pairs (attribute name, attribute value)
1991 * We allow attributes with or without double quotes (")
1992 * Attribute-value pairs may be separated by space or comma
1993 * Space is normal HTML attributes, comma is for RichTable compatibility
1994 * border=1, cellpadding="5"
1995 * border=1 cellpadding="5"
1996 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
1997 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
1999 function parse_attributes($line)
2004 if (empty($line)) return $options;
2005 $line = trim($line);
2006 if (empty($line)) return $options;
2007 $line = trim($line, ",");
2008 if (empty($line)) return $options;
2010 // First we have an attribute name.
2015 while (($i < strlen($line)) && ($line[$i] != '=')) {
2018 $attribute = substr($line, 0, $i);
2019 $attribute = strtolower($attribute);
2021 $line = substr($line, $i + 1);
2022 $line = trim($line);
2023 $line = trim($line, "=");
2024 $line = trim($line);
2026 if (empty($line)) return $options;
2028 // Then we have the attribute value.
2031 // Attribute value might be between double quotes
2032 // In that case we have to find the closing double quote
2033 if ($line[0] == '"') {
2034 $i++; // skip first '"'
2035 while (($i < strlen($line)) && ($line[$i] != '"')) {
2038 $value = substr($line, 0, $i);
2039 $value = trim($value, '"');
2040 $value = trim($value);
2042 // If there are no double quotes, we have to find the next space or comma
2044 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2047 $value = substr($line, 0, $i);
2048 $value = trim($value);
2049 $value = trim($value, ",");
2050 $value = trim($value);
2053 $options[$attribute] = $value;
2055 $line = substr($line, $i + 1);
2056 $line = trim($line);
2057 $line = trim($line, ",");
2058 $line = trim($line);
2060 return $options + parse_attributes($line);
2064 * Returns true if the filename ends with an image suffix.
2065 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif|swf"
2067 function is_image($filename)
2070 if (defined('INLINE_IMAGES')) {
2071 $inline_images = INLINE_IMAGES;
2073 $inline_images = "png|jpg|jpeg|gif|swf";
2076 foreach (explode("|", $inline_images) as $suffix) {
2077 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2085 * Returns true if the filename ends with an video suffix.
2086 * Currently only FLV and OGG
2088 function is_video($filename)
2091 return string_ends_with(strtolower($filename), ".flv")
2092 or string_ends_with(strtolower($filename), ".ogg");
2096 * Remove accents from given text.
2098 function strip_accents($text)
2100 $res = utf8_decode($text);
2102 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2103 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2104 return utf8_encode($res);
2108 * Sanify filename: replace all disallowed characters with dashes
2110 function sanify_filename($filename)
2112 return mb_ereg_replace('[^\w\. \-]', '-', $filename);
2118 // c-basic-offset: 4
2119 // c-hanging-comment-ender-p: nil
2120 // indent-tabs-mode: nil