1 <?php //rcs_id('$Id$');
3 Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4 Copyright 2008 Marc-Etienne Vargenau, Alcatel-Lucent
6 This file is part of PhpWiki.
8 PhpWiki is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 PhpWiki is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with PhpWiki; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 Standard functions for Wiki functionality
25 WikiURL ($pagename, $args, $get_abs_url)
27 IconForLink ($protocol_or_url)
28 PossiblyGlueIconToText($proto_or_url, $text)
30 LinkURL ($url, $linktext)
31 LinkImage ($url, $alt)
32 ImgObject ($img, $url)
34 SplitQueryArgs ($query_args)
35 LinkPhpwikiURL ($url, $text, $basepage)
36 ConvertOldMarkup ($content, $markup_type = "block")
37 MangleXmlIdentifier($str)
38 UnMangleXmlIdentifier($str)
40 class Stack { push($item), pop(), cnt(), top() }
41 class Alert { show() }
42 class WikiPageName {getParent(),isValid(),getWarnings() }
44 expand_tabs($str, $tab_width = 8)
46 NoSuchRevision ($request, $page, $version)
47 TimezoneOffset ($time, $no_colon)
48 Iso8601DateTime ($time)
49 Rfc2822DateTime ($time)
50 ParseRfc1123DateTime ($timestr)
52 ByteFormatter ($bytes = 0, $longformat = false)
55 __vsprintf ($fmt, $args)
57 file_mtime ($filename)
58 sort_file_mtime ($a, $b)
59 class fileSet {fileSet($directory, $filepattern = false),
60 getFiles($exclude='', $sortby='', $limit='') }
61 class ListRegexExpand { listMatchCallback($item, $key),
62 expandRegex ($index, &$pages) }
65 glob_match ($glob, $against, $case_sensitive = true)
66 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
67 explodePageList ($input, $perm = false)
69 can ($object, $method)
70 function_usable ($function_name)
72 better_srand ($seed = '')
75 subPageSlice ($pagename, $pos)
79 obj2hash ($obj, $exclude = false, $fields = false)
82 url_get_contents ($uri)
84 firstNWordsOfContent ($n, $content)
85 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
88 charset_convert($from, $to, $data)
89 string_starts_with($string, $prefix)
90 string_ends_with($string, $suffix)
91 array_remove($arr,$value)
92 longer_timeout($secs=30)
95 binary_search($needle, $haystack)
97 javascript_quote_string($s)
99 parse_attributes($line)
101 compute_tablecell ($table, $i, $j, $imax, $jmax)
103 function: LinkInterWikiLink($link, $linktext)
104 moved to: lib/interwiki.php
105 function: linkExistingWikiWord($wikiword, $linktext, $version)
106 moved to: lib/WikiTheme.php
107 function: LinkUnknownWikiWord($wikiword, $linktext)
108 moved to: lib/WikiTheme.php
109 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
110 gone see: lib/plugin/RecentChanges.php
112 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
113 else define('_PHPWIKI_STDLIB_LOADED', true);
115 define('MAX_PAGENAME_LENGTH', 100);
118 * Convert string to a valid XML identifier.
120 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
122 * We would like to have, e.g. named anchors within wiki pages
123 * names like "Table of Contents" --- clearly not a valid XML
124 * fragment identifier.
126 * This function implements a one-to-one map from {any string}
127 * to {valid XML identifiers}.
130 * converting all bytes not in [A-Za-z0-9:_-],
131 * and any leading byte not in [A-Za-z] to 'xbb.',
132 * where 'bb' is the hexadecimal representation of the
135 * As a special case, the empty string is converted to 'empty.'
140 function MangleXmlIdentifier($str) {
144 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
145 "'x' . sprintf('%02x', ord('\\0')) . '.'",
149 function UnMangleXmlIdentifier($str) {
150 if ($str == 'empty.')
152 return preg_replace('/x(\w\w)\./e',
153 "sprintf('%c', hex('\\0'))",
158 * Returns a name for the WIKI_ID cookie that should be unique on the host.
159 * But for it to be unique you must have set a unique WIKI_NAME in your
160 * configuration file.
161 * @return string The name of the WIKI_ID cookie to use for this wiki.
163 function GetCookieName() {
164 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
168 * Generates a valid URL for a given Wiki pagename.
169 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
170 * If a WikiDB_Page object function will extract the name to link to.
171 * If a WikiDB_PageRevision object function will extract the name to link to.
173 * @param boolean $get_abs_url Default value is false.
174 * @return string The absolute URL to the page passed as $pagename.
176 function WikiURL($pagename, $args = '', $get_abs_url = false) {
177 global $request, $WikiTheme;
180 if (is_object($pagename)) {
181 if (isa($pagename, 'WikiDB_Page')) {
182 $pagename = $pagename->getName();
184 elseif (isa($pagename, 'WikiDB_PageRevision')) {
185 $page = $pagename->getPage();
186 $args['version'] = $pagename->getVersion();
187 $pagename = $page->getName();
189 elseif (isa($pagename, 'WikiPageName')) {
190 $anchor = $pagename->anchor;
191 $pagename = $pagename->name;
193 $anchor = $pagename->anchor;
194 $pagename = $pagename->name;
197 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
199 $args = 'start_debug=' . $request->getArg('start_debug');
200 elseif (is_array($args))
201 $args['start_debug'] = $request->getArg('start_debug');
203 $args .= '&start_debug=' . $request->getArg('start_debug');
205 if (is_array($args)) {
207 foreach ($args as $key => $val) {
208 // avoid default args
209 if (USE_PATH_INFO and $key == 'pagename')
211 elseif ($key == 'action' and $val == 'browse')
213 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
214 $enc_args[] = urlencode($key) . '=' . urlencode($val);
216 $args = join('&', $enc_args);
219 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
220 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
221 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
223 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
224 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
225 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
228 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
230 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
240 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
241 $url .= "?pagename=" . rawurlencode($pagename);
246 $url .= "#" . MangleXmlIdentifier($anchor);
250 /** Convert relative URL to absolute URL.
252 * This converts a relative URL to one of PhpWiki's support files
253 * to an absolute one.
256 * @return string Absolute URL
258 function AbsoluteURL ($url) {
259 if (preg_match('/^https?:/', $url))
261 if ($url[0] != '/') {
262 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
263 while ($base != '/' and substr($url, 0, 3) == "../") {
264 $url = substr($url, 3);
265 $base = dirname($base);
271 return SERVER_URL . $url;
274 function DataURL ($url) {
275 if (preg_match('/^https?:/', $url))
277 $url = NormalizeWebFileName($url);
278 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
279 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
280 return AbsoluteURL($url);
284 * Generates icon in front of links.
286 * @param string $protocol_or_url URL or protocol to determine which icon to use.
288 * @return HtmlElement HtmlElement object that contains data to create img link to
289 * icon for use with url or protocol passed to the function. False if no img to be
292 function IconForLink($protocol_or_url) {
294 if (0 and $filename_suffix == false) {
295 // display apache style icon for file type instead of protocol icon
296 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
297 // - document: html, htm, text, txt, rtf, pdf, doc
298 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
299 // - audio: mp3,mp2,aiff,aif,au
300 // - multimedia: mpeg,mpg,mov,qt
302 list ($proto) = explode(':', $protocol_or_url, 2);
303 $src = $WikiTheme->getLinkIconURL($proto);
305 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
312 * Glue icon in front of or after text.
313 * Pref: 'noLinkIcons' - ignore icon if set
314 * WikiTheme: 'LinkIcons' - 'yes' at front
315 * - 'no' display no icon
316 * - 'front' display at left
317 * - 'after' display at right
319 * @param string $protocol_or_url Protocol or URL. Used to determine the
321 * @param string $text The text.
322 * @return XmlContent.
324 function PossiblyGlueIconToText($proto_or_url, $text) {
325 global $request, $WikiTheme;
326 if ($request->getPref('noLinkIcons'))
328 $icon = IconForLink($proto_or_url);
331 if ($where = $WikiTheme->getLinkIconAttr()) {
332 if ($where == 'no') return $text;
333 if ($where != 'after') $where = 'front';
337 if ($where == 'after') {
338 // span the icon only to the last word (tie them together),
339 // to let the previous words wrap on line breaks.
340 if (!is_object($text)) {
341 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
342 list (, $prefix, $last_word) = $m;
348 $text = HTML::span(array('style' => 'white-space: nowrap'),
349 $last_word, HTML::Raw(' '), $icon);
351 $text = HTML($prefix, $text);
354 // span the icon only to the first word (tie them together),
355 // to let the next words wrap on line breaks
356 if (!is_object($text)) {
357 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
358 list (, $first_word, $tail) = $m;
364 $text = HTML::span(array('style' => 'white-space: nowrap'),
367 $text = HTML($text, $tail);
372 * Determines if the url passed to function is safe, by detecting if the characters
373 * '<', '>', or '"' are present.
374 * Check against their urlencoded values also.
376 * @param string $url URL to check for unsafe characters.
377 * @return boolean True if same, false else.
379 function IsSafeURL($url) {
380 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
384 * Generates an HtmlElement object to store data for a link.
386 * @param string $url URL that the link will point to.
387 * @param string $linktext Text to be displayed as link.
388 * @return HtmlElement HtmlElement object that contains data to construct an html link.
390 function LinkURL($url, $linktext = '') {
391 // FIXME: Is this needed (or sufficient?)
392 if(! IsSafeURL($url)) {
393 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
394 _("BAD URL -- remove all of <, >, \"")));
398 $linktext = preg_replace("/mailto:/A", "", $url);
399 $args = array('href' => $url);
400 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
401 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
402 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
404 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
411 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
412 * Disallows sizes which are too small.
413 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
415 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
417 function LinkImage($url, $alt = "") {
418 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
419 // Disallow tags in img src urls. Typical CSS attacks.
420 // FIXME: Is this needed (or sufficient?)
421 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
423 if(! IsSafeURL($url)) {
424 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
425 _("BAD URL -- remove all of <, >, \"")));
428 // support new syntax: [prefix/image.jpg size=50% border=n]
429 //if (!preg_match("/\.(".$force_img.")/i", $url))
430 if (empty($alt)) $alt = basename($url);
431 $arr = split(' ',$url);
432 if (!empty($arr)) $url = $arr[0];
434 $link = HTML::img(array('src' => $url, 'alt' => $alt));
436 $link = HTML::img(array('src' => $url,
437 'alt' => $alt, 'title' => $alt));
439 if (count($arr) > 1) {
442 foreach ($arr as $attr) {
443 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
444 $link->setAttr('width',$m[1]);
445 $link->setAttr('height',$m[1]);
447 elseif (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
448 $link->setAttr('width',$m[1]);
449 $link->setAttr('height',$m[2]);
451 elseif (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
452 $link->setAttr('width',$m[1]);
453 elseif (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
454 $link->setAttr('height',$m[1]);
455 elseif (preg_match('/^border=(\d+)$/',$attr,$m))
456 $link->setAttr('border',$m[1]);
457 elseif (preg_match('/^align=(\w+)$/',$attr,$m))
458 $link->setAttr('align',$m[1]);
459 elseif (preg_match('/^hspace=(\d+)$/',$attr,$m))
460 $link->setAttr('hspace',$m[1]);
461 elseif (preg_match('/^vspace=(\d+)$/',$attr,$m))
462 $link->setAttr('vspace',$m[1]);
465 if(! IsSafeURL($url)) {
466 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
467 _("BAD URL -- remove all of <, >, \"")));
470 $link->setAttr('src', $url);
475 // Check width and height as spam countermeasure
476 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
477 //$width = (int) $width; // px or % or other suffix
478 //$height = (int) $height;
479 if (($width < 3 and $height < 10) or
480 ($height < 3 and $width < 20) or
481 ($height < 7 and $width < 7))
483 trigger_error(_("Invalid image size"), E_USER_WARNING);
488 // Prepare for getimagesize($url)
489 // $url only valid for external urls, otherwise local path
490 // Older php versions crash here with certain png's:
491 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
492 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
493 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
494 if (DISABLE_GETIMAGESIZE)
496 elseif (! preg_match("/\.$force_img$/i", $url))
497 ; // only valid image extensions or scripts assumed to generate images
498 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
499 ; // it's safe to assume that this will fail.
500 elseif (preg_match("/^http/",$url)) { // external url
501 $size = @getimagesize($url);
502 } else { // local file
503 if (file_exists($file = NormalizeLocalFileName($url))) { // here
504 $size = @getimagesize($file);
505 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
506 $size = @getimagesize($file);
507 $link->setAttr('src', rawurldecode($url));
508 } elseif (string_starts_with($url, getUploadDataPath())) { // there
509 $file = substr($file, strlen(getUploadDataPath()));
510 $size = @getimagesize(getUploadFilePath().rawurldecode($file));
511 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
512 } else { // elsewhere
513 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
519 if (($width < 3 and $height < 10)
520 or ($height < 3 and $width < 20)
521 or ($height < 7 and $width < 7))
523 trigger_error(_("Invalid image size"), E_USER_WARNING);
529 $link->setAttr('class', 'inlineimage');
531 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
532 * png|jpg|gif|jpeg|bmp|pl|cgi
533 * Note: Allow cgi's (pl,cgi) returning images.
535 if (!preg_match("/\.(".$force_img.")/i", $url)) {
536 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
537 // => HTML::object(array('src' => $url)) ...;
538 return ImgObject($link, $ori_url);
544 * <object> / <embed> tags instead of <img> for all non-image extensions
546 * Called by LinkImage(), not directly.
547 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
548 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
549 * $alt may be an alternate img
550 * TODO: Need to unify with WikiPluginCached::embedObject()
552 * Note that Safari 1.0 will crash with <object>, so use only <embed>
553 * http://www.alleged.org.uk/pdc/2002/svg-object.html
555 * Allowed object tags:
556 * DATA=URI (object data)
557 * CLASSID=URI (location of implementation)
558 * ARCHIVE=CDATA (archive files)
559 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
560 * WIDTH=Length (object width)
561 * HEIGHT=Length (object height)
562 * NAME=CDATA (name for form submission)
563 * USEMAP=URI (client-side image map)
564 * TYPE=ContentType (content-type of object)
565 * CODETYPE=ContentType (content-type of code)
566 * STANDBY=Text (message to show while loading)
567 * TABINDEX=NUMBER (position in tabbing order)
568 * DECLARE (do not instantiate object)
569 * The rest is added as <param name="" value="" /> tags
571 function ImgObject($img, $url) {
572 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
573 $args = split(' ', $url);
575 if (count($args) >= 1) {
576 $url = array_shift($args);
578 foreach ($args as $attr) {
579 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
580 "codetype,standby,tabindex,declare") as $param)
582 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
583 $img->setAttr($param, $m[1]);
589 // now all remaing args are added as <param> to the object
590 foreach ($args as $attr) {
591 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
592 $params[] = HTML::param(array('name' => $m[1],
597 $type = $img->getAttr('type');
599 // TODO: map extension to mime-types if type is not given and php < 4.3
600 if (function_exists('mime_content_type'))
601 $type = mime_content_type($url);
603 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
605 $object->setAttr('class', 'inlineobject');
607 foreach ($params as $param) $object->pushContent($param);
609 if (isBrowserSafari()) {
610 return HTML::embed($object->_attr, $object->_content);
612 $object->pushContent(HTML::embed($object->_attr));
619 // var in php5 deprecated
621 $this->items = array();
624 function push($item) {
625 $this->items[$this->size] = $item;
631 if ($this->size == 0) {
632 return false; // stack is empty
635 return $this->items[$this->size];
644 return $this->items[$this->size - 1];
650 // end class definition
652 function SplitQueryArgs ($query_args = '')
654 // FIXME: use the arg-seperator which might not be &
655 $split_args = split('&', $query_args);
657 while (list($key, $val) = each($split_args))
658 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
659 $args[$m[1]] = $m[2];
663 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
666 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
667 return HTML::strong(array('class' => 'rawurl'),
668 HTML::u(array('class' => 'baduri'),
669 _("BAD phpwiki: URL")));
673 $pagename = urldecode($m[1]);
676 if (empty($pagename) &&
677 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
678 // Convert old style links (to not break diff links in
680 $pagename = urldecode($m[2]);
681 $args = array("action" => $m[1]);
684 $args = SplitQueryArgs($qargs);
687 if (empty($pagename))
688 $pagename = $GLOBALS['request']->getArg('pagename');
690 if (isset($args['action']) && $args['action'] == 'browse')
691 unset($args['action']);
694 if (empty($args['action']))
696 else if (is_safe_action($args['action']))
697 $class = 'wikiaction';
699 if (empty($args['action']) || is_safe_action($args['action']))
700 $class = 'wikiaction';
702 // Don't allow administrative links on unlocked pages.
703 $dbi = $GLOBALS['request']->getDbh();
704 $page = $dbi->getPage($basepage ? $basepage : $pagename);
705 if (!$page->get('locked'))
706 return HTML::span(array('class' => 'wikiunsafe'),
707 HTML::u(_("Lock page to enable link")));
708 $class = 'wikiadmin';
712 $text = HTML::span(array('class' => 'rawurl'), $url);
714 $wikipage = new WikiPageName($pagename);
715 if (!$wikipage->isValid()) {
717 return $WikiTheme->linkBadWikiWord($wikipage, $url);
720 return HTML::a(array('href' => WikiURL($pagename, $args),
726 * A class to assist in parsing wiki pagenames.
728 * Now with subpages and anchors, parsing and passing around
729 * pagenames is more complicated. This should help.
733 /** Short name for page.
735 * This is the value of $name passed to the constructor.
736 * (For use, e.g. as a default label for links to the page.)
740 /** The full page name.
742 * This is the full name of the page (without anchor).
748 * This is the referenced anchor within the page, or the empty string.
754 * @param mixed $name Page name.
755 * WikiDB_Page, WikiDB_PageRevision, or string.
756 * This can be a relative subpage name (like '/SubPage'),
757 * or can be the empty string to refer to the $basename.
759 * @param string $anchor For links to anchors in page.
761 * @param mixed $basename Page name from which to interpret
762 * relative or other non-fully-specified page names.
764 function WikiPageName($name, $basename=false, $anchor=false) {
765 if (is_string($name)) {
766 $this->shortName = $name;
767 if (strstr($name, ':')) {
768 list($moniker, $shortName) = split (":", $name, 2);
769 $map = getInterwikiMap(); // allow overrides to custom maps
770 if (isset($map->_map[$moniker])) {
771 $url = $map->_map[$moniker];
772 if (strstr($url, '%s'))
773 $url = sprintf($url, $shortName);
777 // expand Talk or User, but not to absolute urls!
778 if (strstr($url, '//')) {
779 if ($moniker == 'Talk')
780 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
781 elseif ($moniker == 'User')
786 if (strstr($shortName, '?')) {
787 list($shortName, $dummy) = split("\?", $shortName, 2);
789 $this->shortName = $shortName;
792 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
793 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
795 $name = $this->_pagename($basename) . $name;
797 $name = $this->_normalize_bad_pagename($name);
798 $this->shortName = $name;
803 $name = $this->_pagename($name);
804 $this->shortName = $name;
807 $this->name = $this->_check($name);
808 $this->anchor = (string)$anchor;
815 function getParent() {
817 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
819 return substr($name, 0, -strlen($tail));
822 function isValid($strict = false) {
824 return !isset($this->_errors);
825 return (is_string($this->name) and $this->name != '');
828 function getWarnings() {
830 if (isset($this->_warnings))
831 $warnings = array_merge($warnings, $this->_warnings);
832 if (isset($this->_errors))
833 $warnings = array_merge($warnings, $this->_errors);
837 return sprintf(_("'%s': Bad page name: %s"),
838 $this->shortName, join(', ', $warnings));
841 function _pagename($page) {
842 if (isa($page, 'WikiDB_Page'))
843 return $page->getName();
844 elseif (isa($page, 'WikiDB_PageRevision'))
845 return $page->getPageName();
846 elseif (isa($page, 'WikiPageName'))
848 // '0' or e.g. '1984' should be allowed though
849 if (!is_string($page) and !is_integer($page)) {
850 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
851 $page, gettype($page), get_class($page)),
854 //assert(is_string($page));
858 function _normalize_bad_pagename($name) {
859 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
861 // Punt... You really shouldn't get here.
864 return $request->getArg('pagename');
866 assert($name[0] == SUBPAGE_SEPARATOR);
867 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
868 return substr($name, 1);
872 * Compress internal white-space to single space character.
874 * This leads to problems with loading a foreign charset pagename,
875 * which cannot be deleted anymore, because unknown chars are compressed.
876 * So BEFORE importing a file _check must be done !!!
878 function _check($pagename) {
879 // Compress internal white-space to single space character.
880 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
881 if ($pagename != $orig)
882 $this->_warnings[] = _("White space converted to single space");
884 // Delete any control characters.
885 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
886 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
887 if ($pagename != $orig)
888 $this->_errors[] = _("Control characters not allowed");
891 // Strip leading and trailing white-space.
892 $pagename = trim($pagename);
895 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
896 $pagename = substr($pagename, 1);
897 if ($pagename != $orig)
898 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
900 // ";" is urlencoded, so safe from php arg-delim problems
901 /*if (strstr($pagename, ';')) {
902 $this->_warnings[] = _("';' is deprecated");
903 $pagename = str_replace(';', '', $pagename);
906 // not only for SQL, also to restrict url length
907 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
908 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
909 $this->_errors[] = _("too long");
912 // disallow some chars only on file and cvs
913 if ((DATABASE_TYPE == 'cvs'
914 or DATABASE_TYPE == 'file'
915 or DATABASE_TYPE == 'flatfile')
916 and preg_match('/(:|\.\.)/', $pagename, $m))
918 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
919 $pagename = str_replace('..', '', $pagename);
920 $pagename = str_replace(':', '', $pagename);
928 * Convert old page markup to new-style markup.
930 * @param string $text Old-style wiki markup.
932 * @param string $markup_type
934 * <dt><code>"block"</code> <dd>Convert all markup.
935 * <dt><code>"inline"</code> <dd>Convert only inline markup.
936 * <dt><code>"links"</code> <dd>Convert only link markup.
939 * @return string New-style wiki markup.
941 * @bugs Footnotes don't work quite as before (esp if there are
942 * multiple references to the same footnote. But close enough,
943 * probably for now....
944 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
945 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
946 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
947 * also known to crash, even with Apache1.
949 function ConvertOldMarkup ($text, $markup_type = "block") {
955 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
956 // AnciennesR%E8glesDeFormatage crashes.
957 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
958 // also known to crash, even with Apache1.
960 // I suspect this only to crash with Apache2 and IIS.
961 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
962 and preg_match("/plugin CreateToc/", $text))
964 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
965 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
966 ._("Skipped."), E_USER_WARNING);
968 //if (!DEBUG) return $text;
973 /*****************************************************************
974 * Conversions for inline markup:
981 // escape escaped brackets
985 // change ! escapes to ~'s.
986 global $WikiNameRegexp, $request;
987 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
988 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
989 if (check_php_version(4,3,9)) {
990 $map = getInterwikiMap();
991 if ($map_regex = $map->getRegexp())
992 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
994 $bang_esc[] = $WikiNameRegexp;
995 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
998 $subs["links"] = array($orig, $repl);
1000 // Temporarily URL-encode pairs of underscores in links to hide
1001 // them from the re for bold markup.
1002 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1003 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1006 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1009 // Convert footnote references.
1010 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1011 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1013 // Convert old style emphases to HTML style emphasis.
1014 $orig[] = '/__(.*?)__/';
1015 $repl[] = '<strong>\\1</strong>';
1016 $orig[] = "/''(.*?)''/";
1017 $repl[] = '<em>\\1</em>';
1019 // Escape nestled markup.
1020 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1023 // in old markup headings only allowed at beginning of line
1027 // Convert URL-encoded pairs of underscores in links back to
1028 // real underscores after bold markup has been converted.
1029 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1030 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1032 $subs["inline"] = array($orig, $repl);
1034 /*****************************************************************
1035 * Patterns which match block markup constructs which take
1036 * special handling...
1040 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1042 $blockpats[] = '\|(?:.*\n\|)*';
1045 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1047 // Footnote definitions
1048 $blockpats[] = '\[\s*(\d+)\s*\]';
1052 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1056 $blockpats[] = '!{1,3}[^!]';
1058 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1059 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1061 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1062 . join("|", $blockpats)
1067 if ($markup_type != "block") {
1068 list ($orig, $repl) = $subs[$markup_type];
1069 return preg_replace($orig, $repl, $text);
1072 list ($orig, $repl) = $subs['inline'];
1075 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1076 // AnciennesR%E8glesDeFormatage and more
1077 // See http://www.pcre.org/pcre.txt LIMITATIONS
1078 while (preg_match($block_re, $text, $m)) {
1079 $text = substr($text, strlen($m[0]));
1080 list (,$leading_text, $block) = $m;
1083 if (strchr(" \t", $block[0])) {
1085 $prefix = "<pre>\n";
1086 $suffix = "\n</pre>\n";
1088 elseif ($block[0] == '|') {
1090 $prefix = "<?plugin OldStyleTable\n";
1093 elseif (strchr("#*;", $block[0])) {
1094 // Old-style list item
1095 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1096 list (,$ind,$bullet) = $m;
1097 $block = substr($block, strlen($m[0]));
1099 $indent = str_repeat(' ', strlen($ind));
1100 if ($bullet[0] == ';') {
1101 //$term = ltrim(substr($bullet, 1));
1102 //return $indent . $term . "\n" . $indent . ' ';
1103 $prefix = $ind . $bullet;
1106 $prefix = $indent . $bullet . ' ';
1108 elseif ($block[0] == '[') {
1109 // Footnote definition
1110 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1112 $block = substr($block, strlen($m[0]));
1113 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1115 elseif ($block[0] == '<') {
1117 // HACK: no inline markup...
1121 elseif ($block[0] == '!') {
1123 preg_match('/^!{1,3}/', $block, $m);
1125 $block = substr($block, strlen($m[0]));
1131 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1132 if ($block) $block = preg_replace($orig, $repl, $block);
1133 $out .= $leading_text;
1138 return $out . preg_replace($orig, $repl, $text);
1144 * Expand tabs in string.
1146 * Converts all tabs to (the appropriate number of) spaces.
1148 * @param string $str
1149 * @param integer $tab_width
1152 function expand_tabs($str, $tab_width = 8) {
1153 $split = split("\t", $str);
1154 $tail = array_pop($split);
1156 foreach ($split as $hunk) {
1158 $pos = strlen(strrchr($expanded, "\n")) - 1;
1159 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1161 return substr($expanded, 1) . $tail;
1165 * Split WikiWords in page names.
1167 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1168 * places like page titles. This is rumored to help search engines
1171 * @param $page string The page name.
1173 * @return string The split name.
1175 function SplitPagename ($page) {
1177 if (preg_match("/\s/", $page))
1178 return $page; // Already split --- don't split any more.
1180 // This algorithm is specialized for several languages.
1181 // (Thanks to Pierrick MEIGNEN)
1182 // Improvements for other languages welcome.
1185 // This mess splits between a lower-case letter followed by
1186 // either an upper-case or a numeral; except that it wont
1187 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1188 switch ($GLOBALS['LANG']) {
1193 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1196 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1199 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1200 // This the single-letter words 'I' and 'A' from any following
1201 // capitalized words.
1202 switch ($GLOBALS['LANG']) {
1204 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1207 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1210 // Split numerals from following letters.
1211 $RE[] = '/(\d)([[:alpha:]])/';
1212 // Split at subpage seperators. TBD in WikiTheme.php
1213 $RE[] = "/([^${sep}]+)(${sep})/";
1214 $RE[] = "/(${sep})([^${sep}]+)/";
1216 foreach ($RE as $key)
1217 $RE[$key] = pcre_fix_posix_classes($key);
1220 foreach ($RE as $regexp) {
1221 $page = preg_replace($regexp, '\\1 \\2', $page);
1226 function NoSuchRevision (&$request, $page, $version) {
1227 $html = HTML(HTML::h2(_("Revision Not Found")),
1228 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1229 $version, WikiLink($page, 'auto'))));
1230 include_once('lib/Template.php');
1231 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1237 * Get time offset for local time zone.
1239 * @param $time time_t Get offset for this time. Default: now.
1240 * @param $no_colon boolean Don't put colon between hours and minutes.
1241 * @return string Offset as a string in the format +HH:MM.
1243 function TimezoneOffset ($time = false, $no_colon = false) {
1244 if ($time === false)
1246 $secs = date('Z', $time);
1255 $colon = $no_colon ? '' : ':';
1256 $mins = intval(($secs + 30) / 60);
1257 return sprintf("%s%02d%s%02d",
1258 $sign, $mins / 60, $colon, $mins % 60);
1263 * Format time in ISO-8601 format.
1265 * @param $time time_t Time. Default: now.
1266 * @return string Date and time in ISO-8601 format.
1268 function Iso8601DateTime ($time = false) {
1269 if ($time === false)
1271 $tzoff = TimezoneOffset($time);
1272 $date = date('Y-m-d', $time);
1273 $time = date('H:i:s', $time);
1274 return $date . 'T' . $time . $tzoff;
1278 * Format time in RFC-2822 format.
1280 * @param $time time_t Time. Default: now.
1281 * @return string Date and time in RFC-2822 format.
1283 function Rfc2822DateTime ($time = false) {
1284 if ($time === false)
1286 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1290 * Format time in RFC-1123 format.
1292 * @param $time time_t Time. Default: now.
1293 * @return string Date and time in RFC-1123 format.
1295 function Rfc1123DateTime ($time = false) {
1296 if ($time === false)
1298 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1301 /** Parse date in RFC-1123 format.
1303 * According to RFC 1123 we must accept dates in the following
1306 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1307 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1308 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1310 * (Though we're only allowed to generate dates in the first format.)
1312 function ParseRfc1123DateTime ($timestr) {
1313 $timestr = trim($timestr);
1314 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1315 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1317 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1319 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1320 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1322 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1323 if ($year < 70) $year += 2000;
1324 elseif ($year < 100) $year += 1900;
1326 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1327 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1329 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1336 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1338 return false; // failed
1343 * Format time to standard 'ctime' format.
1345 * @param $time time_t Time. Default: now.
1346 * @return string Date and time.
1348 function CTime ($time = false)
1350 if ($time === false)
1352 return date("D M j H:i:s Y", $time);
1357 * Format number as kilobytes or bytes.
1358 * Short format is used for PageList
1359 * Long format is used in PageInfo
1361 * @param $bytes int. Default: 0.
1362 * @param $longformat bool. Default: false.
1363 * @return class FormattedText (XmlElement.php).
1365 function ByteFormatter ($bytes = 0, $longformat = false) {
1368 if ($bytes < 1024) {
1370 $size = fmt("%s b", $bytes);
1372 $size = fmt("%s bytes", $bytes);
1375 $kb = round($bytes / 1024, 1);
1377 $size = fmt("%s k", $kb);
1379 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1385 * Internationalized printf.
1387 * This is essentially the same as PHP's built-in printf
1388 * with the following exceptions:
1390 * <li> It passes the format string through gettext().
1391 * <li> It supports the argument reordering extensions.
1398 * __printf("Differences between versions %s and %s of %s",
1399 * $new_link, $old_link, $page_link);
1402 * Then in locale/po/de.po, one can reorder the printf arguments:
1405 * msgid "Differences between %s and %s of %s."
1406 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1409 * (Note that while PHP tries to expand $vars within double-quotes,
1410 * the values in msgstr undergo no such expansion, so the '$'s
1413 * One shouldn't use reordered arguments in the default format string.
1414 * Backslashes in the default string would be necessary to escape the
1415 * '$'s, and they'll cause all kinds of trouble....
1417 function __printf ($fmt) {
1418 $args = func_get_args();
1420 echo __vsprintf($fmt, $args);
1424 * Internationalized sprintf.
1426 * This is essentially the same as PHP's built-in printf with the
1427 * following exceptions:
1430 * <li> It passes the format string through gettext().
1431 * <li> It supports the argument reordering extensions.
1436 function __sprintf ($fmt) {
1437 $args = func_get_args();
1439 return __vsprintf($fmt, $args);
1443 * Internationalized vsprintf.
1445 * This is essentially the same as PHP's built-in printf with the
1446 * following exceptions:
1449 * <li> It passes the format string through gettext().
1450 * <li> It supports the argument reordering extensions.
1455 function __vsprintf ($fmt, $args) {
1456 $fmt = gettext($fmt);
1457 // PHP's sprintf doesn't support variable with specifiers,
1458 // like sprintf("%*s", 10, "x"); --- so we won't either.
1460 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1461 // Format string has '%2$s' style argument reordering.
1462 // PHP doesn't support this.
1463 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1464 // literal variable name substitution only to keep locale
1465 // strings uncluttered
1466 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1467 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1469 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1472 // Reorder arguments appropriately.
1473 foreach($m[1] as $argnum) {
1474 if ($argnum < 1 || $argnum > count($args))
1475 trigger_error(sprintf(_("%s: argument index out of range"),
1476 $argnum), E_USER_WARNING);
1477 $newargs[] = $args[$argnum - 1];
1482 // Not all PHP's have vsprintf, so...
1483 array_unshift($args, $fmt);
1484 return call_user_func_array('sprintf', $args);
1487 function file_mtime ($filename) {
1488 if ($stat = @stat($filename))
1494 function sort_file_mtime ($a, $b) {
1495 $ma = file_mtime($a);
1496 $mb = file_mtime($b);
1497 if (!$ma or !$mb or $ma == $mb) return 0;
1498 return ($ma > $mb) ? -1 : 1;
1503 * Build an array in $this->_fileList of files from $dirname.
1504 * Subdirectories are not traversed.
1506 * (This was a function LoadDir in lib/loadsave.php)
1507 * See also http://www.php.net/manual/en/function.readdir.php
1509 function getFiles($exclude='', $sortby='', $limit='') {
1510 $list = $this->_fileList;
1513 require_once('lib/PageList.php');
1514 switch (Pagelist::sortby($sortby, 'db')) {
1515 case 'pagename ASC': break;
1516 case 'pagename DESC':
1517 $list = array_reverse($list);
1520 usort($list,'sort_file_mtime');
1523 usort($list,'sort_file_mtime');
1524 $list = array_reverse($list);
1529 return array_splice($list, 0, $limit);
1533 function _filenameSelector($filename) {
1534 if (! $this->_pattern )
1537 if (! $this->_pcre_pattern )
1538 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1539 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1544 function fileSet($directory, $filepattern = false) {
1545 $this->_fileList = array();
1546 $this->_pattern = $filepattern;
1548 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1550 $this->_case = !isWindows();
1551 $this->_pathsep = '/';
1553 if (empty($directory)) {
1554 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1556 return; // early return
1559 @ $dir_handle = opendir($dir=$directory);
1560 if (empty($dir_handle)) {
1561 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1562 $dir), E_USER_NOTICE);
1563 return; // early return
1566 while ($filename = readdir($dir_handle)) {
1567 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1569 if ($this->_filenameSelector($filename)) {
1570 array_push($this->_fileList, "$filename");
1571 //trigger_error(sprintf(_("found file %s"), $filename),
1572 // E_USER_NOTICE); //debugging
1575 closedir($dir_handle);
1581 // expands a list containing regex's to its matching entries
1582 class ListRegexExpand {
1583 //var $match, $list, $index, $case_sensitive;
1584 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1585 $this->match = $match;
1586 $this->list = &$list;
1587 $this->case_sensitive = $case_sensitive;
1588 //$this->index = false;
1590 function listMatchCallback ($item, $key) {
1591 $quoted = str_replace('/','\/',$item);
1592 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1594 unset($this->list[$this->index]);
1595 $this->list[] = $item;
1598 function expandRegex ($index, &$pages) {
1599 $this->index = $index;
1600 array_walk($pages, array($this, 'listMatchCallback'));
1605 // Convert fileglob to regex style:
1606 // Convert some wildcards to pcre style, escape the rest
1607 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1608 // Fixed bug #994994: "/" in $glob.
1609 function glob_to_pcre ($glob) {
1610 // check simple case: no need to escape
1611 $escape = '\[](){}=!<>|:/';
1612 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1614 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1615 $glob = strtr($glob, "\\", "\xff");
1616 $glob = str_replace("/", "\\/", $glob);
1617 // first convert some unescaped expressions to pcre style: . => \.
1619 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1620 "\\1\xff\\2", $glob);
1623 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1624 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1625 if (!preg_match('/^[\?\*]/', $glob))
1627 if (!preg_match('/[\?\*]$/', $glob))
1630 // Fixes Bug 1182997
1631 // .*? handled above, now escape the rest
1632 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1633 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1635 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1637 $re = preg_replace('/\xff/', '', $re);
1641 function glob_match ($glob, $against, $case_sensitive = true) {
1642 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1646 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1647 $list = explode(',',$input);
1648 // expand wildcards from list of $allnames
1649 if (preg_match('/[\?\*]/',$input)) {
1650 // Optimizing loop invariants:
1651 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1652 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1654 if (preg_match('/[\?\*]/',$f)) {
1656 $expand = new ListRegexExpand($list,
1657 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1658 $expand->expandRegex($i, $allnames);
1665 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1666 function explodePageList($input, $include_empty=false, $sortby='pagename',
1667 $limit='', $exclude='') {
1668 include_once("lib/PageList.php");
1669 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1672 // Class introspections
1675 * Determine whether object is of a specified type.
1676 * In PHP builtin since 4.2.0 as is_a()
1677 * is_a() deprecated in PHP 5, in favor of instanceof operator
1679 * @param $object object An object.
1680 * @param $class string Class name.
1681 * @return bool True iff $object is a $class
1682 * or a sub-type of $class.
1684 function isa ($object, $class) {
1685 //if (check_php_version(5))
1686 // return $object instanceof $class;
1687 if (check_php_version(4,2) and !check_php_version(5))
1688 return is_a($object, $class);
1690 $lclass = check_php_version(5) ? $class : strtolower($class);
1691 return is_object($object)
1692 && ( strtolower(get_class($object)) == strtolower($class)
1693 || is_subclass_of($object, $lclass) );
1696 /** Determine whether (possible) object has method.
1698 * @param $object mixed Object
1699 * @param $method string Method name
1700 * @return bool True iff $object is an object with has method $method.
1702 function can ($object, $method) {
1703 return is_object($object) && method_exists($object, strtolower($method));
1706 /** Determine whether a function is okay to use.
1708 * Some providers (e.g. Lycos) disable some of PHP functions for
1709 * "security reasons." This makes those functions, of course,
1710 * unusable, despite the fact the function_exists() says they
1713 * This function test to see if a function exists and is not
1714 * disallowed by PHP's disable_functions config setting.
1716 * @param string $function_name Function name
1717 * @return bool True iff function can be used.
1719 function function_usable($function_name) {
1721 if (!is_array($disabled)) {
1722 $disabled = array();
1723 // Use get_cfg_var since ini_get() is one of the disabled functions
1724 // (on Lycos, at least.)
1725 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1726 foreach ($split as $f)
1727 $disabled[strtolower($f)] = true;
1730 return ( function_exists($function_name)
1731 and ! isset($disabled[strtolower($function_name)])
1738 * This is used for generating ETags.
1740 function wikihash ($x) {
1741 if (is_scalar($x)) {
1744 elseif (is_array($x)) {
1746 return md5(serialize($x));
1748 elseif (is_object($x)) {
1751 trigger_error("Can't hash $x", E_USER_ERROR);
1756 * Seed the random number generator.
1758 * better_srand() ensures the randomizer is seeded only once.
1760 * How random do you want it? See:
1761 * http://www.php.net/manual/en/function.srand.php
1762 * http://www.php.net/manual/en/function.mt-srand.php
1764 function better_srand($seed = '') {
1765 static $wascalled = FALSE;
1767 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1768 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1770 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1774 function rand_ascii($length = 1) {
1777 for ($i = 1; $i <= $length; $i++) {
1778 // return only typeable 7 bit ascii, avoid quotes
1779 if (function_exists('mt_rand'))
1780 $s .= chr(mt_rand(40, 126));
1782 // the usually bad glibc srand()
1783 $s .= chr(rand(40, 126));
1788 /* by Dan Frankowski.
1790 function rand_ascii_readable ($length = 6) {
1791 // Pick a few random letters or numbers
1794 // Don't use 1lI0O, because they're hard to read
1795 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1796 $letter_len = strlen($letters);
1797 for ($i=0; $i < $length; $i++) {
1798 if (function_exists('mt_rand'))
1799 $word .= $letters[mt_rand(0, $letter_len-1)];
1801 $word .= $letters[rand(0, $letter_len-1)];
1807 * Recursively count all non-empty elements
1808 * in array of any dimension or mixed - i.e.
1809 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1810 * See http://www.php.net/manual/en/function.count.php
1812 function count_all($arg) {
1813 // skip if argument is empty
1815 //print_r($arg); //debugging
1817 // not an array, return 1 (base case)
1820 // else call recursively for all elements $arg
1821 foreach($arg as $key => $val)
1822 $count += count_all($val);
1827 function isSubPage($pagename) {
1828 return (strstr($pagename, SUBPAGE_SEPARATOR));
1831 function subPageSlice($pagename, $pos) {
1832 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1833 $pages = array_slice($pages,$pos,1);
1840 * Class for "popping up" and alert box. (Except that right now, it doesn't
1844 * This is a hackish and needs to be refactored. However it would be nice to
1845 * unify all the different methods we use for showing Alerts and Dialogs.
1846 * (E.g. "Page deleted", login form, ...)
1851 * @param object $request
1852 * @param mixed $head Header ("title") for alert box.
1853 * @param mixed $body The text in the alert box.
1854 * @param hash $buttons An array mapping button labels to URLs.
1855 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1857 function Alert($head, $body, $buttons=false) {
1858 if ($buttons === false)
1861 if (is_array($body)) {
1863 foreach ($body as $li) {
1864 $html->pushContent(HTML::li($li));
1868 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1869 $this->_buttons = $buttons;
1873 * Show the alert box.
1878 $tokens = $this->_tokens;
1879 $tokens['BUTTONS'] = $this->_getButtons();
1881 $request->discardOutput();
1882 $tmpl = new Template('dialog', $request, $tokens);
1888 function _getButtons() {
1891 $buttons = $this->_buttons;
1893 $buttons = array(_("Okay") => $request->getURLtoSelf());
1896 foreach ($buttons as $label => $url)
1897 print "$label $url\n";
1898 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1899 return new XmlContent($out);
1904 // 1.3.9-p1 => 1030.091
1905 // 1.3.10pre => 1030.099
1906 // 1.3.11pre-20041120 => 1030.1120041120
1907 // 1.3.12-rc1 => 1030.119
1908 function phpwiki_version() {
1909 static $PHPWIKI_VERSION;
1910 if (!isset($PHPWIKI_VERSION)) {
1911 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1912 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1913 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1914 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1915 $PHPWIKI_VERSION -= 0.01;
1917 return $PHPWIKI_VERSION;
1920 function phpwiki_gzhandler($ob) {
1921 if (function_exists('gzencode'))
1922 $ob = gzencode($ob);
1923 $GLOBALS['request']->_ob_get_length = strlen($ob);
1924 if (!headers_sent()) {
1925 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1930 function isWikiWord($word) {
1931 global $WikiNameRegexp;
1932 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1933 return preg_match("/^$WikiNameRegexp\$/",$word);
1936 // needed to store serialized objects-values only (perm, pref)
1937 function obj2hash ($obj, $exclude = false, $fields = false) {
1939 if (! $fields ) $fields = get_object_vars($obj);
1940 foreach ($fields as $key => $val) {
1941 if (is_array($exclude)) {
1942 if (in_array($key, $exclude)) continue;
1950 * isUtf8String($string) - cheap utf-8 detection
1952 * segfaults for strings longer than 10kb!
1953 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1954 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1956 function isUtf8String( $s ) {
1957 $ptrASCII = '[\x00-\x7F]';
1958 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1959 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1960 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1961 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1962 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1963 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1967 * Check for UTF-8 URLs; Internet Explorer produces these if you
1968 * type non-ASCII chars in the URL bar or follow unescaped links.
1969 * Requires urldecoded pagename.
1970 * Fixes sf.net bug #953949
1972 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1974 function fixTitleEncoding( $s ) {
1979 if (empty($s)) return $s;
1981 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1983 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1984 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1986 $isutf = ($ishigh ? isUtf8String($s) : true);
1987 $locharset = strtolower($charset);
1989 if( $locharset != "utf-8" and $ishigh and $isutf )
1990 $s = charset_convert('UTF-8', $locharset, $s);
1991 if ($locharset == "utf-8" and $ishigh and !$isutf )
1992 return utf8_encode( $s );
1994 // Other languages can safely leave this function, or replace
1995 // it with one to detect and convert another legacy encoding.
2000 * MySQL fulltext index doesn't grok utf-8, so we
2001 * need to fold cases and convert to hex.
2002 * src: languages/Language.php:stripForSearch() from mediawiki
2005 function stripForSearch( $string ) {
2006 global $wikiLowerChars;
2007 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2008 return preg_replace(
2009 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2010 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2016 * Workaround for allow_url_fopen, to get the content of an external URI.
2017 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2018 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2020 function url_get_contents( $uri ) {
2021 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2022 return @file_get_contents($uri);
2024 require_once("lib/HttpClient.php");
2025 $bits = parse_url($uri);
2026 $host = $bits['host'];
2027 $port = isset($bits['port']) ? $bits['port'] : 80;
2028 $path = isset($bits['path']) ? $bits['path'] : '/';
2029 if (isset($bits['query'])) {
2030 $path .= '?'.$bits['query'];
2032 $client = new HttpClient($host, $port);
2033 $client->use_gzip = false;
2034 if (!$client->get($path)) {
2037 return $client->getContent();
2043 * Generate consecutively named strings:
2044 * Name, Name2, Name3, ...
2046 function GenerateId($name) {
2047 static $ids = array();
2048 if (empty($ids[$name])) {
2053 return $name . $ids[$name];
2057 // from IncludePage. To be of general use.
2058 // content: string or array of strings
2059 function firstNWordsOfContent( $n, $content ) {
2060 if ($content and $n > 0) {
2061 if (is_array($content)) {
2062 // fixme: return a list of lines then?
2063 //$content = join("\n", $content);
2064 //$return_array = true;
2066 foreach ($content as $line) {
2067 $words = explode(' ', $line);
2068 if ($wordcount + count($words) > $n) {
2069 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2070 . sprintf(_("... (first %s words)"), $n);
2073 $wordcount += count($words);
2079 // fixme: use better whitespace/word seperators
2080 $words = explode(' ', $content);
2081 if (count($words) > $n) {
2082 return join(' ', array_slice($words, 0, $n))
2083 . sprintf(_("... (first %s words)"), $n);
2093 // moved from lib/plugin/IncludePage.php
2094 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2095 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2097 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2098 . " \\s*$\\n?" // possible blank lines
2099 . " ( (?: ^.*\\n? )*? )" // some lines
2100 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2101 implode("\n", $content),
2103 // Strip trailing blanks lines and ---- <hr>s
2104 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2106 $text = $match[1] . $section ."\n". $text;
2107 return explode("\n", $text);
2110 $mesg = $page ." ". $section;
2113 return array(sprintf(_("<%s: no such section>"), $mesg));
2116 // Extract the first $sections sections of the page
2117 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2119 $mycontent = $content;
2122 while ($sections > 0) {
2124 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2125 . " \\s*$\\n?" // possible blank lines
2126 . " ( (?: ^.*\\n? )*? )" // some lines
2127 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2128 implode("\n", $mycontent),
2130 $section = $match[2];
2131 // Strip trailing blanks lines and ---- <hr>s
2132 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2134 $text = $match[1] . $section ."\n". $text;
2137 $mycontent = explode("\n", $match[4]);
2139 if ($sections === 0) {
2140 return explode("\n", $result);
2146 // use this faster version: only load ExternalReferrer if we came from an external referrer
2147 function isExternalReferrer(&$request) {
2148 if ($referrer = $request->get('HTTP_REFERER')) {
2149 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2150 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2151 require_once("lib/ExternalReferrer.php");
2152 $se = new SearchEngines();
2153 return $se->parseSearchQuery($referrer);
2155 //if (DEBUG) return array('query' => 'wiki');
2160 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2162 function loadPhpExtension($extension) {
2163 if (!extension_loaded($extension)) {
2164 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2165 $soname = ($isWindows ? 'php_' : '')
2167 . ($isWindows ? '.dll' : '.so');
2171 return extension_loaded($extension);
2174 function charset_convert($from, $to, $data) {
2176 //$wikicharset = strtolower($CHARSET);
2177 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2178 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2179 return utf8_decode($data);
2180 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2181 return utf8_encode($data);
2183 if (loadPhpExtension("iconv")) {
2184 $tmpdata = iconv($from, $to, $data);
2186 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2190 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2195 function string_starts_with($string, $prefix) {
2196 return (substr($string, 0, strlen($prefix)) == $prefix);
2198 function string_ends_with($string, $suffix) {
2199 return (substr($string, -strlen($suffix)) == $suffix);
2201 function array_remove($arr,$value) {
2202 return array_values(array_diff($arr,array($value)));
2206 * Ensure that the script will have another $secs time left.
2207 * Works only if safe_mode is off.
2208 * For example not to timeout on waiting socket connections.
2209 * Use the socket timeout as arg.
2211 function longer_timeout($secs = 30) {
2212 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2213 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2214 if ($timeleft < $secs)
2215 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2218 function printSimpleTrace($bt) {
2220 echo "\nTraceback:\n";
2221 if (function_exists('debug_print_backtrace')) { // >= 5
2222 debug_print_backtrace();
2224 foreach ($bt as $i => $elem) {
2225 if (!array_key_exists('file', $elem)) {
2228 //echo join(" ",array_values($elem)),"\n";
2229 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2235 * Return the used process memory, in bytes.
2236 * Enable the section which will work for you. They are very slow.
2237 * Special quirks for Windows: Requires cygwin.
2239 function getMemoryUsage() {
2240 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2241 if (function_exists('memory_get_usage') and memory_get_usage()) {
2242 return memory_get_usage();
2243 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2244 $mem = $u['ru_maxrss'];
2245 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2246 // what we want is the process memory only: apache or php (if CGI)
2249 // win32_ps_stat_proc, win32_ps_stat_mem
2250 if (function_exists('win32_ps_list_procs')) {
2251 $info = win32_ps_stat_proc($pid);
2252 $memstr = $info['mem']['working_set_size'];
2254 // This works only if it's a cygwin process (apache or php).
2255 // Requires a newer cygwin
2256 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2258 // if it's native windows use something like this:
2259 // (requires pslist from sysinternals.com, grep, sed and perl)
2260 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2262 return (integer) trim($memstr);
2265 //%MEM: Percentage of total memory in use by this process
2266 //VSZ: Total virtual memory size, in 1K blocks.
2267 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2268 //CPU time used by process since it started.
2269 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2270 $memstr = exec("ps -orss -p $pid|sed 1d");
2271 return (integer) trim($memstr);
2276 * @param var $needle
2277 * @param array $haystack one-dimensional numeric array only, no hash
2279 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2280 It will return false if not found or the index where it was found.
2281 From dennis.decoene@moveit.be http://www.php.net/array_search
2283 function binary_search($needle, $haystack) {
2284 $high = count($haystack);
2287 while (($high - $low) > 1) {
2288 $probe = floor(($high + $low) / 2);
2289 if ($haystack[$probe] < $needle) {
2291 } elseif ($haystack[$probe] == $needle) {
2292 $high = $low = $probe;
2298 if ($high == count($haystack) || $haystack[$high] != $needle) {
2305 function is_localhost($url = false) {
2307 global $HTTP_SERVER_VARS;
2308 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2313 * Take a string and quote it sufficiently to be passed as a Javascript
2314 * string between ''s
2316 function javascript_quote_string($s) {
2317 return str_replace("'", "\'", $s);
2320 function isSerialized($s) {
2321 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2325 * Take a string and return an array of pairs (attribute name, attribute value)
2327 * We allow attributes with or without double quotes (")
2328 * Attribute-value pairs may be separated by space or comma
2329 * Space is normal HTML attributes, comma is for RichTable compatibility
2330 * border=1, cellpadding="5"
2331 * border=1 cellpadding="5"
2332 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2333 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2335 function parse_attributes($line) {
2339 if (empty($line)) return $options;
2340 $line = trim($line);
2341 if (empty($line)) return $options;
2342 $line = trim($line, ",");
2343 if (empty($line)) return $options;
2345 // First we have an attribute name.
2350 while (($i < strlen($line)) && ($line[$i] != '=')) {
2353 $attribute = substr($line, 0, $i);
2354 $attribute = strtolower($attribute);
2356 $line = substr($line, $i+1);
2357 $line = trim ($line);
2358 $line = trim ($line, "=");
2359 $line = trim ($line);
2361 // Then we have the attribute value.
2364 // Attribute value might be between double quotes
2365 // In that case we have to find the closing double quote
2366 if ($line[0] == '"') {
2367 $i++; // skip first '"'
2368 while (($i < strlen($line)) && ($line[$i] != '"')) {
2371 $value = substr($line, 0, $i);
2372 $value = trim ($value, '"');
2373 $value = trim ($value);
2375 // If there are no double quotes, we have to find the next space or comma
2377 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2380 $value = substr($line, 0, $i);
2381 $value = trim ($value);
2382 $value = trim ($value, ",");
2383 $value = trim ($value);
2386 $options[$attribute] = $value;
2388 $line = substr($line, $i+1);
2389 $line = trim ($line);
2391 return $options + parse_attributes($line);
2395 * Returns true if the filename ends with an image suffix.
2396 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2398 function is_image ($filename) {
2400 if (defined('INLINE_IMAGES')) {
2401 $inline_images = INLINE_IMAGES;
2403 $inline_images = "png|jpg|jpeg|gif";
2406 foreach (explode("|", $inline_images) as $suffix) {
2407 if (string_ends_with($filename, "." . $suffix)) {
2415 * Compute cell in spreadsheet table
2416 * $table: two-dimensional table
2417 * $i and $j: indexes of cell to compute
2418 * $imax and $jmax: table dimensions
2420 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2422 // What is implemented:
2423 // @@=SUM(R)@@ : sum of cells in current row
2424 // @@=SUM(C)@@ : sum of cells in current column
2425 // @@=AVERAGE(R)@@ : average of cells in current row
2426 // @@=AVERAGE(C)@@ : average of cells in current column
2427 // @@=MAX(R)@@ : maximum value of cells in current row
2428 // @@=MAX(C)@@ : maximum value of cells in current column
2429 // @@=MIN(R)@@ : minimum value of cells in current row
2430 // @@=MIN(C)@@ : minimum value of cells in current column
2431 // @@=COUNT(R)@@ : number of cells in current row
2432 // (numeric or not, excluding headers and current cell)
2433 // @@=COUNT(C)@@ : number of cells in current column
2434 // (numeric or not, excluding headers and current cell)
2440 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2441 for ($index=0; $index<$imax; $index++) {
2442 if (is_numeric($table[$index][$j])) {
2443 $result += $table[$index][$j];
2446 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2448 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2449 for ($index=0; $index<$jmax; $index++) {
2450 if (is_numeric($table[$i][$index])) {
2451 $result += $table[$i][$index];
2454 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2456 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2457 for ($index=0; $index<$imax; $index++) {
2458 if (is_numeric($table[$index][$j])) {
2459 $result += $table[$index][$j];
2463 $result=$result/$counter;
2464 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2466 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2467 for ($index=0; $index<$jmax; $index++) {
2468 if (is_numeric($table[$i][$index])) {
2469 $result += $table[$i][$index];
2473 $result=$result/$counter;
2474 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2476 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2477 for ($index=0; $index<$imax; $index++) {
2478 if (is_numeric($table[$index][$j])) {
2481 $result=$table[$index][$j];
2483 $result = max($result, $table[$index][$j]);
2490 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2492 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2493 for ($index=0; $index<$jmax; $index++) {
2494 if (is_numeric($table[$i][$index])) {
2497 $result=$table[$i][$index];
2499 $result = max($result, $table[$i][$index]);
2506 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2508 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2509 for ($index=0; $index<$imax; $index++) {
2510 if (is_numeric($table[$index][$j])) {
2513 $result=$table[$index][$j];
2515 $result = min($result, $table[$index][$j]);
2522 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2524 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2525 for ($index=0; $index<$jmax; $index++) {
2526 if (is_numeric($table[$i][$index])) {
2529 $result=$table[$i][$index];
2531 $result = min($result, $table[$i][$index]);
2538 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2540 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2541 for ($index=0; $index<$imax; $index++) {
2542 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2546 $result = $counter-1; // exclude self
2547 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2549 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2550 for ($index=0; $index<$jmax; $index++) {
2551 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2555 $result = $counter-1; // exclude self
2556 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2559 return $table[$i][$j];
2562 // (c-file-style: "gnu")
2566 // c-basic-offset: 4
2567 // c-hanging-comment-ender-p: nil
2568 // indent-tabs-mode: nil