1 <?php //rcs_id('$Id$');
3 Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4 Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
6 This file is part of PhpWiki.
8 PhpWiki is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 PhpWiki is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
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) and (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 at underscore
1211 $RE[] = '/(_)([[:alpha:]])/';
1212 $RE[] = '/([[:alpha:]])(_)/';
1213 // Split numerals from following letters.
1214 $RE[] = '/(\d)([[:alpha:]])/';
1215 // Split at subpage seperators. TBD in WikiTheme.php
1216 $RE[] = "/([^${sep}]+)(${sep})/";
1217 $RE[] = "/(${sep})([^${sep}]+)/";
1219 foreach ($RE as $key)
1220 $RE[$key] = pcre_fix_posix_classes($key);
1223 foreach ($RE as $regexp) {
1224 $page = preg_replace($regexp, '\\1 \\2', $page);
1229 function NoSuchRevision (&$request, $page, $version) {
1230 $html = HTML(HTML::h2(_("Revision Not Found")),
1231 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1232 $version, WikiLink($page, 'auto'))));
1233 include_once('lib/Template.php');
1234 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1240 * Get time offset for local time zone.
1242 * @param $time time_t Get offset for this time. Default: now.
1243 * @param $no_colon boolean Don't put colon between hours and minutes.
1244 * @return string Offset as a string in the format +HH:MM.
1246 function TimezoneOffset ($time = false, $no_colon = false) {
1247 if ($time === false)
1249 $secs = date('Z', $time);
1258 $colon = $no_colon ? '' : ':';
1259 $mins = intval(($secs + 30) / 60);
1260 return sprintf("%s%02d%s%02d",
1261 $sign, $mins / 60, $colon, $mins % 60);
1266 * Format time in ISO-8601 format.
1268 * @param $time time_t Time. Default: now.
1269 * @return string Date and time in ISO-8601 format.
1271 function Iso8601DateTime ($time = false) {
1272 if ($time === false)
1274 $tzoff = TimezoneOffset($time);
1275 $date = date('Y-m-d', $time);
1276 $time = date('H:i:s', $time);
1277 return $date . 'T' . $time . $tzoff;
1281 * Format time in RFC-2822 format.
1283 * @param $time time_t Time. Default: now.
1284 * @return string Date and time in RFC-2822 format.
1286 function Rfc2822DateTime ($time = false) {
1287 if ($time === false)
1289 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1293 * Format time in RFC-1123 format.
1295 * @param $time time_t Time. Default: now.
1296 * @return string Date and time in RFC-1123 format.
1298 function Rfc1123DateTime ($time = false) {
1299 if ($time === false)
1301 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1304 /** Parse date in RFC-1123 format.
1306 * According to RFC 1123 we must accept dates in the following
1309 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1310 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1311 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1313 * (Though we're only allowed to generate dates in the first format.)
1315 function ParseRfc1123DateTime ($timestr) {
1316 $timestr = trim($timestr);
1317 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1318 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1320 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1322 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1323 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1325 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1326 if ($year < 70) $year += 2000;
1327 elseif ($year < 100) $year += 1900;
1329 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1330 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1332 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1339 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1341 return false; // failed
1346 * Format time to standard 'ctime' format.
1348 * @param $time time_t Time. Default: now.
1349 * @return string Date and time.
1351 function CTime ($time = false)
1353 if ($time === false)
1355 return date("D M j H:i:s Y", $time);
1360 * Format number as kilobytes or bytes.
1361 * Short format is used for PageList
1362 * Long format is used in PageInfo
1364 * @param $bytes int. Default: 0.
1365 * @param $longformat bool. Default: false.
1366 * @return class FormattedText (XmlElement.php).
1368 function ByteFormatter ($bytes = 0, $longformat = false) {
1371 if ($bytes < 1024) {
1373 $size = fmt("%s b", $bytes);
1375 $size = fmt("%s bytes", $bytes);
1378 $kb = round($bytes / 1024, 1);
1380 $size = fmt("%s k", $kb);
1382 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1388 * Internationalized printf.
1390 * This is essentially the same as PHP's built-in printf
1391 * with the following exceptions:
1393 * <li> It passes the format string through gettext().
1394 * <li> It supports the argument reordering extensions.
1401 * __printf("Differences between versions %s and %s of %s",
1402 * $new_link, $old_link, $page_link);
1405 * Then in locale/po/de.po, one can reorder the printf arguments:
1408 * msgid "Differences between %s and %s of %s."
1409 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1412 * (Note that while PHP tries to expand $vars within double-quotes,
1413 * the values in msgstr undergo no such expansion, so the '$'s
1416 * One shouldn't use reordered arguments in the default format string.
1417 * Backslashes in the default string would be necessary to escape the
1418 * '$'s, and they'll cause all kinds of trouble....
1420 function __printf ($fmt) {
1421 $args = func_get_args();
1423 echo __vsprintf($fmt, $args);
1427 * Internationalized sprintf.
1429 * This is essentially the same as PHP's built-in printf with the
1430 * following exceptions:
1433 * <li> It passes the format string through gettext().
1434 * <li> It supports the argument reordering extensions.
1439 function __sprintf ($fmt) {
1440 $args = func_get_args();
1442 return __vsprintf($fmt, $args);
1446 * Internationalized vsprintf.
1448 * This is essentially the same as PHP's built-in printf with the
1449 * following exceptions:
1452 * <li> It passes the format string through gettext().
1453 * <li> It supports the argument reordering extensions.
1458 function __vsprintf ($fmt, $args) {
1459 $fmt = gettext($fmt);
1460 // PHP's sprintf doesn't support variable with specifiers,
1461 // like sprintf("%*s", 10, "x"); --- so we won't either.
1463 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1464 // Format string has '%2$s' style argument reordering.
1465 // PHP doesn't support this.
1466 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1467 // literal variable name substitution only to keep locale
1468 // strings uncluttered
1469 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1470 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1472 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1475 // Reorder arguments appropriately.
1476 foreach($m[1] as $argnum) {
1477 if ($argnum < 1 || $argnum > count($args))
1478 trigger_error(sprintf(_("%s: argument index out of range"),
1479 $argnum), E_USER_WARNING);
1480 $newargs[] = $args[$argnum - 1];
1485 // Not all PHP's have vsprintf, so...
1486 array_unshift($args, $fmt);
1487 return call_user_func_array('sprintf', $args);
1490 function file_mtime ($filename) {
1491 if ($stat = @stat($filename))
1497 function sort_file_mtime ($a, $b) {
1498 $ma = file_mtime($a);
1499 $mb = file_mtime($b);
1500 if (!$ma or !$mb or $ma == $mb) return 0;
1501 return ($ma > $mb) ? -1 : 1;
1506 * Build an array in $this->_fileList of files from $dirname.
1507 * Subdirectories are not traversed.
1509 * (This was a function LoadDir in lib/loadsave.php)
1510 * See also http://www.php.net/manual/en/function.readdir.php
1512 function getFiles($exclude='', $sortby='', $limit='') {
1513 $list = $this->_fileList;
1516 require_once('lib/PageList.php');
1517 switch (Pagelist::sortby($sortby, 'db')) {
1518 case 'pagename ASC': break;
1519 case 'pagename DESC':
1520 $list = array_reverse($list);
1523 usort($list,'sort_file_mtime');
1526 usort($list,'sort_file_mtime');
1527 $list = array_reverse($list);
1532 return array_splice($list, 0, $limit);
1536 function _filenameSelector($filename) {
1537 if (! $this->_pattern )
1540 if (! $this->_pcre_pattern )
1541 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1542 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1547 function fileSet($directory, $filepattern = false) {
1548 $this->_fileList = array();
1549 $this->_pattern = $filepattern;
1551 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1553 $this->_case = !isWindows();
1554 $this->_pathsep = '/';
1556 if (empty($directory)) {
1557 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1559 return; // early return
1562 @ $dir_handle = opendir($dir=$directory);
1563 if (empty($dir_handle)) {
1564 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1565 $dir), E_USER_NOTICE);
1566 return; // early return
1569 while ($filename = readdir($dir_handle)) {
1570 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1572 if ($this->_filenameSelector($filename)) {
1573 array_push($this->_fileList, "$filename");
1574 //trigger_error(sprintf(_("found file %s"), $filename),
1575 // E_USER_NOTICE); //debugging
1578 closedir($dir_handle);
1584 // expands a list containing regex's to its matching entries
1585 class ListRegexExpand {
1586 //var $match, $list, $index, $case_sensitive;
1587 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1588 $this->match = $match;
1589 $this->list = &$list;
1590 $this->case_sensitive = $case_sensitive;
1591 //$this->index = false;
1593 function listMatchCallback ($item, $key) {
1594 $quoted = str_replace('/','\/',$item);
1595 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1597 unset($this->list[$this->index]);
1598 $this->list[] = $item;
1601 function expandRegex ($index, &$pages) {
1602 $this->index = $index;
1603 array_walk($pages, array($this, 'listMatchCallback'));
1608 // Convert fileglob to regex style:
1609 // Convert some wildcards to pcre style, escape the rest
1610 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1611 // Fixed bug #994994: "/" in $glob.
1612 function glob_to_pcre ($glob) {
1613 // check simple case: no need to escape
1614 $escape = '\[](){}=!<>|:/';
1615 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1617 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1618 $glob = strtr($glob, "\\", "\xff");
1619 $glob = str_replace("/", "\\/", $glob);
1620 // first convert some unescaped expressions to pcre style: . => \.
1622 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1623 "\\1\xff\\2", $glob);
1626 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1627 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1628 if (!preg_match('/^[\?\*]/', $glob))
1630 if (!preg_match('/[\?\*]$/', $glob))
1633 // Fixes Bug 1182997
1634 // .*? handled above, now escape the rest
1635 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1636 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1638 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1640 $re = preg_replace('/\xff/', '', $re);
1644 function glob_match ($glob, $against, $case_sensitive = true) {
1645 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1649 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1650 $list = explode(',',$input);
1651 // expand wildcards from list of $allnames
1652 if (preg_match('/[\?\*]/',$input)) {
1653 // Optimizing loop invariants:
1654 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1655 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1657 if (preg_match('/[\?\*]/',$f)) {
1659 $expand = new ListRegexExpand($list,
1660 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1661 $expand->expandRegex($i, $allnames);
1668 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1669 function explodePageList($input, $include_empty=false, $sortby='pagename',
1670 $limit='', $exclude='') {
1671 include_once("lib/PageList.php");
1672 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1675 // Class introspections
1678 * Determine whether object is of a specified type.
1679 * In PHP builtin since 4.2.0 as is_a()
1680 * is_a() deprecated in PHP 5, in favor of instanceof operator
1682 * @param $object object An object.
1683 * @param $class string Class name.
1684 * @return bool True iff $object is a $class
1685 * or a sub-type of $class.
1687 function isa ($object, $class) {
1688 //if (check_php_version(5))
1689 // return $object instanceof $class;
1690 if (check_php_version(4,2) and !check_php_version(5))
1691 return is_a($object, $class);
1693 $lclass = check_php_version(5) ? $class : strtolower($class);
1694 return is_object($object)
1695 && ( strtolower(get_class($object)) == strtolower($class)
1696 || is_subclass_of($object, $lclass) );
1699 /** Determine whether (possible) object has method.
1701 * @param $object mixed Object
1702 * @param $method string Method name
1703 * @return bool True iff $object is an object with has method $method.
1705 function can ($object, $method) {
1706 return is_object($object) && method_exists($object, strtolower($method));
1709 /** Determine whether a function is okay to use.
1711 * Some providers (e.g. Lycos) disable some of PHP functions for
1712 * "security reasons." This makes those functions, of course,
1713 * unusable, despite the fact the function_exists() says they
1716 * This function test to see if a function exists and is not
1717 * disallowed by PHP's disable_functions config setting.
1719 * @param string $function_name Function name
1720 * @return bool True iff function can be used.
1722 function function_usable($function_name) {
1724 if (!is_array($disabled)) {
1725 $disabled = array();
1726 // Use get_cfg_var since ini_get() is one of the disabled functions
1727 // (on Lycos, at least.)
1728 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1729 foreach ($split as $f)
1730 $disabled[strtolower($f)] = true;
1733 return ( function_exists($function_name)
1734 and ! isset($disabled[strtolower($function_name)])
1741 * This is used for generating ETags.
1743 function wikihash ($x) {
1744 if (is_scalar($x)) {
1747 elseif (is_array($x)) {
1749 return md5(serialize($x));
1751 elseif (is_object($x)) {
1754 trigger_error("Can't hash $x", E_USER_ERROR);
1759 * Seed the random number generator.
1761 * better_srand() ensures the randomizer is seeded only once.
1763 * How random do you want it? See:
1764 * http://www.php.net/manual/en/function.srand.php
1765 * http://www.php.net/manual/en/function.mt-srand.php
1767 function better_srand($seed = '') {
1768 static $wascalled = FALSE;
1770 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1771 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1773 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1777 function rand_ascii($length = 1) {
1780 for ($i = 1; $i <= $length; $i++) {
1781 // return only typeable 7 bit ascii, avoid quotes
1782 if (function_exists('mt_rand'))
1783 $s .= chr(mt_rand(40, 126));
1785 // the usually bad glibc srand()
1786 $s .= chr(rand(40, 126));
1791 /* by Dan Frankowski.
1793 function rand_ascii_readable ($length = 6) {
1794 // Pick a few random letters or numbers
1797 // Don't use 1lI0O, because they're hard to read
1798 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1799 $letter_len = strlen($letters);
1800 for ($i=0; $i < $length; $i++) {
1801 if (function_exists('mt_rand'))
1802 $word .= $letters[mt_rand(0, $letter_len-1)];
1804 $word .= $letters[rand(0, $letter_len-1)];
1810 * Recursively count all non-empty elements
1811 * in array of any dimension or mixed - i.e.
1812 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1813 * See http://www.php.net/manual/en/function.count.php
1815 function count_all($arg) {
1816 // skip if argument is empty
1818 //print_r($arg); //debugging
1820 // not an array, return 1 (base case)
1823 // else call recursively for all elements $arg
1824 foreach($arg as $key => $val)
1825 $count += count_all($val);
1830 function isSubPage($pagename) {
1831 return (strstr($pagename, SUBPAGE_SEPARATOR));
1834 function subPageSlice($pagename, $pos) {
1835 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1836 $pages = array_slice($pages,$pos,1);
1843 * Class for "popping up" and alert box. (Except that right now, it doesn't
1847 * This is a hackish and needs to be refactored. However it would be nice to
1848 * unify all the different methods we use for showing Alerts and Dialogs.
1849 * (E.g. "Page deleted", login form, ...)
1854 * @param object $request
1855 * @param mixed $head Header ("title") for alert box.
1856 * @param mixed $body The text in the alert box.
1857 * @param hash $buttons An array mapping button labels to URLs.
1858 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1860 function Alert($head, $body, $buttons=false) {
1861 if ($buttons === false)
1864 if (is_array($body)) {
1866 foreach ($body as $li) {
1867 $html->pushContent(HTML::li($li));
1871 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1872 $this->_buttons = $buttons;
1876 * Show the alert box.
1881 $tokens = $this->_tokens;
1882 $tokens['BUTTONS'] = $this->_getButtons();
1884 $request->discardOutput();
1885 $tmpl = new Template('dialog', $request, $tokens);
1891 function _getButtons() {
1894 $buttons = $this->_buttons;
1896 $buttons = array(_("Okay") => $request->getURLtoSelf());
1899 foreach ($buttons as $label => $url)
1900 print "$label $url\n";
1901 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1902 return new XmlContent($out);
1907 // 1.3.9-p1 => 1030.091
1908 // 1.3.10pre => 1030.099
1909 // 1.3.11pre-20041120 => 1030.1120041120
1910 // 1.3.12-rc1 => 1030.119
1911 function phpwiki_version() {
1912 static $PHPWIKI_VERSION;
1913 if (!isset($PHPWIKI_VERSION)) {
1914 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1915 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1916 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1917 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1918 $PHPWIKI_VERSION -= 0.01;
1920 return $PHPWIKI_VERSION;
1923 function phpwiki_gzhandler($ob) {
1924 if (function_exists('gzencode'))
1925 $ob = gzencode($ob);
1926 $GLOBALS['request']->_ob_get_length = strlen($ob);
1927 if (!headers_sent()) {
1928 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1933 function isWikiWord($word) {
1934 global $WikiNameRegexp;
1935 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1936 return preg_match("/^$WikiNameRegexp\$/",$word);
1939 // needed to store serialized objects-values only (perm, pref)
1940 function obj2hash ($obj, $exclude = false, $fields = false) {
1942 if (! $fields ) $fields = get_object_vars($obj);
1943 foreach ($fields as $key => $val) {
1944 if (is_array($exclude)) {
1945 if (in_array($key, $exclude)) continue;
1953 * isUtf8String($string) - cheap utf-8 detection
1955 * segfaults for strings longer than 10kb!
1956 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1957 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1959 function isUtf8String( $s ) {
1960 $ptrASCII = '[\x00-\x7F]';
1961 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1962 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1963 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1964 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1965 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1966 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1970 * Check for UTF-8 URLs; Internet Explorer produces these if you
1971 * type non-ASCII chars in the URL bar or follow unescaped links.
1972 * Requires urldecoded pagename.
1973 * Fixes sf.net bug #953949
1975 * src: languages/Language.php:checkTitleEncoding() from mediawiki
1977 function fixTitleEncoding( $s ) {
1982 if (empty($s)) return $s;
1984 $ishigh = preg_match( '/[\x80-\xff]/', $s);
1986 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1987 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1989 $isutf = ($ishigh ? isUtf8String($s) : true);
1990 $locharset = strtolower($charset);
1992 if( $locharset != "utf-8" and $ishigh and $isutf )
1993 $s = charset_convert('UTF-8', $locharset, $s);
1994 if ($locharset == "utf-8" and $ishigh and !$isutf )
1995 return utf8_encode( $s );
1997 // Other languages can safely leave this function, or replace
1998 // it with one to detect and convert another legacy encoding.
2003 * MySQL fulltext index doesn't grok utf-8, so we
2004 * need to fold cases and convert to hex.
2005 * src: languages/Language.php:stripForSearch() from mediawiki
2008 function stripForSearch( $string ) {
2009 global $wikiLowerChars;
2010 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2011 return preg_replace(
2012 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2013 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2019 * Workaround for allow_url_fopen, to get the content of an external URI.
2020 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2021 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2023 function url_get_contents( $uri ) {
2024 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2025 return @file_get_contents($uri);
2027 require_once("lib/HttpClient.php");
2028 $bits = parse_url($uri);
2029 $host = $bits['host'];
2030 $port = isset($bits['port']) ? $bits['port'] : 80;
2031 $path = isset($bits['path']) ? $bits['path'] : '/';
2032 if (isset($bits['query'])) {
2033 $path .= '?'.$bits['query'];
2035 $client = new HttpClient($host, $port);
2036 $client->use_gzip = false;
2037 if (!$client->get($path)) {
2040 return $client->getContent();
2046 * Generate consecutively named strings:
2047 * Name, Name2, Name3, ...
2049 function GenerateId($name) {
2050 static $ids = array();
2051 if (empty($ids[$name])) {
2056 return $name . $ids[$name];
2060 // from IncludePage. To be of general use.
2061 // content: string or array of strings
2062 function firstNWordsOfContent( $n, $content ) {
2063 if ($content and $n > 0) {
2064 if (is_array($content)) {
2065 // fixme: return a list of lines then?
2066 //$content = join("\n", $content);
2067 //$return_array = true;
2069 foreach ($content as $line) {
2070 $words = explode(' ', $line);
2071 if ($wordcount + count($words) > $n) {
2072 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2073 . sprintf(_("... (first %s words)"), $n);
2076 $wordcount += count($words);
2082 // fixme: use better whitespace/word seperators
2083 $words = explode(' ', $content);
2084 if (count($words) > $n) {
2085 return join(' ', array_slice($words, 0, $n))
2086 . sprintf(_("... (first %s words)"), $n);
2096 // moved from lib/plugin/IncludePage.php
2097 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2098 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2100 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2101 . " \\s*$\\n?" // possible blank lines
2102 . " ( (?: ^.*\\n? )*? )" // some lines
2103 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2104 implode("\n", $content),
2106 // Strip trailing blanks lines and ---- <hr>s
2107 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2109 $text = $match[1] . $section ."\n". $text;
2110 return explode("\n", $text);
2113 $mesg = $page ." ". $section;
2116 return array(sprintf(_("<%s: no such section>"), $mesg));
2119 // Extract the first $sections sections of the page
2120 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2122 $mycontent = $content;
2125 while ($sections > 0) {
2127 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2128 . " \\s*$\\n?" // possible blank lines
2129 . " ( (?: ^.*\\n? )*? )" // some lines
2130 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2131 implode("\n", $mycontent),
2133 $section = $match[2];
2134 // Strip trailing blanks lines and ---- <hr>s
2135 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2137 $text = $match[1] . $section ."\n". $text;
2140 $mycontent = explode("\n", $match[4]);
2142 if ($sections === 0) {
2143 return explode("\n", $result);
2149 // use this faster version: only load ExternalReferrer if we came from an external referrer
2150 function isExternalReferrer(&$request) {
2151 if ($referrer = $request->get('HTTP_REFERER')) {
2152 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2153 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2154 require_once("lib/ExternalReferrer.php");
2155 $se = new SearchEngines();
2156 return $se->parseSearchQuery($referrer);
2158 //if (DEBUG) return array('query' => 'wiki');
2163 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2165 function loadPhpExtension($extension) {
2166 if (!extension_loaded($extension)) {
2167 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2168 $soname = ($isWindows ? 'php_' : '')
2170 . ($isWindows ? '.dll' : '.so');
2174 return extension_loaded($extension);
2177 function charset_convert($from, $to, $data) {
2179 //$wikicharset = strtolower($CHARSET);
2180 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2181 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2182 return utf8_decode($data);
2183 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2184 return utf8_encode($data);
2186 if (loadPhpExtension("iconv")) {
2187 $tmpdata = iconv($from, $to, $data);
2189 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2193 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2198 function string_starts_with($string, $prefix) {
2199 return (substr($string, 0, strlen($prefix)) == $prefix);
2201 function string_ends_with($string, $suffix) {
2202 return (substr($string, -strlen($suffix)) == $suffix);
2204 function array_remove($arr,$value) {
2205 return array_values(array_diff($arr,array($value)));
2209 * Ensure that the script will have another $secs time left.
2210 * Works only if safe_mode is off.
2211 * For example not to timeout on waiting socket connections.
2212 * Use the socket timeout as arg.
2214 function longer_timeout($secs = 30) {
2215 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2216 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2217 if ($timeleft < $secs)
2218 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2221 function printSimpleTrace($bt) {
2223 echo "\nTraceback:\n";
2224 if (function_exists('debug_print_backtrace')) { // >= 5
2225 debug_print_backtrace();
2227 foreach ($bt as $i => $elem) {
2228 if (!array_key_exists('file', $elem)) {
2231 //echo join(" ",array_values($elem)),"\n";
2232 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2238 * Return the used process memory, in bytes.
2239 * Enable the section which will work for you. They are very slow.
2240 * Special quirks for Windows: Requires cygwin.
2242 function getMemoryUsage() {
2243 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2244 if (function_exists('memory_get_usage') and memory_get_usage()) {
2245 return memory_get_usage();
2246 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2247 $mem = $u['ru_maxrss'];
2248 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2249 // what we want is the process memory only: apache or php (if CGI)
2252 // win32_ps_stat_proc, win32_ps_stat_mem
2253 if (function_exists('win32_ps_list_procs')) {
2254 $info = win32_ps_stat_proc($pid);
2255 $memstr = $info['mem']['working_set_size'];
2257 // This works only if it's a cygwin process (apache or php).
2258 // Requires a newer cygwin
2259 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2261 // if it's native windows use something like this:
2262 // (requires pslist from sysinternals.com, grep, sed and perl)
2263 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2265 return (integer) trim($memstr);
2268 //%MEM: Percentage of total memory in use by this process
2269 //VSZ: Total virtual memory size, in 1K blocks.
2270 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2271 //CPU time used by process since it started.
2272 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2273 $memstr = exec("ps -orss -p $pid|sed 1d");
2274 return (integer) trim($memstr);
2279 * @param var $needle
2280 * @param array $haystack one-dimensional numeric array only, no hash
2282 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2283 It will return false if not found or the index where it was found.
2284 From dennis.decoene@moveit.be http://www.php.net/array_search
2286 function binary_search($needle, $haystack) {
2287 $high = count($haystack);
2290 while (($high - $low) > 1) {
2291 $probe = floor(($high + $low) / 2);
2292 if ($haystack[$probe] < $needle) {
2294 } elseif ($haystack[$probe] == $needle) {
2295 $high = $low = $probe;
2301 if ($high == count($haystack) || $haystack[$high] != $needle) {
2308 function is_localhost($url = false) {
2310 global $HTTP_SERVER_VARS;
2311 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2316 * Take a string and quote it sufficiently to be passed as a Javascript
2317 * string between ''s
2319 function javascript_quote_string($s) {
2320 return str_replace("'", "\'", $s);
2323 function isSerialized($s) {
2324 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2328 * Take a string and return an array of pairs (attribute name, attribute value)
2330 * We allow attributes with or without double quotes (")
2331 * Attribute-value pairs may be separated by space or comma
2332 * Space is normal HTML attributes, comma is for RichTable compatibility
2333 * border=1, cellpadding="5"
2334 * border=1 cellpadding="5"
2335 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2336 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2338 function parse_attributes($line) {
2342 if (empty($line)) return $options;
2343 $line = trim($line);
2344 if (empty($line)) return $options;
2345 $line = trim($line, ",");
2346 if (empty($line)) return $options;
2348 // First we have an attribute name.
2353 while (($i < strlen($line)) && ($line[$i] != '=')) {
2356 $attribute = substr($line, 0, $i);
2357 $attribute = strtolower($attribute);
2359 $line = substr($line, $i+1);
2360 $line = trim ($line);
2361 $line = trim ($line, "=");
2362 $line = trim ($line);
2364 if (empty($line)) return $options;
2366 // Then we have the attribute value.
2369 // Attribute value might be between double quotes
2370 // In that case we have to find the closing double quote
2371 if ($line[0] == '"') {
2372 $i++; // skip first '"'
2373 while (($i < strlen($line)) && ($line[$i] != '"')) {
2376 $value = substr($line, 0, $i);
2377 $value = trim ($value, '"');
2378 $value = trim ($value);
2380 // If there are no double quotes, we have to find the next space or comma
2382 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2385 $value = substr($line, 0, $i);
2386 $value = trim ($value);
2387 $value = trim ($value, ",");
2388 $value = trim ($value);
2391 $options[$attribute] = $value;
2393 $line = substr($line, $i+1);
2394 $line = trim ($line);
2395 $line = trim ($line, ",");
2396 $line = trim ($line);
2398 return $options + parse_attributes($line);
2402 * Returns true if the filename ends with an image suffix.
2403 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2405 function is_image ($filename) {
2407 if (defined('INLINE_IMAGES')) {
2408 $inline_images = INLINE_IMAGES;
2410 $inline_images = "png|jpg|jpeg|gif";
2413 foreach (explode("|", $inline_images) as $suffix) {
2414 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2422 * Compute cell in spreadsheet table
2423 * $table: two-dimensional table
2424 * $i and $j: indexes of cell to compute
2425 * $imax and $jmax: table dimensions
2427 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2429 // What is implemented:
2430 // @@=SUM(R)@@ : sum of cells in current row
2431 // @@=SUM(C)@@ : sum of cells in current column
2432 // @@=AVERAGE(R)@@ : average of cells in current row
2433 // @@=AVERAGE(C)@@ : average of cells in current column
2434 // @@=MAX(R)@@ : maximum value of cells in current row
2435 // @@=MAX(C)@@ : maximum value of cells in current column
2436 // @@=MIN(R)@@ : minimum value of cells in current row
2437 // @@=MIN(C)@@ : minimum value of cells in current column
2438 // @@=COUNT(R)@@ : number of cells in current row
2439 // (numeric or not, excluding headers and current cell)
2440 // @@=COUNT(C)@@ : number of cells in current column
2441 // (numeric or not, excluding headers and current cell)
2447 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2448 for ($index=0; $index<$imax; $index++) {
2449 if (is_numeric($table[$index][$j])) {
2450 $result += $table[$index][$j];
2453 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2455 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2456 for ($index=0; $index<$jmax; $index++) {
2457 if (is_numeric($table[$i][$index])) {
2458 $result += $table[$i][$index];
2461 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2463 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2464 for ($index=0; $index<$imax; $index++) {
2465 if (is_numeric($table[$index][$j])) {
2466 $result += $table[$index][$j];
2470 $result=$result/$counter;
2471 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2473 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2474 for ($index=0; $index<$jmax; $index++) {
2475 if (is_numeric($table[$i][$index])) {
2476 $result += $table[$i][$index];
2480 $result=$result/$counter;
2481 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2483 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2484 for ($index=0; $index<$imax; $index++) {
2485 if (is_numeric($table[$index][$j])) {
2488 $result=$table[$index][$j];
2490 $result = max($result, $table[$index][$j]);
2497 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2499 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2500 for ($index=0; $index<$jmax; $index++) {
2501 if (is_numeric($table[$i][$index])) {
2504 $result=$table[$i][$index];
2506 $result = max($result, $table[$i][$index]);
2513 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2515 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2516 for ($index=0; $index<$imax; $index++) {
2517 if (is_numeric($table[$index][$j])) {
2520 $result=$table[$index][$j];
2522 $result = min($result, $table[$index][$j]);
2529 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2531 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2532 for ($index=0; $index<$jmax; $index++) {
2533 if (is_numeric($table[$i][$index])) {
2536 $result=$table[$i][$index];
2538 $result = min($result, $table[$i][$index]);
2545 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2547 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2548 for ($index=0; $index<$imax; $index++) {
2549 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2553 $result = $counter-1; // exclude self
2554 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2556 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2557 for ($index=0; $index<$jmax; $index++) {
2558 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2562 $result = $counter-1; // exclude self
2563 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2566 return $table[$i][$j];
2570 * Remove accents from given text.
2572 function strip_accents($text) {
2573 $res = utf8_decode($text);
2575 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2576 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2577 return utf8_encode($res);
2579 // (c-file-style: "gnu")
2583 // c-basic-offset: 4
2584 // c-hanging-comment-ender-p: nil
2585 // indent-tabs-mode: nil