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 url_get_contents ($uri)
76 firstNWordsOfContent ($n, $content)
77 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
80 string_starts_with($string, $prefix)
81 string_ends_with($string, $suffix)
82 array_remove($arr,$value)
83 longer_timeout($secs=30)
85 binary_search($needle, $haystack)
87 javascript_quote_string($s)
90 parse_attributes($line)
94 function: linkExistingWikiWord($wikiword, $linktext, $version)
95 moved to: lib/WikiTheme.php
97 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
98 else define('_PHPWIKI_STDLIB_LOADED', true);
100 if (!defined('MAX_PAGENAME_LENGTH')) {
101 define('MAX_PAGENAME_LENGTH', 100);
105 * Convert string to a valid XML identifier.
107 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
109 * We would like to have, e.g. named anchors within wiki pages
110 * names like "Table of Contents" --- clearly not a valid XML
111 * fragment identifier.
113 * This function implements a one-to-one map from {any string}
114 * to {valid XML identifiers}.
117 * converting all bytes not in [A-Za-z0-9:_-],
118 * and any leading byte not in [A-Za-z] to '.bb',
119 * where 'bb' is the hexadecimal representation of the
122 * As a special case, the empty string is converted to 'empty.'
127 function MangleXmlIdentifier($str)
132 return preg_replace_callback(
133 '/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/',
135 return '.' . sprintf('%02x', ord('$m'));
141 * Returns a name for the WIKI_ID cookie that should be unique on the host.
142 * But for it to be unique you must have set a unique WIKI_NAME in your
143 * configuration file.
144 * @return string The name of the WIKI_ID cookie to use for this wiki.
146 function getCookieName()
148 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
152 * Generates a valid URL for a given Wiki pagename.
153 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
154 * If a WikiDB_Page object function will extract the name to link to.
155 * If a WikiDB_PageRevision object function will extract the name to link to.
157 * @param bool $get_abs_url Default value is false.
158 * @return string The absolute URL to the page passed as $pagename.
160 function WikiURL($pagename, $args = array(), $get_abs_url = false)
162 global $request, $WikiTheme;
165 if (is_object($pagename)) {
166 if (is_a($pagename, 'WikiDB_Page')) {
167 $pagename = $pagename->getName();
168 } elseif (is_a($pagename, 'WikiDB_PageRevision')) {
169 $page = $pagename->getPage();
170 $args['version'] = $pagename->getVersion();
171 $pagename = $page->getName();
172 } elseif (is_a($pagename, 'WikiPageName')) {
173 $anchor = $pagename->anchor;
174 $pagename = $pagename->name;
176 $anchor = $pagename->anchor;
177 $pagename = $pagename->name;
180 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
182 $args = 'start_debug=' . $request->getArg('start_debug');
183 elseif (is_array($args))
184 $args['start_debug'] = $request->getArg('start_debug'); else
185 $args .= '&start_debug=' . $request->getArg('start_debug');
187 if (is_array($args)) {
189 foreach ($args as $key => $val) {
190 // avoid default args
191 if (USE_PATH_INFO and $key == 'pagename')
193 elseif ($key == 'action' and $val == 'browse')
194 ; elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
195 $enc_args[] = urlencode($key) . '=' . urlencode($val);
197 $args = join('&', $enc_args);
200 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
201 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
202 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
204 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
205 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
206 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
209 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
211 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
220 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
221 $url .= "?pagename=" . rawurlencode($pagename);
226 $url .= "#" . MangleXmlIdentifier($anchor);
230 /** Convert relative URL to absolute URL.
232 * This converts a relative URL to one of PhpWiki's support files
233 * to an absolute one.
236 * @return string Absolute URL
238 function AbsoluteURL($url)
240 if (preg_match('/^https?:/', $url))
242 if ($url[0] != '/') {
243 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
244 while ($base != '/' and substr($url, 0, 3) == "../") {
245 $url = substr($url, 3);
246 $base = dirname($base);
252 return SERVER_URL . $url;
256 * Generates icon in front of links.
258 * @param string $protocol_or_url URL or protocol to determine which icon to use.
260 * @return HtmlElement HtmlElement object that contains data to create img link to
261 * icon for use with url or protocol passed to the function. False if no img to be
264 function IconForLink($protocol_or_url)
268 if (0 and $filename_suffix == false) {
269 // display apache style icon for file type instead of protocol icon
270 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
271 // - document: html, htm, text, txt, rtf, pdf, doc
272 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
273 // - audio: mp3,mp2,aiff,aif,au
274 // - multimedia: mpeg,mpg,mov,qt
277 list ($proto) = explode(':', $protocol_or_url, 2);
278 $src = $WikiTheme->getLinkIconURL($proto);
280 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon'));
287 * Glue icon in front of or after text.
288 * Pref: 'noLinkIcons' - ignore icon if set
289 * WikiTheme: 'LinkIcons' - 'yes' at front
290 * - 'no' display no icon
291 * - 'front' display at left
292 * - 'after' display at right
294 * @param string $proto_or_url Protocol or URL. Used to determine the
296 * @param string $text The text.
297 * @return XmlContent.
299 function PossiblyGlueIconToText($proto_or_url, $text)
301 global $request, $WikiTheme;
302 if ($request->getPref('noLinkIcons'))
304 $icon = IconForLink($proto_or_url);
307 if ($where = $WikiTheme->getLinkIconAttr()) {
308 if ($where == 'no') return $text;
309 if ($where != 'after') $where = 'front';
313 if ($where == 'after') {
314 // span the icon only to the last word (tie them together),
315 // to let the previous words wrap on line breaks.
316 if (!is_object($text)) {
317 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
318 list (, $prefix, $last_word) = $m;
323 $text = HTML::span(array('style' => 'white-space: nowrap'),
324 $last_word, HTML::raw(' '), $icon);
326 $text = HTML($prefix, $text);
329 // span the icon only to the first word (tie them together),
330 // to let the next words wrap on line breaks
331 if (!is_object($text)) {
332 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
333 list (, $first_word, $tail) = $m;
338 $text = HTML::span(array('style' => 'white-space: nowrap'),
341 $text = HTML($text, $tail);
346 * Determines if the url passed to function is safe, by detecting if the characters
347 * '<', '>', or '"' are present.
348 * Check against their urlencoded values also.
350 * @param string $url URL to check for unsafe characters.
351 * @return boolean True if same, false else.
353 function IsSafeURL($url)
355 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
359 * Generates an HtmlElement object to store data for a link.
361 * @param string $url URL that the link will point to.
362 * @param string $linktext Text to be displayed as link.
363 * @return HtmlElement HtmlElement object that contains data to construct an html link.
365 function LinkURL($url, $linktext = '')
367 // FIXME: Is this needed (or sufficient?)
368 if (!IsSafeURL($url)) {
369 $link = HTML::span(array('class' => 'error'), _('Bad URL -- remove all of <, >, "'));
373 $linktext = preg_replace("/mailto:/A", "", $url);
374 $args = array('href' => $url);
375 if (defined('EXTERNAL_LINK_TARGET')) // can also be set in the css
376 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
377 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
379 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
386 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
387 * Disallows sizes which are too small.
388 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
390 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
392 function LinkImage($url, $alt = "")
394 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
395 // Disallow tags in img src urls. Typical CSS attacks.
396 // FIXME: Is this needed (or sufficient?)
397 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
399 // support new syntax: [prefix/image.jpg size=50% border=n]
404 $arr = explode(' ', $url);
405 if (!empty($arr)) $url = $arr[0];
406 if (!IsSafeURL($url)) {
407 $link = HTML::span(array('class' => 'error'), _('Bad URL for image -- remove all of <, >, "'));
410 // spaces in inline images must be %20 encoded!
411 $link = HTML::img(array('src' => $url));
413 // Extract attributes
414 $arr = parse_attributes(strstr($ori_url, " "));
415 foreach ($arr as $attr => $value) {
416 // These attributes take strings: lang, id, title, alt
417 if (($attr == "lang")
419 || ($attr == "title")
422 $link->setAttr($attr, $value);
423 } // align = bottom|middle|top|left|right
424 // we allow "center" as synonym for "middle"
425 elseif (($attr == "align")
426 && (($value == "bottom")
427 || ($value == "middle")
428 || ($value == "center")
430 || ($value == "left")
431 || ($value == "right"))
433 if ($value == "center") {
436 $link->setAttr($attr, $value);
437 } // These attributes take a number (pixels): border, hspace, vspace
438 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
439 && (is_numeric($value))
441 $link->setAttr($attr, (int)$value);
442 } // These attributes take a number (pixels) or a percentage: height, width
443 elseif ((($attr == "height") || ($attr == "width"))
444 && (preg_match('/\d+[%p]?x?/', $value))
446 $link->setAttr($attr, $value);
447 } // We allow size=50% and size=20x30
448 // We replace this with "width" and "height" HTML attributes
449 elseif ($attr == "size") {
450 if (preg_match('/(\d+%)/', $value, $m)) {
451 $link->setAttr('width', $m[1]);
452 $link->setAttr('height', $m[1]);
453 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
454 $link->setAttr('width', $m[1]);
455 $link->setAttr('height', $m[2]);
458 $url = substr(strrchr($ori_url, "/"), 1);
459 $link = HTML::span(array('class' => 'error'),
460 sprintf(_("Invalid attribute %s=%s for image %s"),
461 $attr, $value, $url));
465 // Correct silently the most common error
466 if ($url != $ori_url and empty($arr) and !preg_match("/^http/", $url)) {
467 // space belongs to the path
468 $file = NormalizeLocalFileName($ori_url);
469 if (file_exists($file)) {
470 $link = HTML::img(array('src' => $ori_url));
472 sprintf(_("Invalid image link fixed “%s” => “%s”. Spaces must be quoted with %%20."),
473 $url, $ori_url), E_USER_WARNING);
474 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
475 $file = substr($file, strlen(getUploadDataPath()));
476 $path = getUploadFilePath() . $file;
477 if (file_exists($path)) {
478 trigger_error(sprintf(_("Invalid image link fixed “%s” => “%s”. Spaces must be quoted with %%20."),
479 $url, $ori_url), E_USER_WARNING);
480 $link->setAttr('src', getUploadDataPath() . $file);
485 if (!$link->getAttr('alt')) {
486 $link->setAttr('alt', $alt);
488 // Check width and height as spam countermeasure
489 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
490 //$width = (int) $width; // px or % or other suffix
491 //$height = (int) $height;
492 if (($width < 3 and $height < 10) or
493 ($height < 3 and $width < 20) or
494 ($height < 7 and $width < 7)
496 $link = HTML::span(array('class' => 'error'),
497 _("Invalid image size"));
502 // Prepare for getimagesize($url)
503 // $url only valid for external urls, otherwise local path
504 if (DISABLE_GETIMAGESIZE)
506 elseif (!preg_match("/\.$force_img$/i", $url))
507 ; // only valid image extensions or scripts assumed to generate images
508 elseif (preg_match("/^http/", $url)) { // external url
509 $size = @getimagesize($url);
510 } else { // local file
511 if (file_exists($file = NormalizeLocalFileName($url))) { // here
512 $size = @getimagesize($file);
513 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
514 $size = @getimagesize($file);
515 $link->setAttr('src', rawurldecode($url));
516 } elseif (string_starts_with($url, getUploadDataPath())) { // there
517 $file = substr($file, strlen(getUploadDataPath()));
518 $path = getUploadFilePath() . rawurldecode($file);
519 $size = @getimagesize($path);
520 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
521 } else { // elsewhere
523 $size = @getimagesize($request->get('DOCUMENT_ROOT') . urldecode($url));
529 if (($width < 3 and $height < 10)
530 or ($height < 3 and $width < 20)
531 or ($height < 7 and $width < 7)
533 $link = HTML::span(array('class' => 'error'),
534 _("Invalid image size"));
539 $link->setAttr('class', 'inlineimage');
541 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
542 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
543 * Note: Allow cgi's (pl,cgi) returning images.
545 if (!preg_match("/\.(" . $force_img . ")/i", $ori_url)) {
546 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
547 // => HTML::object(array('src' => $url)) ...;
548 return ImgObject($link, $ori_url);
554 * <object> / <embed> tags instead of <img> for all non-image extensions
556 * Called by LinkImage(), not directly.
557 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
558 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
559 * $alt may be an alternate img
560 * TODO: Need to unify with WikiPluginCached::embedObject()
562 * Note that Safari 1.0 will crash with <object>, so use only <embed>
563 * http://www.alleged.org.uk/pdc/2002/svg-object.html
565 * Allowed object tags:
567 * DATA=URI (object data)
568 * CLASSID=URI (location of implementation)
569 * ARCHIVE=CDATA (archive files)
570 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
571 * WIDTH=Length (object width)
572 * HEIGHT=Length (object height)
573 * NAME=CDATA (name for form submission)
574 * USEMAP=URI (client-side image map)
575 * TYPE=ContentType (content-type of object)
576 * CODETYPE=ContentType (content-type of code)
577 * STANDBY=Text (message to show while loading)
578 * TABINDEX=NUMBER (position in tabbing order)
579 * DECLARE (do not instantiate object)
580 * The rest is added as <param name="" value="" /> tags
582 function ImgObject($img, $url)
584 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
585 $params = explode(",", "id,width,height,data,classid,archive,codebase,name,usemap,type," .
586 "codetype,standby,tabindex,declare");
587 if (is_array($url)) {
590 foreach ($args as $attr => $value) {
591 foreach ($params as $param) {
592 if ($param == $attr) {
593 $img->setAttr($param, $value);
594 if (isset($found[$param])) $found[$param]++;
595 else $found[$param] = 1;
600 // now all remaining args are added as <param> to the object
602 foreach ($args as $attr => $value) {
603 if (!isset($found[$attr])) {
604 $params[] = HTML::param(array('name' => $attr,
608 $url = $img->getAttr('src');
609 $force_img = "png|jpg|gif|jpeg|bmp";
610 if (!preg_match("/\.(" . $force_img . ")/i", $url)) {
611 $img->setAttr('src', false);
614 $args = explode(' ', $url);
615 if (count($args) >= 1) {
616 $url = array_shift($args);
618 foreach ($args as $attr) {
619 foreach ($params as $param) {
620 if (preg_match("/^$param=(\S+)$/i", $attr, $m)) {
621 $img->setAttr($param, $m[1]);
622 if (isset($found[$param])) $found[$param]++;
623 else $found[$param] = 1;
628 // now all remaining args are added as <param> to the object
630 foreach ($args as $attr) {
631 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i", $attr, $m)) {
632 $params[] = HTML::param(array('name' => $m[1],
638 $type = $img->getAttr('type');
640 if (file_exists($url)) {
641 $type = mime_content_type($url);
644 $object = HTML::object(array_merge($img->_attr,
645 array('type' => $type)), //'src' => $url
647 $object->setAttr('class', 'inlineobject');
649 foreach ($params as $param) $object->pushContent($param);
651 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
652 return HTML::embed($object->_attr, $object->_content);
654 $object->pushContent(HTML::embed($object->_attr));
660 function __construct()
662 $this->items = array();
666 public function push($item)
668 $this->items[$this->size] = $item;
673 public function pop()
675 if ($this->size == 0) {
676 return false; // stack is empty
679 return $this->items[$this->size];
682 public function cnt()
687 public function top()
690 return $this->items[$this->size - 1];
697 // end class definition
699 function SplitQueryArgs($query_args = '')
701 // FIXME: use the arg-separator which might not be &
702 $split_args = explode('&', $query_args);
704 while (list($key, $val) = each($split_args))
705 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
706 $args[$m[1]] = $m[2];
710 function LinkPhpwikiURL($url, $text = '', $basepage = false)
713 * @var WikiRequest $request
719 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
720 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
724 $pagename = urldecode($m[1]);
727 if (empty($pagename) &&
728 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)
730 // Convert old style links (to not break diff links in
732 $pagename = urldecode($m[2]);
733 $args = array("action" => $m[1]);
735 $args = SplitQueryArgs($qargs);
738 if (empty($pagename))
739 $pagename = $request->getArg('pagename');
741 if (isset($args['action']) && $args['action'] == 'browse')
742 unset($args['action']);
745 if (empty($args['action']))
747 else if (is_safe_action($args['action']))
748 $class = 'wikiaction';
750 if (empty($args['action']) || is_safe_action($args['action']))
751 $class = 'wikiaction';
753 // Don't allow administrative links on unlocked pages.
754 $dbi = $request->getDbh();
755 $page = $dbi->getPage($basepage ? $basepage : $pagename);
756 if (!$page->get('locked'))
757 return HTML::span(array('class' => 'wikiunsafe'),
758 HTML::u(_("Lock page to enable link")));
759 $class = 'wikiadmin';
763 $text = HTML::span(array('class' => 'rawurl'), $url);
765 $wikipage = new WikiPageName($pagename);
766 if (!$wikipage->isValid()) {
768 return $WikiTheme->linkBadWikiWord($wikipage, $url);
771 return HTML::a(array('href' => WikiURL($pagename, $args), 'class' => $class), $text);
775 * A class to assist in parsing wiki pagenames.
777 * Now with subpages and anchors, parsing and passing around
778 * pagenames is more complicated. This should help.
782 /** Short name for page.
784 * This is the value of $name passed to the constructor.
785 * (For use, e.g. as a default label for links to the page.)
789 /** The full page name.
791 * This is the full name of the page (without anchor).
797 * This is the referenced anchor within the page, or the empty string.
805 * @param mixed $name Page name.
806 * WikiDB_Page, WikiDB_PageRevision, or string.
807 * This can be a relative subpage name (like '/SubPage'),
808 * or can be the empty string to refer to the $basename.
810 * @param mixed $basename Page name from which to interpret
811 * relative or other non-fully-specified page names.
813 * @param mixed $anchor For links to anchors in page.
815 function __construct($name, $basename = false, $anchor = false)
817 if (is_string($name)) {
818 $this->shortName = $name;
819 if (strstr($name, ':')) {
820 list($moniker, $shortName) = explode(":", $name, 2);
821 $map = getInterwikiMap(); // allow overrides to custom maps
822 if (isset($map->_map[$moniker])) {
823 $url = $map->_map[$moniker];
824 if (strstr($url, '%s'))
825 $url = sprintf($url, $shortName);
829 // expand Talk or User, but not to absolute urls!
830 if (strstr($url, '//')) {
831 if ($moniker == 'Talk')
832 $name = $name . '/' . _("Discussion");
836 $this->shortName = $shortName;
839 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
840 if ($name == '' or $name[0] == '/') {
842 $name = $this->_pagename($basename) . $name;
844 $name = $this->_normalize_bad_pagename($name);
845 $this->shortName = $name;
849 $name = $this->_pagename($name);
850 $this->shortName = $name;
853 $this->name = $this->_check($name);
854 $this->anchor = (string)$anchor;
865 if (!($tail = strrchr($name, '/')))
867 return substr($name, 0, -strlen($tail));
870 function isValid($strict = false)
873 return !isset($this->_errors);
874 return (is_string($this->name) and $this->name != '');
877 function getWarnings()
880 if (isset($this->_warnings))
881 $warnings = array_merge($warnings, $this->_warnings);
882 if (isset($this->_errors))
883 $warnings = array_merge($warnings, $this->_errors);
887 return sprintf(_("“%s”: Bad page name: %s"),
888 $this->shortName, join(', ', $warnings));
891 private function _pagename($page)
893 if (is_a($page, 'WikiDB_Page'))
894 return $page->getName();
895 elseif (is_a($page, 'WikiDB_PageRevision'))
896 return $page->getPageName();
897 elseif (is_a($page, 'WikiPageName'))
902 private function _normalize_bad_pagename($name)
904 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
906 // Punt... You really shouldn't get here.
909 return $request->getArg('pagename');
911 assert($name[0] == '/');
912 $this->_errors[] = _("Leading “/” not allowed");
913 return substr($name, 1);
917 * Compress internal white-space to single space character.
919 * This leads to problems with loading a foreign charset pagename,
920 * which cannot be deleted anymore, because unknown chars are compressed.
921 * So BEFORE importing a file _check must be done !!!
923 private function _check($pagename)
925 // Compress internal white-space to single space character.
926 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
927 if ($pagename != $orig)
928 $this->_warnings[] = _("White space converted to single space");
930 // Delete any control characters.
931 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
932 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
933 if ($pagename != $orig)
934 $this->_errors[] = _("Control characters not allowed");
937 // Strip leading and trailing white-space.
938 $pagename = trim($pagename);
941 while ($pagename and $pagename[0] == '/')
942 $pagename = substr($pagename, 1);
943 if ($pagename != $orig)
944 $this->_errors[] = _("Leading “/” not allowed");
946 // not only for SQL, also to restrict url length
947 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
948 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
949 $this->_errors[] = _("Page name too long");
952 // disallow some chars only on file and cvs
953 if ((DATABASE_TYPE == 'cvs'
954 or DATABASE_TYPE == 'file'
955 or DATABASE_TYPE == 'flatfile')
956 and preg_match('/(:|\.\.)/', $pagename, $m)
958 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
959 $pagename = str_replace('..', '', $pagename);
960 $pagename = str_replace(':', '', $pagename);
968 * Expand tabs in string.
970 * Converts all tabs to (the appropriate number of) spaces.
973 * @param int $tab_width
976 function expand_tabs($str, $tab_width = 8)
978 $split = explode("\t", $str);
979 $tail = array_pop($split);
981 foreach ($split as $hunk) {
983 $pos = strlen(strrchr($expanded, "\n")) - 1;
984 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
986 return substr($expanded, 1) . $tail;
990 * Split WikiWords in page names.
992 * It has been deemed useful to split WikiWords (into "Wiki Words") in
993 * places like page titles. This is rumored to help search engines
996 * @param $page string The page name.
998 * @return string The split name.
1000 function SplitPagename($page)
1003 if (preg_match("/\s/", $page))
1004 return $page; // Already split --- don't split any more.
1006 // This algorithm is specialized for several languages.
1007 // (Thanks to Pierrick MEIGNEN)
1008 // Improvements for other languages welcome.
1011 // This mess splits between a lower-case letter followed by
1012 // either an upper-case or a numeral; except that it wont
1013 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1014 switch ($GLOBALS['LANG']) {
1019 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1022 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1025 $sep = preg_quote('/', '/');
1026 // This the single-letter words 'I' and 'A' from any following
1027 // capitalized words.
1028 switch ($GLOBALS['LANG']) {
1030 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1033 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1036 // Split at underscore
1037 $RE[] = '/(_)([[:alpha:]])/';
1038 $RE[] = '/([[:alpha:]])(_)/';
1039 // Split numerals from following letters.
1040 $RE[] = '/(\d)([[:alpha:]])/';
1041 // Split at subpage separators. TBD in WikiTheme.php
1042 $RE[] = "/([^${sep}]+)(${sep})/";
1043 $RE[] = "/(${sep})([^${sep}]+)/";
1045 foreach ($RE as $key)
1049 foreach ($RE as $regexp) {
1050 $page = preg_replace($regexp, '\\1 \\2', $page);
1055 function NoSuchRevision(&$request, $page, $version)
1057 $html = HTML(HTML::h2(_("Revision Not Found")),
1058 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1059 $version, WikiLink($page, 'auto'))));
1060 include_once 'lib/Template.php';
1061 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1066 * Get time offset for local time zone.
1068 * @param int $time Get offset for this time. Default: now.
1069 * @param bool $no_colon Don't put colon between hours and minutes.
1070 * @return string Offset as a string in the format +HH:MM.
1072 function TimezoneOffset($time = 0, $no_colon = false)
1076 $secs = date('Z', $time);
1084 $colon = $no_colon ? '' : ':';
1085 $mins = intval(($secs + 30) / 60);
1086 return sprintf("%s%02d%s%02d",
1087 $sign, $mins / 60, $colon, $mins % 60);
1091 * Format time in ISO-8601 format.
1093 * @param int $time Time. Default: now.
1094 * @return string Date and time in ISO-8601 format.
1096 function Iso8601DateTime($time = 0)
1100 $tzoff = TimezoneOffset($time);
1101 $date = date('Y-m-d', $time);
1102 $time = date('H:i:s', $time);
1103 return $date . 'T' . $time . $tzoff;
1107 * Format time in RFC-2822 format.
1109 * @param int $time Time. Default: now.
1110 * @return string Date and time in RFC-2822 format.
1112 function Rfc2822DateTime($time = 0)
1116 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1120 * Format time in RFC-1123 format.
1122 * @param int $time Time. Default: now.
1123 * @return string Date and time in RFC-1123 format.
1125 function Rfc1123DateTime($time = 0)
1129 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1132 /** Parse date in RFC-1123 format.
1134 * According to RFC 1123 we must accept dates in the following
1137 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1138 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1139 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1141 * (Though we're only allowed to generate dates in the first format.)
1143 function ParseRfc1123DateTime($timestr)
1145 $timestr = trim($timestr);
1146 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1147 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1150 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1151 } elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1152 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1155 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1156 if ($year < 70) $year += 2000;
1157 elseif ($year < 100) $year += 1900;
1158 } elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1159 . '(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1162 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1168 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1170 return false; // failed
1175 * Format time to standard 'ctime' format.
1177 * @param int $time Time. Default: now.
1178 * @return string Date and time.
1180 function CTime($time = 0)
1184 return date("D M j H:i:s Y", $time);
1188 * Format number as kibibytes or bytes.
1189 * Short format is used for PageList
1190 * Long format is used in PageInfo
1192 * @param $bytes int. Default: 0.
1193 * @param $longformat bool. Default: false.
1194 * @return FormattedText (XmlElement.php).
1196 function ByteFormatter($bytes = 0, $longformat = false)
1200 if ($bytes < 1024) {
1202 $size = fmt("%s B", $bytes);
1204 $size = fmt("%s bytes", $bytes);
1206 $kb = round($bytes / 1024, 1);
1208 $size = fmt("%s KiB", $kb);
1210 $size = fmt("%s KiB (%s bytes)", $kb, $bytes);
1216 * Internationalized printf.
1218 * This is essentially the same as PHP's built-in printf
1219 * with the following exceptions:
1221 * <li> It passes the format string through gettext().
1222 * <li> It supports the argument reordering extensions.
1229 * __printf("Differences between versions %s and %s of %s",
1230 * $new_link, $old_link, $page_link);
1233 * Then in locale/po/de.po, one can reorder the printf arguments:
1236 * msgid "Differences between %s and %s of %s."
1237 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1240 * (Note that while PHP tries to expand $vars within double-quotes,
1241 * the values in msgstr undergo no such expansion, so the '$'s
1244 * One shouldn't use reordered arguments in the default format string.
1245 * Backslashes in the default string would be necessary to escape the
1246 * '$'s, and they'll cause all kinds of trouble....
1248 function __printf($fmt)
1250 $args = func_get_args();
1252 echo __vsprintf($fmt, $args);
1256 * Internationalized sprintf.
1258 * This is essentially the same as PHP's built-in printf with the
1259 * following exceptions:
1262 * <li> It passes the format string through gettext().
1263 * <li> It supports the argument reordering extensions.
1268 function __sprintf($fmt)
1270 $args = func_get_args();
1272 return __vsprintf($fmt, $args);
1276 * Internationalized vsprintf.
1278 * This is essentially the same as PHP's built-in printf with the
1279 * following exceptions:
1282 * <li> It passes the format string through gettext().
1283 * <li> It supports the argument reordering extensions.
1288 function __vsprintf($fmt, $args)
1290 $fmt = gettext($fmt);
1291 // PHP's sprintf doesn't support variable with specifiers,
1292 // like sprintf("%*s", 10, "x"); --- so we won't either.
1294 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1295 // Format string has '%2$s' style argument reordering.
1296 // PHP doesn't support this.
1297 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1298 // literal variable name substitution only to keep locale
1299 // strings uncluttered
1300 trigger_error(sprintf(_("Can't mix “%s” with “%s” type format strings"),
1301 '%1\$s', '%s'), E_USER_WARNING); //php+locale error
1303 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1306 // Reorder arguments appropriately.
1307 foreach ($m[1] as $argnum) {
1308 if ($argnum < 1 || $argnum > count($args))
1309 trigger_error(sprintf(_("%s: argument index out of range"),
1310 $argnum), E_USER_WARNING);
1311 $newargs[] = $args[$argnum - 1];
1316 // Not all PHP's have vsprintf, so...
1317 array_unshift($args, $fmt);
1318 return call_user_func_array('sprintf', $args);
1321 function file_mtime($filename)
1323 if ($stat = @stat($filename))
1329 function sort_file_mtime($a, $b)
1331 $ma = file_mtime($a);
1332 $mb = file_mtime($b);
1333 if (!$ma or !$mb or $ma == $mb) return 0;
1334 return ($ma > $mb) ? -1 : 1;
1339 function __construct($directory, $filepattern = false)
1341 $this->_fileList = array();
1342 $this->_pattern = $filepattern;
1344 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1346 $this->_case = !isWindows();
1347 $this->_pathsep = '/';
1349 if (empty($directory) or !file_exists($directory) or !is_dir($directory)) {
1350 return; // early return
1353 $dir_handle = opendir($dir = $directory);
1354 if (empty($dir_handle)) {
1355 return; // early return
1358 while ($filename = readdir($dir_handle)) {
1359 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1361 if ($this->_filenameSelector($filename)) {
1362 array_push($this->_fileList, "$filename");
1365 closedir($dir_handle);
1369 * Build an array in $this->_fileList of files from $dirname.
1370 * Subdirectories are not traversed.
1372 * (This was a function LoadDir in lib/loadsave.php)
1373 * See also http://www.php.net/manual/en/function.readdir.php
1375 public function getFiles($exclude = '', $sortby = '', $limit = '')
1377 $list = $this->_fileList;
1380 require_once 'lib/PageList.php';
1381 switch (Pagelist::sortby($sortby, 'db')) {
1382 case 'pagename ASC':
1384 case 'pagename DESC':
1385 $list = array_reverse($list);
1388 usort($list, 'sort_file_mtime');
1391 usort($list, 'sort_file_mtime');
1392 $list = array_reverse($list);
1397 return array_splice($list, 0, $limit);
1401 protected function _filenameSelector($filename)
1403 if (!$this->_pattern)
1406 if (!$this->_pcre_pattern)
1407 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1408 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1414 class imageSet extends fileSet
1417 * A file is considered an image when the suffix matches one from
1420 protected function _filenameSelector($filename)
1422 return is_image($filename);
1426 class imageOrVideoSet extends fileSet
1428 protected function _filenameSelector($filename)
1430 return is_image($filename) or is_video($filename);
1434 // Convert fileglob to regex style:
1435 // Convert some wildcards to pcre style, escape the rest
1436 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1437 // Fixed bug #994994: "/" in $glob.
1438 function glob_to_pcre($glob)
1440 // check simple case: no need to escape
1441 $escape = '\[](){}=!<>|:/';
1442 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1444 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1445 $glob = strtr($glob, "\\", "\xff");
1446 $glob = str_replace("/", "\\/", $glob);
1447 // first convert some unescaped expressions to pcre style: . => \.
1449 $re = preg_replace('/([^\xff])?([' . preg_quote($special) . '])/',
1450 "\\1\xff\\2", $glob);
1453 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1454 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1455 if (!preg_match('/^[\?\*]/', $glob))
1457 if (!preg_match('/[\?\*]$/', $glob))
1460 // Fixes Bug 1182997
1461 // .*? handled above, now escape the rest
1462 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1463 $re = preg_replace('/([^\xff])([' . preg_quote($escape, "/") . '])/',
1465 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1467 $re = preg_replace('/\xff/', '', $re);
1471 function glob_match($glob, $against, $case_sensitive = true)
1473 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1477 function explodePageList($input, $include_empty = false, $sortby = 'pagename',
1478 $limit = '', $exclude = '')
1480 include_once 'lib/PageList.php';
1481 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1484 // Class introspections
1486 /** Determine whether a function is okay to use.
1488 * Some providers (e.g. Lycos) disable some of PHP functions for
1489 * "security reasons." This makes those functions, of course,
1490 * unusable, despite the fact the function_exists() says they
1493 * This function test to see if a function exists and is not
1494 * disallowed by PHP's disable_functions config setting.
1496 * @param string $function_name Function name
1497 * @return bool True iff function can be used.
1499 function function_usable($function_name)
1502 if (!is_array($disabled)) {
1503 $disabled = array();
1504 // Use get_cfg_var since ini_get() is one of the disabled functions
1505 // (on Lycos, at least.)
1506 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1507 foreach ($split as $f)
1508 $disabled[strtolower($f)] = true;
1511 return (function_exists($function_name)
1512 and !isset($disabled[strtolower($function_name)])
1518 * This is used for generating ETags.
1520 function wikihash($x)
1522 if (is_scalar($x)) {
1524 } elseif (is_array($x)) {
1526 return md5(serialize($x));
1527 } elseif (is_object($x)) {
1530 trigger_error("Can't hash $x", E_USER_ERROR);
1534 function rand_ascii($length = 1)
1537 for ($i = 1; $i <= $length; $i++) {
1538 // return only typeable 7 bit ascii, avoid quotes
1539 $s .= chr(mt_rand(40, 126));
1544 /* by Dan Frankowski.
1546 function rand_ascii_readable($length = 6)
1548 // Pick a few random letters or numbers
1550 // Don't use 1lI0O, because they're hard to read
1551 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1552 $letter_len = strlen($letters);
1553 for ($i = 0; $i < $length; $i++) {
1554 $word .= $letters[mt_rand(0, $letter_len - 1)];
1560 * Recursively count all non-empty elements
1561 * in array of any dimension or mixed - i.e.
1562 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1563 * See http://www.php.net/manual/en/function.count.php
1565 function count_all($arg)
1567 // skip if argument is empty
1569 //print_r($arg); //debugging
1571 // not an array, return 1 (base case)
1572 if (!is_array($arg))
1574 // else call recursively for all elements $arg
1575 foreach ($arg as $key => $val)
1576 $count += count_all($val);
1582 function isSubPage($pagename)
1584 return (strstr($pagename, '/'));
1587 function subPageSlice($pagename, $pos)
1589 $pages = explode('/', $pagename);
1590 $pages = array_slice($pages, $pos, 1);
1594 function isActionPage($filename)
1597 global $AllActionPages;
1599 $localizedAllActionPages = array_map("__", $AllActionPages);
1601 return (in_array($filename, $localizedAllActionPages));
1607 * Class for "popping up" and alert box. (Except that right now, it doesn't
1611 * This is a hackish and needs to be refactored. However it would be nice to
1612 * unify all the different methods we use for showing Alerts and Dialogs.
1613 * (E.g. "Page deleted", login form, ...)
1618 * @param mixed $head Header ("title") for alert box.
1619 * @param mixed $body The text in the alert box.
1620 * @param array $buttons An array mapping button labels to URLs.
1621 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1623 function __construct($head, $body, $buttons = array())
1625 if (is_array($body)) {
1627 foreach ($body as $li) {
1628 $html->pushContent(HTML::li($li));
1632 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1633 $this->_buttons = $buttons;
1637 * Show the alert box.
1639 public function show()
1643 $tokens = $this->_tokens;
1644 $tokens['BUTTONS'] = $this->_getButtons();
1646 $request->discardOutput();
1647 $tmpl = new Template('dialog', $request, $tokens);
1652 private function _getButtons()
1656 $buttons = $this->_buttons;
1658 $buttons = array(_("OK") => $request->getURLtoSelf());
1661 foreach ($buttons as $label => $url)
1662 print "$label $url\n";
1663 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1664 return new XmlContent($out);
1669 // 1.3.9-p1 => 1030.091
1670 // 1.3.10pre => 1030.099
1671 // 1.3.11pre-20041120 => 1030.1120041120
1672 // 1.3.12-rc1 => 1030.119
1673 function phpwiki_version()
1675 static $PHPWIKI_VERSION;
1676 if (!isset($PHPWIKI_VERSION)) {
1677 $arr = explode('.', preg_replace('/\D+$/', '', PHPWIKI_VERSION)); // remove the pre
1678 $arr[2] = preg_replace('/\.+/', '.', preg_replace('/\D/', '.', $arr[2]));
1679 $PHPWIKI_VERSION = $arr[0] * 1000 + $arr[1] * 10 + 0.01 * $arr[2];
1680 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1681 $PHPWIKI_VERSION -= 0.01;
1683 return $PHPWIKI_VERSION;
1686 function phpwiki_gzhandler($ob)
1689 * @var WikiRequest $request
1693 $ob = gzencode($ob);
1694 $request->_ob_get_length = strlen($ob);
1695 if (!headers_sent()) {
1696 header(sprintf("Content-Length: %d", $request->_ob_get_length));
1701 function isWikiWord($word)
1703 global $WikiNameRegexp;
1704 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1705 return preg_match("/^$WikiNameRegexp\$/", $word);
1709 * isAsciiString($string)
1711 function isAsciiString($s)
1713 $ptrASCII = '[\x00-\x7F]';
1714 return preg_match("/^($ptrASCII)*$/s", $s);
1718 * Workaround for allow_url_fopen, to get the content of an external URI.
1719 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1720 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1722 function url_get_contents($uri)
1724 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1725 return @file_get_contents($uri);
1727 require_once 'lib/HttpClient.php';
1728 $bits = parse_url($uri);
1729 $host = $bits['host'];
1730 $port = isset($bits['port']) ? $bits['port'] : 80;
1731 $path = isset($bits['path']) ? $bits['path'] : '/';
1732 if (isset($bits['query'])) {
1733 $path .= '?' . $bits['query'];
1735 $client = new HttpClient($host, $port);
1736 $client->use_gzip = false;
1737 if (!$client->get($path)) {
1740 return $client->getContent();
1746 * Generate consecutively named strings:
1747 * Name, Name2, Name3, ...
1749 function GenerateId($name)
1751 static $ids = array();
1752 if (empty($ids[$name])) {
1757 return $name . $ids[$name];
1761 // from IncludePage. To be of general use.
1762 // content: string or array of strings
1763 function firstNWordsOfContent($n, $content)
1765 if ($content and $n > 0) {
1766 if (is_array($content)) {
1767 // fixme: return a list of lines then?
1768 //$content = join("\n", $content);
1769 //$return_array = true;
1772 foreach ($content as $line) {
1773 $words = explode(' ', $line);
1774 if ($wordcount + count($words) > $n) {
1775 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1776 . sprintf(_("... (first %s words)"), $n);
1779 $wordcount += count($words);
1785 // fixme: use better whitespace/word separators
1786 $words = explode(' ', $content);
1787 if (count($words) > $n) {
1788 return join(' ', array_slice($words, 0, $n))
1789 . sprintf(_("... (first %s words)"), $n);
1799 // moved from lib/plugin/IncludePage.php
1800 function extractSection($section, $content, $page, $quiet = false, $sectionhead = false)
1802 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1804 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
1805 . " \\s*$\\n?" // possible blank lines
1806 . " ( (?: ^.*\\n? )*? )" // some lines
1807 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
1808 implode("\n", $content),
1811 // Strip trailing blanks lines and ---- <hr>s
1812 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
1814 $text = $match[1] . $section . "\n" . $text;
1815 return explode("\n", $text);
1818 $mesg = $page . " " . $section;
1821 return array(sprintf(_("<%s: no such section>"), $mesg));
1824 // Extract the first $sections sections of the page
1825 function extractSections($sections, $content, $page, $quiet = false, $sectionhead = false)
1828 $mycontent = $content;
1831 while ($sections > 0) {
1833 if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
1834 . " \\s*$\\n?" // possible blank lines
1835 . " ( (?: ^.*\\n? )*? )" // some lines
1836 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
1837 implode("\n", $mycontent),
1840 $section = $match[2];
1841 // Strip trailing blanks lines and ---- <hr>s
1842 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
1844 $text = $match[1] . $section . "\n" . $text;
1847 $mycontent = explode("\n", $match[4]);
1849 if ($sections === 0) {
1850 return explode("\n", $result);
1857 // use this faster version: only load ExternalReferrer if we came from an external referrer
1858 function isExternalReferrer(&$request)
1860 if ($referrer = $request->get('HTTP_REFERER')) {
1861 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
1862 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
1863 require_once 'lib/ExternalReferrer.php';
1864 $se = new SearchEngines();
1865 return $se->parseSearchQuery($referrer);
1867 //if (DEBUG) return array('query' => 'wiki');
1872 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
1874 function loadPhpExtension($extension)
1876 if (!extension_loaded($extension)) {
1877 $isWindows = (substr(PHP_OS, 0, 3) == 'WIN');
1878 $soname = ($isWindows ? 'php_' : '')
1880 . ($isWindows ? '.dll' : '.so');
1884 return extension_loaded($extension);
1887 function string_starts_with($string, $prefix)
1889 return (substr($string, 0, strlen($prefix)) == $prefix);
1892 function string_ends_with($string, $suffix)
1894 return (substr($string, -strlen($suffix)) == $suffix);
1897 function array_remove($arr, $value)
1899 return array_values(array_diff($arr, array($value)));
1903 * Ensure that the script will have another $secs time left.
1904 * Works only if safe_mode is off.
1905 * For example not to timeout on waiting socket connections.
1906 * Use the socket timeout as arg.
1908 function longer_timeout($secs = 30)
1910 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
1911 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
1912 if ($timeleft < $secs)
1913 @set_time_limit(max($timeout, (integer)($secs + $timeleft)));
1916 function printSimpleTrace($bt)
1918 echo "\nTraceback:\n";
1919 debug_print_backtrace();
1923 * @param mixed $needle
1924 * @param array $haystack one-dimensional numeric array only, no hash
1926 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
1927 It will return false if not found or the index where it was found.
1928 From dennis.decoene@moveit.be http://www.php.net/array_search
1930 function binary_search($needle, $haystack)
1932 $high = count($haystack);
1935 while (($high - $low) > 1) {
1936 $probe = floor(($high + $low) / 2);
1937 if ($haystack[$probe] < $needle) {
1939 } elseif ($haystack[$probe] == $needle) {
1940 $high = $low = $probe;
1946 if ($high == count($haystack) || $haystack[$high] != $needle) {
1953 function is_localhost()
1955 return $_SERVER['SERVER_ADDR'] == '127.0.0.1';
1959 * Take a string and quote it sufficiently to be passed as a Javascript
1960 * string between ''s
1962 function javascript_quote_string($s)
1964 return str_replace("'", "\'", $s);
1967 function isSerialized($s)
1969 return (!empty($s) and (strlen($s) > 3) and (substr($s, 1, 1) == ':'));
1973 * Determine if a variable represents a limit
1974 * It can be an integer or two integers separated by ","
1977 function is_limit($var)
1979 if (is_whole_number($var)) {
1982 $limits = explode(',', $var);
1983 return (count($limits) == 2)
1984 && is_whole_number($limits[0])
1985 && is_whole_number($limits[1]);
1989 * Determine if a variable represents a whole number
1992 function is_whole_number($var)
1994 return (is_numeric($var) && (intval($var) == floatval($var)));
1998 * Take a string and return an array of pairs (attribute name, attribute value)
2000 * We allow attributes with or without double quotes (")
2001 * Attribute-value pairs may be separated by space or comma
2002 * Space is normal HTML attributes, comma is for RichTable compatibility
2003 * border=1, cellpadding="5"
2004 * border=1 cellpadding="5"
2005 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2006 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2008 function parse_attributes($line)
2013 if (empty($line)) return $options;
2014 $line = trim($line);
2015 if (empty($line)) return $options;
2016 $line = trim($line, ",");
2017 if (empty($line)) return $options;
2019 // First we have an attribute name.
2022 while (($i < strlen($line)) && ($line[$i] != '=')) {
2025 $attribute = substr($line, 0, $i);
2026 $attribute = strtolower($attribute);
2028 $line = substr($line, $i + 1);
2029 $line = trim($line);
2030 $line = trim($line, "=");
2031 $line = trim($line);
2033 if (empty($line)) return $options;
2035 // Then we have the attribute value.
2038 // Attribute value might be between double quotes
2039 // In that case we have to find the closing double quote
2040 if ($line[0] == '"') {
2041 $i++; // skip first '"'
2042 while (($i < strlen($line)) && ($line[$i] != '"')) {
2045 $value = substr($line, 0, $i);
2046 $value = trim($value, '"');
2047 $value = trim($value);
2049 // If there are no double quotes, we have to find the next space or comma
2051 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2054 $value = substr($line, 0, $i);
2055 $value = trim($value);
2056 $value = trim($value, ",");
2057 $value = trim($value);
2060 $options[$attribute] = $value;
2062 $line = substr($line, $i + 1);
2063 $line = trim($line);
2064 $line = trim($line, ",");
2065 $line = trim($line);
2067 return $options + parse_attributes($line);
2071 * Returns true if the filename ends with an image suffix.
2072 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif|swf"
2074 function is_image($filename)
2077 if (defined('INLINE_IMAGES')) {
2078 $inline_images = INLINE_IMAGES;
2080 $inline_images = "png|jpg|jpeg|gif|swf";
2083 foreach (explode("|", $inline_images) as $suffix) {
2084 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2092 * Returns true if the filename ends with an video suffix.
2093 * Currently only FLV and OGG
2095 function is_video($filename)
2098 return string_ends_with(strtolower($filename), ".flv")
2099 or string_ends_with(strtolower($filename), ".ogg");
2103 * Remove accents from given text.
2105 function strip_accents($text)
2107 $res = utf8_decode($text);
2109 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2110 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2111 return utf8_encode($res);
2115 * Sanify filename: replace all disallowed characters with dashes
2117 function sanify_filename($filename)
2119 return mb_ereg_replace('[^\w\. \-]', '-', $filename);
2125 // c-basic-offset: 4
2126 // c-hanging-comment-ender-p: nil
2127 // indent-tabs-mode: nil