1 <?php //rcs_id('$Id$');
3 Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4 Copyright 2008 Marc-Etienne Vargenau, Alcatel-Lucent
6 This file is part of PhpWiki.
8 PhpWiki is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 PhpWiki is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with PhpWiki; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 Standard functions for Wiki functionality
25 WikiURL ($pagename, $args, $get_abs_url)
27 IconForLink ($protocol_or_url)
28 PossiblyGlueIconToText($proto_or_url, $text)
30 LinkURL ($url, $linktext)
31 LinkImage ($url, $alt)
32 ImgObject ($img, $url)
34 SplitQueryArgs ($query_args)
35 LinkPhpwikiURL ($url, $text, $basepage)
36 ConvertOldMarkup ($content, $markup_type = "block")
37 MangleXmlIdentifier($str)
38 UnMangleXmlIdentifier($str)
40 class Stack { push($item), pop(), cnt(), top() }
41 class Alert { show() }
42 class WikiPageName {getParent(),isValid(),getWarnings() }
44 expand_tabs($str, $tab_width = 8)
46 NoSuchRevision ($request, $page, $version)
47 TimezoneOffset ($time, $no_colon)
48 Iso8601DateTime ($time)
49 Rfc2822DateTime ($time)
50 ParseRfc1123DateTime ($timestr)
52 ByteFormatter ($bytes = 0, $longformat = false)
55 __vsprintf ($fmt, $args)
57 file_mtime ($filename)
58 sort_file_mtime ($a, $b)
59 class fileSet {fileSet($directory, $filepattern = false),
60 getFiles($exclude='', $sortby='', $limit='') }
61 class ListRegexExpand { listMatchCallback($item, $key),
62 expandRegex ($index, &$pages) }
65 glob_match ($glob, $against, $case_sensitive = true)
66 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
67 explodePageList ($input, $perm = false)
69 can ($object, $method)
70 function_usable ($function_name)
72 better_srand ($seed = '')
75 subPageSlice ($pagename, $pos)
79 obj2hash ($obj, $exclude = false, $fields = false)
82 url_get_contents ($uri)
84 firstNWordsOfContent ($n, $content)
85 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
88 charset_convert($from, $to, $data)
90 function: LinkInterWikiLink($link, $linktext)
91 moved to: lib/interwiki.php
92 function: linkExistingWikiWord($wikiword, $linktext, $version)
93 moved to: lib/WikiTheme.php
94 function: LinkUnknownWikiWord($wikiword, $linktext)
95 moved to: lib/WikiTheme.php
96 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
97 gone see: lib/plugin/RecentChanges.php
99 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
100 else define('_PHPWIKI_STDLIB_LOADED', true);
102 define('MAX_PAGENAME_LENGTH', 100);
105 * Convert string to a valid XML identifier.
107 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
109 * We would like to have, e.g. named anchors within wiki pages
110 * names like "Table of Contents" --- clearly not a valid XML
111 * fragment identifier.
113 * This function implements a one-to-one map from {any string}
114 * to {valid XML identifiers}.
117 * converting all bytes not in [A-Za-z0-9:_-],
118 * and any leading byte not in [A-Za-z] to 'xbb.',
119 * where 'bb' is the hexadecimal representation of the
122 * As a special case, the empty string is converted to 'empty.'
127 function MangleXmlIdentifier($str) {
131 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
132 "'x' . sprintf('%02x', ord('\\0')) . '.'",
136 function UnMangleXmlIdentifier($str) {
137 if ($str == 'empty.')
139 return preg_replace('/x(\w\w)\./e',
140 "sprintf('%c', hex('\\0'))",
145 * Returns a name for the WIKI_ID cookie that should be unique on the host.
146 * But for it to be unique you must have set a unique WIKI_NAME in your
147 * configuration file.
148 * @return string The name of the WIKI_ID cookie to use for this wiki.
150 function GetCookieName() {
151 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
155 * Generates a valid URL for a given Wiki pagename.
156 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
157 * If a WikiDB_Page object function will extract the name to link to.
158 * If a WikiDB_PageRevision object function will extract the name to link to.
160 * @param boolean $get_abs_url Default value is false.
161 * @return string The absolute URL to the page passed as $pagename.
163 function WikiURL($pagename, $args = '', $get_abs_url = false) {
164 global $request, $WikiTheme;
167 if (is_object($pagename)) {
168 if (isa($pagename, 'WikiDB_Page')) {
169 $pagename = $pagename->getName();
171 elseif (isa($pagename, 'WikiDB_PageRevision')) {
172 $page = $pagename->getPage();
173 $args['version'] = $pagename->getVersion();
174 $pagename = $page->getName();
176 elseif (isa($pagename, 'WikiPageName')) {
177 $anchor = $pagename->anchor;
178 $pagename = $pagename->name;
180 $anchor = $pagename->anchor;
181 $pagename = $pagename->name;
184 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
186 $args = 'start_debug=' . $request->getArg('start_debug');
187 elseif (is_array($args))
188 $args['start_debug'] = $request->getArg('start_debug');
190 $args .= '&start_debug=' . $request->getArg('start_debug');
192 if (is_array($args)) {
194 foreach ($args as $key => $val) {
195 // avoid default args
196 if (USE_PATH_INFO and $key == 'pagename')
198 elseif ($key == 'action' and $val == 'browse')
200 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
201 $enc_args[] = urlencode($key) . '=' . urlencode($val);
203 $args = join('&', $enc_args);
206 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
207 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
208 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
210 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
211 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
212 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
215 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
217 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
227 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
228 $url .= "?pagename=" . rawurlencode($pagename);
233 $url .= "#" . MangleXmlIdentifier($anchor);
237 /** Convert relative URL to absolute URL.
239 * This converts a relative URL to one of PhpWiki's support files
240 * to an absolute one.
243 * @return string Absolute URL
245 function AbsoluteURL ($url) {
246 if (preg_match('/^https?:/', $url))
248 if ($url[0] != '/') {
249 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
250 while ($base != '/' and substr($url, 0, 3) == "../") {
251 $url = substr($url, 3);
252 $base = dirname($base);
258 return SERVER_URL . $url;
261 function DataURL ($url) {
262 if (preg_match('/^https?:/', $url))
264 $url = NormalizeWebFileName($url);
265 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
266 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
267 return AbsoluteURL($url);
271 * Generates icon in front of links.
273 * @param string $protocol_or_url URL or protocol to determine which icon to use.
275 * @return HtmlElement HtmlElement object that contains data to create img link to
276 * icon for use with url or protocol passed to the function. False if no img to be
279 function IconForLink($protocol_or_url) {
281 if (0 and $filename_suffix == false) {
282 // display apache style icon for file type instead of protocol icon
283 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
284 // - document: html, htm, text, txt, rtf, pdf, doc
285 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
286 // - audio: mp3,mp2,aiff,aif,au
287 // - multimedia: mpeg,mpg,mov,qt
289 list ($proto) = explode(':', $protocol_or_url, 2);
290 $src = $WikiTheme->getLinkIconURL($proto);
292 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
299 * Glue icon in front of or after text.
300 * Pref: 'noLinkIcons' - ignore icon if set
301 * WikiTheme: 'LinkIcons' - 'yes' at front
302 * - 'no' display no icon
303 * - 'front' display at left
304 * - 'after' display at right
306 * @param string $protocol_or_url Protocol or URL. Used to determine the
308 * @param string $text The text.
309 * @return XmlContent.
311 function PossiblyGlueIconToText($proto_or_url, $text) {
312 global $request, $WikiTheme;
313 if ($request->getPref('noLinkIcons'))
315 $icon = IconForLink($proto_or_url);
318 if ($where = $WikiTheme->getLinkIconAttr()) {
319 if ($where == 'no') return $text;
320 if ($where != 'after') $where = 'front';
324 if ($where == 'after') {
325 // span the icon only to the last word (tie them together),
326 // to let the previous words wrap on line breaks.
327 if (!is_object($text)) {
328 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
329 list (, $prefix, $last_word) = $m;
335 $text = HTML::span(array('style' => 'white-space: nowrap'),
336 $last_word, HTML::Raw(' '), $icon);
338 $text = HTML($prefix, $text);
341 // span the icon only to the first word (tie them together),
342 // to let the next words wrap on line breaks
343 if (!is_object($text)) {
344 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
345 list (, $first_word, $tail) = $m;
351 $text = HTML::span(array('style' => 'white-space: nowrap'),
354 $text = HTML($text, $tail);
359 * Determines if the url passed to function is safe, by detecting if the characters
360 * '<', '>', or '"' are present.
361 * Check against their urlencoded values also.
363 * @param string $url URL to check for unsafe characters.
364 * @return boolean True if same, false else.
366 function IsSafeURL($url) {
367 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
371 * Generates an HtmlElement object to store data for a link.
373 * @param string $url URL that the link will point to.
374 * @param string $linktext Text to be displayed as link.
375 * @return HtmlElement HtmlElement object that contains data to construct an html link.
377 function LinkURL($url, $linktext = '') {
378 // FIXME: Is this needed (or sufficient?)
379 if(! IsSafeURL($url)) {
380 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
381 _("BAD URL -- remove all of <, >, \"")));
385 $linktext = preg_replace("/mailto:/A", "", $url);
386 $args = array('href' => $url);
387 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
388 $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
389 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
391 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
398 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
399 * Disallows sizes which are too small.
400 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
402 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
404 function LinkImage($url, $alt = "") {
405 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
406 // Disallow tags in img src urls. Typical CSS attacks.
407 // FIXME: Is this needed (or sufficient?)
408 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
410 if(! IsSafeURL($url)) {
411 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
412 _("BAD URL -- remove all of <, >, \"")));
415 // support new syntax: [prefix/image.jpg size=50% border=n]
416 //if (!preg_match("/\.(".$force_img.")/i", $url))
417 if (empty($alt)) $alt = "";
418 $arr = split(' ',$url);
419 if (!empty($arr)) $url = $arr[0];
421 $link = HTML::img(array('src' => $url, 'alt' => $alt));
423 $link = HTML::img(array('src' => $url,
424 'alt' => $alt, 'title' => $alt));
426 if (count($arr) > 1) {
429 foreach ($arr as $attr) {
430 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
431 $link->setAttr('width',$m[1]);
432 $link->setAttr('height',$m[1]);
434 elseif (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
435 $link->setAttr('width',$m[1]);
436 $link->setAttr('height',$m[2]);
438 elseif (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
439 $link->setAttr('width',$m[1]);
440 elseif (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
441 $link->setAttr('height',$m[1]);
442 elseif (preg_match('/^border=(\d+)$/',$attr,$m))
443 $link->setAttr('border',$m[1]);
444 elseif (preg_match('/^align=(\w+)$/',$attr,$m))
445 $link->setAttr('align',$m[1]);
446 elseif (preg_match('/^hspace=(\d+)$/',$attr,$m))
447 $link->setAttr('hspace',$m[1]);
448 elseif (preg_match('/^vspace=(\d+)$/',$attr,$m))
449 $link->setAttr('vspace',$m[1]);
452 if(! IsSafeURL($url)) {
453 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
454 _("BAD URL -- remove all of <, >, \"")));
457 $link->setAttr('src', $url);
462 // Check width and height as spam countermeasure
463 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
464 //$width = (int) $width; // px or % or other suffix
465 //$height = (int) $height;
466 if (($width < 3 and $height < 10) or
467 ($height < 3 and $width < 20) or
468 ($height < 7 and $width < 7))
470 trigger_error(_("Invalid image size"), E_USER_WARNING);
475 // Prepare for getimagesize($url)
476 // $url only valid for external urls, otherwise local path
477 // Older php versions crash here with certain png's:
478 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
479 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
480 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
481 if (DISABLE_GETIMAGESIZE)
483 elseif (! preg_match("/\.$force_img$/i", $url))
484 ; // only valid image extensions or scripts assumed to generate images
485 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
486 ; // it's safe to assume that this will fail.
487 elseif (preg_match("/^http/",$url)) { // external url
488 $size = @getimagesize($url);
489 } else { // local file
490 if (file_exists($file = NormalizeLocalFileName($url))) { // here
491 $size = @getimagesize($file);
492 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
493 $size = @getimagesize($file);
494 $link->setAttr('src', rawurldecode($url));
495 } elseif (string_starts_with($url, getUploadDataPath())) { // there
496 $file = substr($file, strlen(getUploadDataPath()));
497 $size = @getimagesize(getUploadFilePath().rawurldecode($file));
498 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
499 } else { // elsewhere
500 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
506 if (($width < 3 and $height < 10)
507 or ($height < 3 and $width < 20)
508 or ($height < 7 and $width < 7))
510 trigger_error(_("Invalid image size"), E_USER_WARNING);
516 $link->setAttr('class', 'inlineimage');
518 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
519 * png|jpg|gif|jpeg|bmp|pl|cgi
520 * Note: Allow cgi's (pl,cgi) returning images.
522 if (!preg_match("/\.(".$force_img.")/i", $url)) {
523 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
524 // => HTML::object(array('src' => $url)) ...;
525 return ImgObject($link, $ori_url);
531 * <object> / <embed> tags instead of <img> for all non-image extensions
533 * Called by LinkImage(), not directly.
534 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
535 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
536 * $alt may be an alternate img
537 * TODO: Need to unify with WikiPluginCached::embedObject()
539 * Note that Safari 1.0 will crash with <object>, so use only <embed>
540 * http://www.alleged.org.uk/pdc/2002/svg-object.html
542 * Allowed object tags:
543 * DATA=URI (object data)
544 * CLASSID=URI (location of implementation)
545 * ARCHIVE=CDATA (archive files)
546 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
547 * WIDTH=Length (object width)
548 * HEIGHT=Length (object height)
549 * NAME=CDATA (name for form submission)
550 * USEMAP=URI (client-side image map)
551 * TYPE=ContentType (content-type of object)
552 * CODETYPE=ContentType (content-type of code)
553 * STANDBY=Text (message to show while loading)
554 * TABINDEX=NUMBER (position in tabbing order)
555 * DECLARE (do not instantiate object)
556 * The rest is added as <param name="" value="" /> tags
558 function ImgObject($img, $url) {
559 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
560 $args = split(' ', $url);
562 if (count($args) >= 1) {
563 $url = array_shift($args);
565 foreach ($args as $attr) {
566 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
567 "codetype,standby,tabindex,declare") as $param)
569 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
570 $img->setAttr($param, $m[1]);
576 // now all remaing args are added as <param> to the object
577 foreach ($args as $attr) {
578 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
579 $params[] = HTML::param(array('name' => $m[1],
584 $type = $img->getAttr('type');
586 // TODO: map extension to mime-types if type is not given and php < 4.3
587 if (function_exists('mime_content_type'))
588 $type = mime_content_type($url);
590 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
592 $object->setAttr('class', 'inlineobject');
594 foreach ($params as $param) $object->pushContent($param);
596 if (isBrowserSafari()) {
597 return HTML::embed($object->_attr, $object->_content);
599 $object->pushContent(HTML::embed($object->_attr));
606 // var in php5 deprecated
608 $this->items = array();
611 function push($item) {
612 $this->items[$this->size] = $item;
618 if ($this->size == 0) {
619 return false; // stack is empty
622 return $this->items[$this->size];
631 return $this->items[$this->size - 1];
637 // end class definition
639 function SplitQueryArgs ($query_args = '')
641 // FIXME: use the arg-seperator which might not be &
642 $split_args = split('&', $query_args);
644 while (list($key, $val) = each($split_args))
645 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
646 $args[$m[1]] = $m[2];
650 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
653 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
654 return HTML::strong(array('class' => 'rawurl'),
655 HTML::u(array('class' => 'baduri'),
656 _("BAD phpwiki: URL")));
660 $pagename = urldecode($m[1]);
663 if (empty($pagename) &&
664 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
665 // Convert old style links (to not break diff links in
667 $pagename = urldecode($m[2]);
668 $args = array("action" => $m[1]);
671 $args = SplitQueryArgs($qargs);
674 if (empty($pagename))
675 $pagename = $GLOBALS['request']->getArg('pagename');
677 if (isset($args['action']) && $args['action'] == 'browse')
678 unset($args['action']);
681 if (empty($args['action']))
683 else if (is_safe_action($args['action']))
684 $class = 'wikiaction';
686 if (empty($args['action']) || is_safe_action($args['action']))
687 $class = 'wikiaction';
689 // Don't allow administrative links on unlocked pages.
690 $dbi = $GLOBALS['request']->getDbh();
691 $page = $dbi->getPage($basepage ? $basepage : $pagename);
692 if (!$page->get('locked'))
693 return HTML::span(array('class' => 'wikiunsafe'),
694 HTML::u(_("Lock page to enable link")));
695 $class = 'wikiadmin';
699 $text = HTML::span(array('class' => 'rawurl'), $url);
701 $wikipage = new WikiPageName($pagename);
702 if (!$wikipage->isValid()) {
704 return $WikiTheme->linkBadWikiWord($wikipage, $url);
707 return HTML::a(array('href' => WikiURL($pagename, $args),
713 * A class to assist in parsing wiki pagenames.
715 * Now with subpages and anchors, parsing and passing around
716 * pagenames is more complicated. This should help.
720 /** Short name for page.
722 * This is the value of $name passed to the constructor.
723 * (For use, e.g. as a default label for links to the page.)
727 /** The full page name.
729 * This is the full name of the page (without anchor).
735 * This is the referenced anchor within the page, or the empty string.
741 * @param mixed $name Page name.
742 * WikiDB_Page, WikiDB_PageRevision, or string.
743 * This can be a relative subpage name (like '/SubPage'),
744 * or can be the empty string to refer to the $basename.
746 * @param string $anchor For links to anchors in page.
748 * @param mixed $basename Page name from which to interpret
749 * relative or other non-fully-specified page names.
751 function WikiPageName($name, $basename=false, $anchor=false) {
752 if (is_string($name)) {
753 $this->shortName = $name;
754 if (strstr($name, ':')) {
755 list($moniker, $shortName) = split (":", $name, 2);
756 $map = getInterwikiMap(); // allow overrides to custom maps
757 if (isset($map->_map[$moniker])) {
758 $url = $map->_map[$moniker];
759 if (strstr($url, '%s'))
760 $url = sprintf($url, $shortName);
764 // expand Talk or User, but not to absolute urls!
765 if (strstr($url, '//')) {
766 if ($moniker == 'Talk')
767 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
768 elseif ($moniker == 'User')
773 if (strstr($shortName, '?')) {
774 list($shortName, $dummy) = split("\?", $shortName, 2);
776 $this->shortName = $shortName;
779 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
780 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
782 $name = $this->_pagename($basename) . $name;
784 $name = $this->_normalize_bad_pagename($name);
785 $this->shortName = $name;
790 $name = $this->_pagename($name);
791 $this->shortName = $name;
794 $this->name = $this->_check($name);
795 $this->anchor = (string)$anchor;
802 function getParent() {
804 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
806 return substr($name, 0, -strlen($tail));
809 function isValid($strict = false) {
811 return !isset($this->_errors);
812 return (is_string($this->name) and $this->name != '');
815 function getWarnings() {
817 if (isset($this->_warnings))
818 $warnings = array_merge($warnings, $this->_warnings);
819 if (isset($this->_errors))
820 $warnings = array_merge($warnings, $this->_errors);
824 return sprintf(_("'%s': Bad page name: %s"),
825 $this->shortName, join(', ', $warnings));
828 function _pagename($page) {
829 if (isa($page, 'WikiDB_Page'))
830 return $page->getName();
831 elseif (isa($page, 'WikiDB_PageRevision'))
832 return $page->getPageName();
833 elseif (isa($page, 'WikiPageName'))
835 // '0' or e.g. '1984' should be allowed though
836 if (!is_string($page) and !is_integer($page)) {
837 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
838 $page, gettype($page), get_class($page)),
841 //assert(is_string($page));
845 function _normalize_bad_pagename($name) {
846 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
848 // Punt... You really shouldn't get here.
851 return $request->getArg('pagename');
853 assert($name[0] == SUBPAGE_SEPARATOR);
854 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
855 return substr($name, 1);
859 * Compress internal white-space to single space character.
861 * This leads to problems with loading a foreign charset pagename,
862 * which cannot be deleted anymore, because unknown chars are compressed.
863 * So BEFORE importing a file _check must be done !!!
865 function _check($pagename) {
866 // Compress internal white-space to single space character.
867 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
868 if ($pagename != $orig)
869 $this->_warnings[] = _("White space converted to single space");
871 // Delete any control characters.
872 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
873 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
874 if ($pagename != $orig)
875 $this->_errors[] = _("Control characters not allowed");
878 // Strip leading and trailing white-space.
879 $pagename = trim($pagename);
882 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
883 $pagename = substr($pagename, 1);
884 if ($pagename != $orig)
885 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
887 // ";" is urlencoded, so safe from php arg-delim problems
888 /*if (strstr($pagename, ';')) {
889 $this->_warnings[] = _("';' is deprecated");
890 $pagename = str_replace(';', '', $pagename);
893 // not only for SQL, also to restrict url length
894 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
895 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
896 $this->_errors[] = _("too long");
899 // disallow some chars only on file and cvs
900 if ((DATABASE_TYPE == 'cvs'
901 or DATABASE_TYPE == 'file'
902 or DATABASE_TYPE == 'flatfile')
903 and preg_match('/(:|\.\.)/', $pagename, $m))
905 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
906 $pagename = str_replace('..', '', $pagename);
907 $pagename = str_replace(':', '', $pagename);
915 * Convert old page markup to new-style markup.
917 * @param string $text Old-style wiki markup.
919 * @param string $markup_type
921 * <dt><code>"block"</code> <dd>Convert all markup.
922 * <dt><code>"inline"</code> <dd>Convert only inline markup.
923 * <dt><code>"links"</code> <dd>Convert only link markup.
926 * @return string New-style wiki markup.
928 * @bugs Footnotes don't work quite as before (esp if there are
929 * multiple references to the same footnote. But close enough,
930 * probably for now....
931 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
932 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
933 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
934 * also known to crash, even with Apache1.
936 function ConvertOldMarkup ($text, $markup_type = "block") {
942 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
943 // AnciennesR%E8glesDeFormatage crashes.
944 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
945 // also known to crash, even with Apache1.
947 // I suspect this only to crash with Apache2 and IIS.
948 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
949 and preg_match("/plugin CreateToc/", $text))
951 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
952 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
953 ._("Skipped."), E_USER_WARNING);
955 //if (!DEBUG) return $text;
960 /*****************************************************************
961 * Conversions for inline markup:
968 // escape escaped brackets
972 // change ! escapes to ~'s.
973 global $WikiNameRegexp, $request;
974 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
975 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
976 if (check_php_version(4,3,9)) {
977 $map = getInterwikiMap();
978 if ($map_regex = $map->getRegexp())
979 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
981 $bang_esc[] = $WikiNameRegexp;
982 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
985 $subs["links"] = array($orig, $repl);
987 // Temporarily URL-encode pairs of underscores in links to hide
988 // them from the re for bold markup.
989 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
990 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
993 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
996 // Convert footnote references.
997 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
998 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1000 // Convert old style emphases to HTML style emphasis.
1001 $orig[] = '/__(.*?)__/';
1002 $repl[] = '<strong>\\1</strong>';
1003 $orig[] = "/''(.*?)''/";
1004 $repl[] = '<em>\\1</em>';
1006 // Escape nestled markup.
1007 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1010 // in old markup headings only allowed at beginning of line
1014 // Convert URL-encoded pairs of underscores in links back to
1015 // real underscores after bold markup has been converted.
1016 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1017 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1019 $subs["inline"] = array($orig, $repl);
1021 /*****************************************************************
1022 * Patterns which match block markup constructs which take
1023 * special handling...
1027 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1029 $blockpats[] = '\|(?:.*\n\|)*';
1032 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1034 // Footnote definitions
1035 $blockpats[] = '\[\s*(\d+)\s*\]';
1039 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1043 $blockpats[] = '!{1,3}[^!]';
1045 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1046 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1048 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1049 . join("|", $blockpats)
1054 if ($markup_type != "block") {
1055 list ($orig, $repl) = $subs[$markup_type];
1056 return preg_replace($orig, $repl, $text);
1059 list ($orig, $repl) = $subs['inline'];
1062 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1063 // AnciennesR%E8glesDeFormatage and more
1064 // See http://www.pcre.org/pcre.txt LIMITATIONS
1065 while (preg_match($block_re, $text, $m)) {
1066 $text = substr($text, strlen($m[0]));
1067 list (,$leading_text, $block) = $m;
1070 if (strchr(" \t", $block[0])) {
1072 $prefix = "<pre>\n";
1073 $suffix = "\n</pre>\n";
1075 elseif ($block[0] == '|') {
1077 $prefix = "<?plugin OldStyleTable\n";
1080 elseif (strchr("#*;", $block[0])) {
1081 // Old-style list item
1082 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1083 list (,$ind,$bullet) = $m;
1084 $block = substr($block, strlen($m[0]));
1086 $indent = str_repeat(' ', strlen($ind));
1087 if ($bullet[0] == ';') {
1088 //$term = ltrim(substr($bullet, 1));
1089 //return $indent . $term . "\n" . $indent . ' ';
1090 $prefix = $ind . $bullet;
1093 $prefix = $indent . $bullet . ' ';
1095 elseif ($block[0] == '[') {
1096 // Footnote definition
1097 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1099 $block = substr($block, strlen($m[0]));
1100 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1102 elseif ($block[0] == '<') {
1104 // HACK: no inline markup...
1108 elseif ($block[0] == '!') {
1110 preg_match('/^!{1,3}/', $block, $m);
1112 $block = substr($block, strlen($m[0]));
1118 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1119 if ($block) $block = preg_replace($orig, $repl, $block);
1120 $out .= $leading_text;
1125 return $out . preg_replace($orig, $repl, $text);
1131 * Expand tabs in string.
1133 * Converts all tabs to (the appropriate number of) spaces.
1135 * @param string $str
1136 * @param integer $tab_width
1139 function expand_tabs($str, $tab_width = 8) {
1140 $split = split("\t", $str);
1141 $tail = array_pop($split);
1143 foreach ($split as $hunk) {
1145 $pos = strlen(strrchr($expanded, "\n")) - 1;
1146 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1148 return substr($expanded, 1) . $tail;
1152 * Split WikiWords in page names.
1154 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1155 * places like page titles. This is rumored to help search engines
1158 * @param $page string The page name.
1160 * @return string The split name.
1162 function SplitPagename ($page) {
1164 if (preg_match("/\s/", $page))
1165 return $page; // Already split --- don't split any more.
1167 // This algorithm is specialized for several languages.
1168 // (Thanks to Pierrick MEIGNEN)
1169 // Improvements for other languages welcome.
1172 // This mess splits between a lower-case letter followed by
1173 // either an upper-case or a numeral; except that it wont
1174 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1175 switch ($GLOBALS['LANG']) {
1180 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1183 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1186 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1187 // This the single-letter words 'I' and 'A' from any following
1188 // capitalized words.
1189 switch ($GLOBALS['LANG']) {
1191 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1194 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1197 // Split numerals from following letters.
1198 $RE[] = '/(\d)([[:alpha:]])/';
1199 // Split at subpage seperators. TBD in WikiTheme.php
1200 $RE[] = "/([^${sep}]+)(${sep})/";
1201 $RE[] = "/(${sep})([^${sep}]+)/";
1203 foreach ($RE as $key)
1204 $RE[$key] = pcre_fix_posix_classes($key);
1207 foreach ($RE as $regexp) {
1208 $page = preg_replace($regexp, '\\1 \\2', $page);
1213 function NoSuchRevision (&$request, $page, $version) {
1214 $html = HTML(HTML::h2(_("Revision Not Found")),
1215 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1216 $version, WikiLink($page, 'auto'))));
1217 include_once('lib/Template.php');
1218 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1224 * Get time offset for local time zone.
1226 * @param $time time_t Get offset for this time. Default: now.
1227 * @param $no_colon boolean Don't put colon between hours and minutes.
1228 * @return string Offset as a string in the format +HH:MM.
1230 function TimezoneOffset ($time = false, $no_colon = false) {
1231 if ($time === false)
1233 $secs = date('Z', $time);
1242 $colon = $no_colon ? '' : ':';
1243 $mins = intval(($secs + 30) / 60);
1244 return sprintf("%s%02d%s%02d",
1245 $sign, $mins / 60, $colon, $mins % 60);
1250 * Format time in ISO-8601 format.
1252 * @param $time time_t Time. Default: now.
1253 * @return string Date and time in ISO-8601 format.
1255 function Iso8601DateTime ($time = false) {
1256 if ($time === false)
1258 $tzoff = TimezoneOffset($time);
1259 $date = date('Y-m-d', $time);
1260 $time = date('H:i:s', $time);
1261 return $date . 'T' . $time . $tzoff;
1265 * Format time in RFC-2822 format.
1267 * @param $time time_t Time. Default: now.
1268 * @return string Date and time in RFC-2822 format.
1270 function Rfc2822DateTime ($time = false) {
1271 if ($time === false)
1273 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1277 * Format time in RFC-1123 format.
1279 * @param $time time_t Time. Default: now.
1280 * @return string Date and time in RFC-1123 format.
1282 function Rfc1123DateTime ($time = false) {
1283 if ($time === false)
1285 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1288 /** Parse date in RFC-1123 format.
1290 * According to RFC 1123 we must accept dates in the following
1293 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1294 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1295 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1297 * (Though we're only allowed to generate dates in the first format.)
1299 function ParseRfc1123DateTime ($timestr) {
1300 $timestr = trim($timestr);
1301 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1302 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1304 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1306 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1307 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1309 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1310 if ($year < 70) $year += 2000;
1311 elseif ($year < 100) $year += 1900;
1313 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1314 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1316 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1323 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1325 return false; // failed
1330 * Format time to standard 'ctime' format.
1332 * @param $time time_t Time. Default: now.
1333 * @return string Date and time.
1335 function CTime ($time = false)
1337 if ($time === false)
1339 return date("D M j H:i:s Y", $time);
1344 * Format number as kilobytes or bytes.
1345 * Short format is used for PageList
1346 * Long format is used in PageInfo
1348 * @param $bytes int. Default: 0.
1349 * @param $longformat bool. Default: false.
1350 * @return class FormattedText (XmlElement.php).
1352 function ByteFormatter ($bytes = 0, $longformat = false) {
1355 if ($bytes < 1024) {
1357 $size = fmt("%s b", $bytes);
1359 $size = fmt("%s bytes", $bytes);
1362 $kb = round($bytes / 1024, 1);
1364 $size = fmt("%s k", $kb);
1366 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1372 * Internationalized printf.
1374 * This is essentially the same as PHP's built-in printf
1375 * with the following exceptions:
1377 * <li> It passes the format string through gettext().
1378 * <li> It supports the argument reordering extensions.
1385 * __printf("Differences between versions %s and %s of %s",
1386 * $new_link, $old_link, $page_link);
1389 * Then in locale/po/de.po, one can reorder the printf arguments:
1392 * msgid "Differences between %s and %s of %s."
1393 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1396 * (Note that while PHP tries to expand $vars within double-quotes,
1397 * the values in msgstr undergo no such expansion, so the '$'s
1400 * One shouldn't use reordered arguments in the default format string.
1401 * Backslashes in the default string would be necessary to escape the
1402 * '$'s, and they'll cause all kinds of trouble....
1404 function __printf ($fmt) {
1405 $args = func_get_args();
1407 echo __vsprintf($fmt, $args);
1411 * Internationalized sprintf.
1413 * This is essentially the same as PHP's built-in printf with the
1414 * following exceptions:
1417 * <li> It passes the format string through gettext().
1418 * <li> It supports the argument reordering extensions.
1423 function __sprintf ($fmt) {
1424 $args = func_get_args();
1426 return __vsprintf($fmt, $args);
1430 * Internationalized vsprintf.
1432 * This is essentially the same as PHP's built-in printf with the
1433 * following exceptions:
1436 * <li> It passes the format string through gettext().
1437 * <li> It supports the argument reordering extensions.
1442 function __vsprintf ($fmt, $args) {
1443 $fmt = gettext($fmt);
1444 // PHP's sprintf doesn't support variable with specifiers,
1445 // like sprintf("%*s", 10, "x"); --- so we won't either.
1447 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1448 // Format string has '%2$s' style argument reordering.
1449 // PHP doesn't support this.
1450 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1451 // literal variable name substitution only to keep locale
1452 // strings uncluttered
1453 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1454 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1456 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1459 // Reorder arguments appropriately.
1460 foreach($m[1] as $argnum) {
1461 if ($argnum < 1 || $argnum > count($args))
1462 trigger_error(sprintf(_("%s: argument index out of range"),
1463 $argnum), E_USER_WARNING);
1464 $newargs[] = $args[$argnum - 1];
1469 // Not all PHP's have vsprintf, so...
1470 array_unshift($args, $fmt);
1471 return call_user_func_array('sprintf', $args);
1474 function file_mtime ($filename) {
1475 if ($stat = @stat($filename))
1481 function sort_file_mtime ($a, $b) {
1482 $ma = file_mtime($a);
1483 $mb = file_mtime($b);
1484 if (!$ma or !$mb or $ma == $mb) return 0;
1485 return ($ma > $mb) ? -1 : 1;
1490 * Build an array in $this->_fileList of files from $dirname.
1491 * Subdirectories are not traversed.
1493 * (This was a function LoadDir in lib/loadsave.php)
1494 * See also http://www.php.net/manual/en/function.readdir.php
1496 function getFiles($exclude='', $sortby='', $limit='') {
1497 $list = $this->_fileList;
1500 require_once('lib/PageList.php');
1501 switch (Pagelist::sortby($sortby, 'db')) {
1502 case 'pagename ASC': break;
1503 case 'pagename DESC':
1504 $list = array_reverse($list);
1507 usort($list,'sort_file_mtime');
1510 usort($list,'sort_file_mtime');
1511 $list = array_reverse($list);
1516 return array_splice($list, 0, $limit);
1520 function _filenameSelector($filename) {
1521 if (! $this->_pattern )
1524 if (! $this->_pcre_pattern )
1525 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1526 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1531 function fileSet($directory, $filepattern = false) {
1532 $this->_fileList = array();
1533 $this->_pattern = $filepattern;
1535 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1537 $this->_case = !isWindows();
1538 $this->_pathsep = '/';
1540 if (empty($directory)) {
1541 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1543 return; // early return
1546 @ $dir_handle = opendir($dir=$directory);
1547 if (empty($dir_handle)) {
1548 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1549 $dir), E_USER_NOTICE);
1550 return; // early return
1553 while ($filename = readdir($dir_handle)) {
1554 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1556 if ($this->_filenameSelector($filename)) {
1557 array_push($this->_fileList, "$filename");
1558 //trigger_error(sprintf(_("found file %s"), $filename),
1559 // E_USER_NOTICE); //debugging
1562 closedir($dir_handle);
1568 // expands a list containing regex's to its matching entries
1569 class ListRegexExpand {
1570 //var $match, $list, $index, $case_sensitive;
1571 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1572 $this->match = $match;
1573 $this->list = &$list;
1574 $this->case_sensitive = $case_sensitive;
1575 //$this->index = false;
1577 function listMatchCallback ($item, $key) {
1578 $quoted = str_replace('/','\/',$item);
1579 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1581 unset($this->list[$this->index]);
1582 $this->list[] = $item;
1585 function expandRegex ($index, &$pages) {
1586 $this->index = $index;
1587 array_walk($pages, array($this, 'listMatchCallback'));
1592 // Convert fileglob to regex style:
1593 // Convert some wildcards to pcre style, escape the rest
1594 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1595 // Fixed bug #994994: "/" in $glob.
1596 function glob_to_pcre ($glob) {
1597 // check simple case: no need to escape
1598 $escape = '\[](){}=!<>|:/';
1599 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1601 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1602 $glob = strtr($glob, "\\", "\xff");
1603 $glob = str_replace("/", "\\/", $glob);
1604 // first convert some unescaped expressions to pcre style: . => \.
1606 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1607 "\\1\xff\\2", $glob);
1610 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1611 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1612 if (!preg_match('/^[\?\*]/', $glob))
1614 if (!preg_match('/[\?\*]$/', $glob))
1617 // Fixes Bug 1182997
1618 // .*? handled above, now escape the rest
1619 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1620 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1622 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1624 $re = preg_replace('/\xff/', '', $re);
1628 function glob_match ($glob, $against, $case_sensitive = true) {
1629 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1633 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1634 $list = explode(',',$input);
1635 // expand wildcards from list of $allnames
1636 if (preg_match('/[\?\*]/',$input)) {
1637 // Optimizing loop invariants:
1638 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1639 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1641 if (preg_match('/[\?\*]/',$f)) {
1643 $expand = new ListRegexExpand($list,
1644 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1645 $expand->expandRegex($i, $allnames);
1652 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1653 function explodePageList($input, $include_empty=false, $sortby='pagename',
1654 $limit='', $exclude='') {
1655 include_once("lib/PageList.php");
1656 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1659 // Class introspections
1662 * Determine whether object is of a specified type.
1663 * In PHP builtin since 4.2.0 as is_a()
1664 * is_a() deprecated in PHP 5, in favor of instanceof operator
1666 * @param $object object An object.
1667 * @param $class string Class name.
1668 * @return bool True iff $object is a $class
1669 * or a sub-type of $class.
1671 function isa ($object, $class) {
1672 //if (check_php_version(5))
1673 // return $object instanceof $class;
1674 if (check_php_version(4,2) and !check_php_version(5))
1675 return is_a($object, $class);
1677 $lclass = check_php_version(5) ? $class : strtolower($class);
1678 return is_object($object)
1679 && ( strtolower(get_class($object)) == strtolower($class)
1680 || is_subclass_of($object, $lclass) );
1683 /** Determine whether (possible) object has method.
1685 * @param $object mixed Object
1686 * @param $method string Method name
1687 * @return bool True iff $object is an object with has method $method.
1689 function can ($object, $method) {
1690 return is_object($object) && method_exists($object, strtolower($method));
1693 /** Determine whether a function is okay to use.
1695 * Some providers (e.g. Lycos) disable some of PHP functions for
1696 * "security reasons." This makes those functions, of course,
1697 * unusable, despite the fact the function_exists() says they
1700 * This function test to see if a function exists and is not
1701 * disallowed by PHP's disable_functions config setting.
1703 * @param string $function_name Function name
1704 * @return bool True iff function can be used.
1706 function function_usable($function_name) {
1708 if (!is_array($disabled)) {
1709 $disabled = array();
1710 // Use get_cfg_var since ini_get() is one of the disabled functions
1711 // (on Lycos, at least.)
1712 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1713 foreach ($split as $f)
1714 $disabled[strtolower($f)] = true;
1717 return ( function_exists($function_name)
1718 and ! isset($disabled[strtolower($function_name)])
1725 * This is used for generating ETags.
1727 function wikihash ($x) {
1728 if (is_scalar($x)) {
1731 elseif (is_array($x)) {
1733 return md5(serialize($x));
1735 elseif (is_object($x)) {
1738 trigger_error("Can't hash $x", E_USER_ERROR);
1743 * Seed the random number generator.
1745 * better_srand() ensures the randomizer is seeded only once.
1747 * How random do you want it? See:
1748 * http://www.php.net/manual/en/function.srand.php
1749 * http://www.php.net/manual/en/function.mt-srand.php
1751 function better_srand($seed = '') {
1752 static $wascalled = FALSE;
1754 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1755 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1757 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1761 function rand_ascii($length = 1) {
1764 for ($i = 1; $i <= $length; $i++) {
1765 // return only typeable 7 bit ascii, avoid quotes
1766 if (function_exists('mt_rand'))
1767 $s .= chr(mt_rand(40, 126));
1769 // the usually bad glibc srand()
1770 $s .= chr(rand(40, 126));
1775 /* by Dan Frankowski.
1777 function rand_ascii_readable ($length = 6) {
1778 // Pick a few random letters or numbers
1781 // Don't use 1lI0O, because they're hard to read
1782 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1783 $letter_len = strlen($letters);
1784 for ($i=0; $i < $length; $i++) {
1785 if (function_exists('mt_rand'))
1786 $word .= $letters[mt_rand(0, $letter_len-1)];
1788 $word .= $letters[rand(0, $letter_len-1)];
1794 * Recursively count all non-empty elements
1795 * in array of any dimension or mixed - i.e.
1796 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1797 * See http://www.php.net/manual/en/function.count.php
1799 function count_all($arg) {
1800 // skip if argument is empty
1802 //print_r($arg); //debugging
1804 // not an array, return 1 (base case)
1807 // else call recursively for all elements $arg
1808 foreach($arg as $key => $val)
1809 $count += count_all($val);
1814 function isSubPage($pagename) {
1815 return (strstr($pagename, SUBPAGE_SEPARATOR));
1818 function subPageSlice($pagename, $pos) {
1819 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1820 $pages = array_slice($pages,$pos,1);
1827 * Class for "popping up" and alert box. (Except that right now, it doesn't
1831 * This is a hackish and needs to be refactored. However it would be nice to
1832 * unify all the different methods we use for showing Alerts and Dialogs.
1833 * (E.g. "Page deleted", login form, ...)
1838 * @param object $request
1839 * @param mixed $head Header ("title") for alert box.
1840 * @param mixed $body The text in the alert box.
1841 * @param hash $buttons An array mapping button labels to URLs.
1842 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1844 function Alert($head, $body, $buttons=false) {
1845 if ($buttons === false)
1848 if (is_array($body)) {
1850 foreach ($body as $li) {
1851 $html->pushContent(HTML::li($li));
1855 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1856 $this->_buttons = $buttons;
1860 * Show the alert box.
1865 $tokens = $this->_tokens;
1866 $tokens['BUTTONS'] = $this->_getButtons();
1868 $request->discardOutput();
1869 $tmpl = new Template('dialog', $request, $tokens);
1875 function _getButtons() {
1878 $buttons = $this->_buttons;
1880 $buttons = array(_("Okay") => $request->getURLtoSelf());
1883 foreach ($buttons as $label => $url)
1884 print "$label $url\n";
1885 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1886 return new XmlContent($out);
1891 // 1.3.9-p1 => 1030.091
1892 // 1.3.10pre => 1030.099
1893 // 1.3.11pre-20041120 => 1030.1120041120
1894 // 1.3.12-rc1 => 1030.119
1895 function phpwiki_version() {
1896 static $PHPWIKI_VERSION;
1897 if (!isset($PHPWIKI_VERSION)) {
1898 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1899 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1900 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1901 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1902 $PHPWIKI_VERSION -= 0.01;
1904 return $PHPWIKI_VERSION;
1907 function phpwiki_gzhandler($ob) {
1908 if (function_exists('gzencode'))
1909 $ob = gzencode($ob);
1910 $GLOBALS['request']->_ob_get_length = strlen($ob);
1911 if (!headers_sent()) {
1912 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1917 function isWikiWord($word) {
1918 global $WikiNameRegexp;
1919 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1920 return preg_match("/^$WikiNameRegexp\$/",$word);
1923 // needed to store serialized objects-values only (perm, pref)
1924 function obj2hash ($obj, $exclude = false, $fields = false) {
1926 if (! $fields ) $fields = get_object_vars($obj);
1927 foreach ($fields as $key => $val) {
1928 if (is_array($exclude)) {
1929 if (in_array($key, $exclude)) continue;
1937 * isUtf8String($string) - cheap utf-8 detection
1939 * segfaults for strings longer than 10kb!
1940 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1941 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1943 function isUtf8String( $s ) {
1944 $ptrASCII = '[\x00-\x7F]';
1945 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1946 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1947 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1948 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1949 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1950 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1954 * Check for UTF-8 URLs; Internet Explorer produces these if you
1955 * type non-ASCII chars in the URL bar or follow unescaped links.
1956 * Requires urldecoded pagename.
1957 * Fixes sf.net bug #953949
1959 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1961 function fixTitleEncoding( $s ) {
1966 if (empty($s)) return $s;
1968 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1970 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1971 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1973 $isutf = ($ishigh ? isUtf8String($s) : true);
1974 $locharset = strtolower($charset);
1976 if( $locharset != "utf-8" and $ishigh and $isutf )
1977 $s = charset_convert('UTF-8', $locharset, $s);
1978 if ($locharset == "utf-8" and $ishigh and !$isutf )
1979 return utf8_encode( $s );
1981 // Other languages can safely leave this function, or replace
1982 // it with one to detect and convert another legacy encoding.
1987 * MySQL fulltext index doesn't grok utf-8, so we
1988 * need to fold cases and convert to hex.
1989 * src: languages/Language.php:stripForSearch() from mediawiki
1992 function stripForSearch( $string ) {
1993 global $wikiLowerChars;
1994 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1995 return preg_replace(
1996 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1997 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2003 * Workaround for allow_url_fopen, to get the content of an external URI.
2004 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2005 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2007 function url_get_contents( $uri ) {
2008 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2009 return @file_get_contents($uri);
2011 require_once("lib/HttpClient.php");
2012 $bits = parse_url($uri);
2013 $host = $bits['host'];
2014 $port = isset($bits['port']) ? $bits['port'] : 80;
2015 $path = isset($bits['path']) ? $bits['path'] : '/';
2016 if (isset($bits['query'])) {
2017 $path .= '?'.$bits['query'];
2019 $client = new HttpClient($host, $port);
2020 $client->use_gzip = false;
2021 if (!$client->get($path)) {
2024 return $client->getContent();
2030 * Generate consecutively named strings:
2031 * Name, Name2, Name3, ...
2033 function GenerateId($name) {
2034 static $ids = array();
2035 if (empty($ids[$name])) {
2040 return $name . $ids[$name];
2044 // from IncludePage. To be of general use.
2045 // content: string or array of strings
2046 function firstNWordsOfContent( $n, $content ) {
2047 if ($content and $n > 0) {
2048 if (is_array($content)) {
2049 // fixme: return a list of lines then?
2050 //$content = join("\n", $content);
2051 //$return_array = true;
2053 foreach ($content as $line) {
2054 $words = explode(' ', $line);
2055 if ($wordcount + count($words) > $n) {
2056 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2057 . sprintf(_("... (first %s words)"), $n);
2060 $wordcount += count($words);
2066 // fixme: use better whitespace/word seperators
2067 $words = explode(' ', $content);
2068 if (count($words) > $n) {
2069 return join(' ', array_slice($words, 0, $n))
2070 . sprintf(_("... (first %s words)"), $n);
2080 // moved from lib/plugin/IncludePage.php
2081 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2082 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2084 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2085 . " \\s*$\\n?" // possible blank lines
2086 . " ( (?: ^.*\\n? )*? )" // some lines
2087 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2088 implode("\n", $content),
2090 // Strip trailing blanks lines and ---- <hr>s
2091 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2093 $text = $match[1] . $section ."\n". $text;
2094 return explode("\n", $text);
2097 $mesg = $page ." ". $section;
2100 return array(sprintf(_("<%s: no such section>"), $mesg));
2103 // Extract the first $sections sections of the page
2104 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2106 $mycontent = $content;
2109 while ($sections > 0) {
2111 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2112 . " \\s*$\\n?" // possible blank lines
2113 . " ( (?: ^.*\\n? )*? )" // some lines
2114 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2115 implode("\n", $mycontent),
2117 $section = $match[2];
2118 // Strip trailing blanks lines and ---- <hr>s
2119 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2121 $text = $match[1] . $section ."\n". $text;
2124 $mycontent = explode("\n", $match[4]);
2126 if ($sections === 0) {
2127 return explode("\n", $result);
2133 // use this faster version: only load ExternalReferrer if we came from an external referrer
2134 function isExternalReferrer(&$request) {
2135 if ($referrer = $request->get('HTTP_REFERER')) {
2136 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2137 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2138 require_once("lib/ExternalReferrer.php");
2139 $se = new SearchEngines();
2140 return $se->parseSearchQuery($referrer);
2142 //if (DEBUG) return array('query' => 'wiki');
2147 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2149 function loadPhpExtension($extension) {
2150 if (!extension_loaded($extension)) {
2151 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2152 $soname = ($isWindows ? 'php_' : '')
2154 . ($isWindows ? '.dll' : '.so');
2158 return extension_loaded($extension);
2161 function charset_convert($from, $to, $data) {
2163 //$wikicharset = strtolower($CHARSET);
2164 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2165 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2166 return utf8_decode($data);
2167 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2168 return utf8_encode($data);
2170 if (loadPhpExtension("iconv")) {
2171 $tmpdata = iconv($from, $to, $data);
2173 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2177 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2182 function string_starts_with($string, $prefix) {
2183 return (substr($string, 0, strlen($prefix)) == $prefix);
2185 function string_ends_with($string, $suffix) {
2186 return (substr($string, -strlen($suffix)) == $suffix);
2188 function array_remove($arr,$value) {
2189 return array_values(array_diff($arr,array($value)));
2193 * Ensure that the script will have another $secs time left.
2194 * Works only if safe_mode is off.
2195 * For example not to timeout on waiting socket connections.
2196 * Use the socket timeout as arg.
2198 function longer_timeout($secs = 30) {
2199 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2200 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2201 if ($timeleft < $secs)
2202 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2205 function printSimpleTrace($bt) {
2207 echo "\nTraceback:\n";
2208 if (function_exists('debug_print_backtrace')) { // >= 5
2209 debug_print_backtrace();
2211 foreach ($bt as $i => $elem) {
2212 if (!array_key_exists('file', $elem)) {
2215 //echo join(" ",array_values($elem)),"\n";
2216 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2222 * Return the used process memory, in bytes.
2223 * Enable the section which will work for you. They are very slow.
2224 * Special quirks for Windows: Requires cygwin.
2226 function getMemoryUsage() {
2227 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2228 if (function_exists('memory_get_usage') and memory_get_usage()) {
2229 return memory_get_usage();
2230 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2231 $mem = $u['ru_maxrss'];
2232 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2233 // what we want is the process memory only: apache or php (if CGI)
2236 // win32_ps_stat_proc, win32_ps_stat_mem
2237 if (function_exists('win32_ps_list_procs')) {
2238 $info = win32_ps_stat_proc($pid);
2239 $memstr = $info['mem']['working_set_size'];
2241 // This works only if it's a cygwin process (apache or php).
2242 // Requires a newer cygwin
2243 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2245 // if it's native windows use something like this:
2246 // (requires pslist from sysinternals.com, grep, sed and perl)
2247 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2249 return (integer) trim($memstr);
2252 //%MEM: Percentage of total memory in use by this process
2253 //VSZ: Total virtual memory size, in 1K blocks.
2254 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2255 //CPU time used by process since it started.
2256 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2257 $memstr = exec("ps -orss -p $pid|sed 1d");
2258 return (integer) trim($memstr);
2263 * @param var $needle
2264 * @param array $haystack one-dimensional numeric array only, no hash
2266 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2267 It will return false if not found or the index where it was found.
2268 From dennis.decoene@moveit.be http://www.php.net/array_search
2270 function binary_search($needle, $haystack) {
2271 $high = count($haystack);
2274 while (($high - $low) > 1) {
2275 $probe = floor(($high + $low) / 2);
2276 if ($haystack[$probe] < $needle) {
2278 } elseif ($haystack[$probe] == $needle) {
2279 $high = $low = $probe;
2285 if ($high == count($haystack) || $haystack[$high] != $needle) {
2292 function is_localhost($url = false) {
2294 global $HTTP_SERVER_VARS;
2295 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2300 * Take a string and quote it sufficiently to be passed as a Javascript
2301 * string between ''s
2303 function javascript_quote_string($s) {
2304 return str_replace("'", "\'", $s);
2307 function isSerialized($s) {
2308 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2312 * Take a string and return an array of pairs (attribute name, attribute value)
2314 * We allow attributes with or without double quotes (")
2315 * Attribute-value pairs may be separated by space or comma
2316 * border=1, cellpadding="5"
2317 * border=1 cellpadding="5"
2318 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2319 * What will not work is style with comma inside, e. g.
2320 / style="font-family: Verdana, Arial, Helvetica, sans-serif"
2322 function parse_attributes($line) {
2323 if (empty($line)) return array();
2324 $line = strtolower($line);
2325 $line = str_replace(",", "", $line);
2326 $attr_chunks = preg_split("/\s* \s*/", $line);
2328 foreach ($attr_chunks as $attr_pair) {
2329 if (empty($attr_pair)) continue;
2330 $key_val = preg_split("/\s*=\s*/", $attr_pair);
2331 if (!empty($key_val[1]))
2332 $options[trim($key_val[0])] = trim(str_replace("\"", "", $key_val[1]));
2338 * Returns true if the filename ends with an image suffix.
2339 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2341 function is_image ($filename) {
2343 if (defined('INLINE_IMAGES')) {
2344 $inline_images = INLINE_IMAGES;
2346 $inline_images = "png|jpg|jpeg|gif";
2349 foreach (explode("|", $inline_images) as $suffix) {
2350 if (string_ends_with($filename, "." . $suffix)) {
2358 * Compute cell in spreadsheet table
2359 * $table: two-dimensional table
2360 * $i and $j: indexes of cell to compute
2361 * $imax and $jmax: table dimensions
2363 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2365 // What is implemented:
2366 // @@=SUM(R)@@ : sum of cells in current row
2367 // @@=SUM(C)@@ : sum of cells in current column
2368 // @@=AVERAGE(R)@@ : average of cells in current row
2369 // @@=AVERAGE(C)@@ : average of cells in current column
2370 // @@=MAX(R)@@ : maximum value of cells in current row
2371 // @@=MAX(C)@@ : maximum value of cells in current column
2372 // @@=MIN(R)@@ : minimum value of cells in current row
2373 // @@=MIN(C)@@ : minimum value of cells in current column
2374 // @@=COUNT(R)@@ : number of cells in current row
2375 // (numeric or not, excluding headers and current cell)
2376 // @@=COUNT(C)@@ : number of cells in current column
2377 // (numeric or not, excluding headers and current cell)
2383 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2384 for ($index=0; $index<$imax; $index++) {
2385 if (is_numeric($table[$index][$j])) {
2386 $result += $table[$index][$j];
2389 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2391 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2392 for ($index=0; $index<$jmax; $index++) {
2393 if (is_numeric($table[$i][$index])) {
2394 $result += $table[$i][$index];
2397 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2399 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2400 for ($index=0; $index<$imax; $index++) {
2401 if (is_numeric($table[$index][$j])) {
2402 $result += $table[$index][$j];
2406 $result=$result/$counter;
2407 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2409 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2410 for ($index=0; $index<$jmax; $index++) {
2411 if (is_numeric($table[$i][$index])) {
2412 $result += $table[$i][$index];
2416 $result=$result/$counter;
2417 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2419 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2420 for ($index=0; $index<$imax; $index++) {
2421 if (is_numeric($table[$index][$j])) {
2424 $result=$table[$index][$j];
2426 $result = max($result, $table[$index][$j]);
2433 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2435 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2436 for ($index=0; $index<$jmax; $index++) {
2437 if (is_numeric($table[$i][$index])) {
2440 $result=$table[$i][$index];
2442 $result = max($result, $table[$i][$index]);
2449 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2451 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2452 for ($index=0; $index<$imax; $index++) {
2453 if (is_numeric($table[$index][$j])) {
2456 $result=$table[$index][$j];
2458 $result = min($result, $table[$index][$j]);
2465 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2467 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2468 for ($index=0; $index<$jmax; $index++) {
2469 if (is_numeric($table[$i][$index])) {
2472 $result=$table[$i][$index];
2474 $result = min($result, $table[$i][$index]);
2481 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2483 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2484 for ($index=0; $index<$imax; $index++) {
2485 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2489 $result = $counter-1; // exclude self
2490 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2492 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2493 for ($index=0; $index<$jmax; $index++) {
2494 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2498 $result = $counter-1; // exclude self
2499 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2502 return $table[$i][$j];
2505 // (c-file-style: "gnu")
2509 // c-basic-offset: 4
2510 // c-hanging-comment-ender-p: nil
2511 // indent-tabs-mode: nil