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 // support new syntax: [prefix/image.jpg size=50% border=n]
424 if (empty($alt)) $alt = "";
427 $arr = split(' ',$url);
428 if (!empty($arr)) $url = $arr[0];
429 if (! IsSafeURL($url)) {
430 $link = HTML::strong(HTML::u(array('class' => 'baduri'),
431 _("BAD URL -- remove all of <, >, \"")));
434 // spaces in inline images must be %20 encoded!
435 $link = HTML::img(array('src' => $url));
437 // Extract attributes
438 $arr = parse_attributes(strstr($ori_url, " "));
439 foreach ($arr as $attr => $value) {
440 // These attributes take strings: lang, id, title, alt
441 if (($attr == "lang")
443 || ($attr == "title")
444 || ($attr == "alt")) {
445 $link->setAttr($attr, $value);
447 // align = bottom|middle|top|left|right
448 elseif (($attr == "align")
449 && (($value == "bottom")
450 || ($value == "middle")
452 || ($value == "left")
453 || ($value == "right"))) {
454 $link->setAttr($attr, $value);
456 // These attributes take a number (pixels): border, hspace, vspace
457 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
458 && (is_int($value))) {
459 $link->setAttr($attr, $value);
461 // These attributes take a number (pixels) or a percentage: height, width
462 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
463 && (preg_match('/\d+[%p]?x?/', $value))) {
464 $link->setAttr($attr, $value);
466 // We allow size=50% and size=20x30
467 // We replace this with "width" and "height" HTML attributes
468 elseif ($attr == "size") {
469 if (preg_match('/(\d+)%/', $value, $m)) {
470 $link->setAttr('width',$m[1]);
471 $link->setAttr('height',$m[1]);
472 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
473 $link->setAttr('width',$m[1]);
474 $link->setAttr('height',$m[2]);
478 trigger_error(sprintf(_("Invalid image attribute %s %s=%s"),
479 $url, $attr, $value), E_USER_WARNING);
482 // Correct silently the most common error
483 if ($url != $ori_url and empty($arr) and !preg_match("/^http/",$url)) {
484 // space belongs to the path
485 $file = NormalizeLocalFileName($ori_url);
486 if (file_exists($file)) {
487 $link = HTML::img(array('src' => $ori_url));
488 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
489 $file = substr($file, strlen(getUploadDataPath()));
490 $path = getUploadFilePath().$file;
491 if (file_exists($path)) {
492 $link->setAttr('src', getUploadDataPath() . $file);
497 if (!$link->getAttr('alt')) {
498 $link->setAttr('alt', $alt);
500 // Check width and height as spam countermeasure
501 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
502 //$width = (int) $width; // px or % or other suffix
503 //$height = (int) $height;
504 if (($width < 3 and $height < 10) or
505 ($height < 3 and $width < 20) or
506 ($height < 7 and $width < 7))
508 trigger_error(_("Invalid image size"), E_USER_WARNING);
513 // Prepare for getimagesize($url)
514 // $url only valid for external urls, otherwise local path
515 // Older php versions crash here with certain png's:
516 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
517 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
518 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
519 if (DISABLE_GETIMAGESIZE)
521 elseif (! preg_match("/\.$force_img$/i", $url))
522 ; // only valid image extensions or scripts assumed to generate images
523 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
524 ; // it's safe to assume that this will fail.
525 elseif (preg_match("/^http/",$url)) { // external url
526 $size = @getimagesize($url);
527 } else { // local file
528 if (file_exists($file = NormalizeLocalFileName($url))) { // here
529 $size = @getimagesize($file);
530 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
531 $size = @getimagesize($file);
532 $link->setAttr('src', rawurldecode($url));
533 } elseif (string_starts_with($url, getUploadDataPath())) { // there
534 $file = substr($file, strlen(getUploadDataPath()));
535 $path = getUploadFilePath().rawurldecode($file);
536 $size = @getimagesize($path);
537 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
538 } else { // elsewhere
539 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
545 if (($width < 3 and $height < 10)
546 or ($height < 3 and $width < 20)
547 or ($height < 7 and $width < 7))
549 trigger_error(_("Invalid image size"), E_USER_WARNING);
554 $link->setAttr('class', 'inlineimage');
556 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
557 * png|jpg|gif|jpeg|bmp|pl|cgi
558 * Note: Allow cgi's (pl,cgi) returning images.
560 if (!preg_match("/\.(".$force_img.")/i", $url)) {
561 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
562 // => HTML::object(array('src' => $url)) ...;
563 return ImgObject($link, $ori_url);
569 * <object> / <embed> tags instead of <img> for all non-image extensions
571 * Called by LinkImage(), not directly.
572 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
573 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
574 * $alt may be an alternate img
575 * TODO: Need to unify with WikiPluginCached::embedObject()
577 * Note that Safari 1.0 will crash with <object>, so use only <embed>
578 * http://www.alleged.org.uk/pdc/2002/svg-object.html
580 * Allowed object tags:
581 * DATA=URI (object data)
582 * CLASSID=URI (location of implementation)
583 * ARCHIVE=CDATA (archive files)
584 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
585 * WIDTH=Length (object width)
586 * HEIGHT=Length (object height)
587 * NAME=CDATA (name for form submission)
588 * USEMAP=URI (client-side image map)
589 * TYPE=ContentType (content-type of object)
590 * CODETYPE=ContentType (content-type of code)
591 * STANDBY=Text (message to show while loading)
592 * TABINDEX=NUMBER (position in tabbing order)
593 * DECLARE (do not instantiate object)
594 * The rest is added as <param name="" value="" /> tags
596 function ImgObject($img, $url) {
597 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
598 $args = split(' ', $url);
600 if (count($args) >= 1) {
601 $url = array_shift($args);
603 foreach ($args as $attr) {
604 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
605 "codetype,standby,tabindex,declare") as $param)
607 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
608 $img->setAttr($param, $m[1]);
614 // now all remaing args are added as <param> to the object
615 foreach ($args as $attr) {
616 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
617 $params[] = HTML::param(array('name' => $m[1],
622 $type = $img->getAttr('type');
624 // TODO: map extension to mime-types if type is not given and php < 4.3
625 if (function_exists('mime_content_type'))
626 $type = mime_content_type($url);
628 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
630 $object->setAttr('class', 'inlineobject');
632 foreach ($params as $param) $object->pushContent($param);
634 if (isBrowserSafari()) {
635 return HTML::embed($object->_attr, $object->_content);
637 $object->pushContent(HTML::embed($object->_attr));
644 // var in php5 deprecated
646 $this->items = array();
649 function push($item) {
650 $this->items[$this->size] = $item;
656 if ($this->size == 0) {
657 return false; // stack is empty
660 return $this->items[$this->size];
669 return $this->items[$this->size - 1];
675 // end class definition
677 function SplitQueryArgs ($query_args = '')
679 // FIXME: use the arg-seperator which might not be &
680 $split_args = split('&', $query_args);
682 while (list($key, $val) = each($split_args))
683 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
684 $args[$m[1]] = $m[2];
688 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
691 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
692 return HTML::strong(array('class' => 'rawurl'),
693 HTML::u(array('class' => 'baduri'),
694 _("BAD phpwiki: URL")));
698 $pagename = urldecode($m[1]);
701 if (empty($pagename) &&
702 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
703 // Convert old style links (to not break diff links in
705 $pagename = urldecode($m[2]);
706 $args = array("action" => $m[1]);
709 $args = SplitQueryArgs($qargs);
712 if (empty($pagename))
713 $pagename = $GLOBALS['request']->getArg('pagename');
715 if (isset($args['action']) && $args['action'] == 'browse')
716 unset($args['action']);
719 if (empty($args['action']))
721 else if (is_safe_action($args['action']))
722 $class = 'wikiaction';
724 if (empty($args['action']) || is_safe_action($args['action']))
725 $class = 'wikiaction';
727 // Don't allow administrative links on unlocked pages.
728 $dbi = $GLOBALS['request']->getDbh();
729 $page = $dbi->getPage($basepage ? $basepage : $pagename);
730 if (!$page->get('locked'))
731 return HTML::span(array('class' => 'wikiunsafe'),
732 HTML::u(_("Lock page to enable link")));
733 $class = 'wikiadmin';
737 $text = HTML::span(array('class' => 'rawurl'), $url);
739 $wikipage = new WikiPageName($pagename);
740 if (!$wikipage->isValid()) {
742 return $WikiTheme->linkBadWikiWord($wikipage, $url);
745 return HTML::a(array('href' => WikiURL($pagename, $args),
751 * A class to assist in parsing wiki pagenames.
753 * Now with subpages and anchors, parsing and passing around
754 * pagenames is more complicated. This should help.
758 /** Short name for page.
760 * This is the value of $name passed to the constructor.
761 * (For use, e.g. as a default label for links to the page.)
765 /** The full page name.
767 * This is the full name of the page (without anchor).
773 * This is the referenced anchor within the page, or the empty string.
779 * @param mixed $name Page name.
780 * WikiDB_Page, WikiDB_PageRevision, or string.
781 * This can be a relative subpage name (like '/SubPage'),
782 * or can be the empty string to refer to the $basename.
784 * @param string $anchor For links to anchors in page.
786 * @param mixed $basename Page name from which to interpret
787 * relative or other non-fully-specified page names.
789 function WikiPageName($name, $basename=false, $anchor=false) {
790 if (is_string($name)) {
791 $this->shortName = $name;
792 if (strstr($name, ':')) {
793 list($moniker, $shortName) = split (":", $name, 2);
794 $map = getInterwikiMap(); // allow overrides to custom maps
795 if (isset($map->_map[$moniker])) {
796 $url = $map->_map[$moniker];
797 if (strstr($url, '%s'))
798 $url = sprintf($url, $shortName);
802 // expand Talk or User, but not to absolute urls!
803 if (strstr($url, '//')) {
804 if ($moniker == 'Talk')
805 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
806 elseif ($moniker == 'User')
811 if (strstr($shortName, '?')) {
812 list($shortName, $dummy) = split("\?", $shortName, 2);
814 $this->shortName = $shortName;
817 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
818 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
820 $name = $this->_pagename($basename) . $name;
822 $name = $this->_normalize_bad_pagename($name);
823 $this->shortName = $name;
828 $name = $this->_pagename($name);
829 $this->shortName = $name;
832 $this->name = $this->_check($name);
833 $this->anchor = (string)$anchor;
840 function getParent() {
842 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
844 return substr($name, 0, -strlen($tail));
847 function isValid($strict = false) {
849 return !isset($this->_errors);
850 return (is_string($this->name) and $this->name != '');
853 function getWarnings() {
855 if (isset($this->_warnings))
856 $warnings = array_merge($warnings, $this->_warnings);
857 if (isset($this->_errors))
858 $warnings = array_merge($warnings, $this->_errors);
862 return sprintf(_("'%s': Bad page name: %s"),
863 $this->shortName, join(', ', $warnings));
866 function _pagename($page) {
867 if (isa($page, 'WikiDB_Page'))
868 return $page->getName();
869 elseif (isa($page, 'WikiDB_PageRevision'))
870 return $page->getPageName();
871 elseif (isa($page, 'WikiPageName'))
873 // '0' or e.g. '1984' should be allowed though
874 if (!is_string($page) and !is_integer($page)) {
875 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
876 $page, gettype($page), get_class($page)),
879 //assert(is_string($page));
883 function _normalize_bad_pagename($name) {
884 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
886 // Punt... You really shouldn't get here.
889 return $request->getArg('pagename');
891 assert($name[0] == SUBPAGE_SEPARATOR);
892 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
893 return substr($name, 1);
897 * Compress internal white-space to single space character.
899 * This leads to problems with loading a foreign charset pagename,
900 * which cannot be deleted anymore, because unknown chars are compressed.
901 * So BEFORE importing a file _check must be done !!!
903 function _check($pagename) {
904 // Compress internal white-space to single space character.
905 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
906 if ($pagename != $orig)
907 $this->_warnings[] = _("White space converted to single space");
909 // Delete any control characters.
910 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
911 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
912 if ($pagename != $orig)
913 $this->_errors[] = _("Control characters not allowed");
916 // Strip leading and trailing white-space.
917 $pagename = trim($pagename);
920 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
921 $pagename = substr($pagename, 1);
922 if ($pagename != $orig)
923 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
925 // ";" is urlencoded, so safe from php arg-delim problems
926 /*if (strstr($pagename, ';')) {
927 $this->_warnings[] = _("';' is deprecated");
928 $pagename = str_replace(';', '', $pagename);
931 // not only for SQL, also to restrict url length
932 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
933 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
934 $this->_errors[] = _("too long");
937 // disallow some chars only on file and cvs
938 if ((DATABASE_TYPE == 'cvs'
939 or DATABASE_TYPE == 'file'
940 or DATABASE_TYPE == 'flatfile')
941 and preg_match('/(:|\.\.)/', $pagename, $m))
943 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
944 $pagename = str_replace('..', '', $pagename);
945 $pagename = str_replace(':', '', $pagename);
953 * Convert old page markup to new-style markup.
955 * @param string $text Old-style wiki markup.
957 * @param string $markup_type
959 * <dt><code>"block"</code> <dd>Convert all markup.
960 * <dt><code>"inline"</code> <dd>Convert only inline markup.
961 * <dt><code>"links"</code> <dd>Convert only link markup.
964 * @return string New-style wiki markup.
966 * @bugs Footnotes don't work quite as before (esp if there are
967 * multiple references to the same footnote. But close enough,
968 * probably for now....
969 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
970 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
971 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
972 * also known to crash, even with Apache1.
974 function ConvertOldMarkup ($text, $markup_type = "block") {
980 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
981 // AnciennesR%E8glesDeFormatage crashes.
982 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
983 // also known to crash, even with Apache1.
985 // I suspect this only to crash with Apache2 and IIS.
986 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
987 and preg_match("/plugin CreateToc/", $text))
989 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
990 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
991 ._("Skipped."), E_USER_WARNING);
993 //if (!DEBUG) return $text;
998 /*****************************************************************
999 * Conversions for inline markup:
1006 // escape escaped brackets
1010 // change ! escapes to ~'s.
1011 global $WikiNameRegexp, $request;
1012 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1013 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1014 if (check_php_version(4,3,9)) {
1015 $map = getInterwikiMap();
1016 if ($map_regex = $map->getRegexp())
1017 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1019 $bang_esc[] = $WikiNameRegexp;
1020 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1023 $subs["links"] = array($orig, $repl);
1025 // Temporarily URL-encode pairs of underscores in links to hide
1026 // them from the re for bold markup.
1027 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1028 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1031 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1034 // Convert footnote references.
1035 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1036 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1038 // Convert old style emphases to HTML style emphasis.
1039 $orig[] = '/__(.*?)__/';
1040 $repl[] = '<strong>\\1</strong>';
1041 $orig[] = "/''(.*?)''/";
1042 $repl[] = '<em>\\1</em>';
1044 // Escape nestled markup.
1045 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1048 // in old markup headings only allowed at beginning of line
1052 // Convert URL-encoded pairs of underscores in links back to
1053 // real underscores after bold markup has been converted.
1054 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1055 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1057 $subs["inline"] = array($orig, $repl);
1059 /*****************************************************************
1060 * Patterns which match block markup constructs which take
1061 * special handling...
1065 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1067 $blockpats[] = '\|(?:.*\n\|)*';
1070 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1072 // Footnote definitions
1073 $blockpats[] = '\[\s*(\d+)\s*\]';
1077 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1081 $blockpats[] = '!{1,3}[^!]';
1083 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1084 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1086 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1087 . join("|", $blockpats)
1092 if ($markup_type != "block") {
1093 list ($orig, $repl) = $subs[$markup_type];
1094 return preg_replace($orig, $repl, $text);
1097 list ($orig, $repl) = $subs['inline'];
1100 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1101 // AnciennesR%E8glesDeFormatage and more
1102 // See http://www.pcre.org/pcre.txt LIMITATIONS
1103 while (preg_match($block_re, $text, $m)) {
1104 $text = substr($text, strlen($m[0]));
1105 list (,$leading_text, $block) = $m;
1108 if (strchr(" \t", $block[0])) {
1110 $prefix = "<pre>\n";
1111 $suffix = "\n</pre>\n";
1113 elseif ($block[0] == '|') {
1115 $prefix = "<?plugin OldStyleTable\n";
1118 elseif (strchr("#*;", $block[0])) {
1119 // Old-style list item
1120 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1121 list (,$ind,$bullet) = $m;
1122 $block = substr($block, strlen($m[0]));
1124 $indent = str_repeat(' ', strlen($ind));
1125 if ($bullet[0] == ';') {
1126 //$term = ltrim(substr($bullet, 1));
1127 //return $indent . $term . "\n" . $indent . ' ';
1128 $prefix = $ind . $bullet;
1131 $prefix = $indent . $bullet . ' ';
1133 elseif ($block[0] == '[') {
1134 // Footnote definition
1135 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1137 $block = substr($block, strlen($m[0]));
1138 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1140 elseif ($block[0] == '<') {
1142 // HACK: no inline markup...
1146 elseif ($block[0] == '!') {
1148 preg_match('/^!{1,3}/', $block, $m);
1150 $block = substr($block, strlen($m[0]));
1156 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1157 if ($block) $block = preg_replace($orig, $repl, $block);
1158 $out .= $leading_text;
1163 return $out . preg_replace($orig, $repl, $text);
1169 * Expand tabs in string.
1171 * Converts all tabs to (the appropriate number of) spaces.
1173 * @param string $str
1174 * @param integer $tab_width
1177 function expand_tabs($str, $tab_width = 8) {
1178 $split = split("\t", $str);
1179 $tail = array_pop($split);
1181 foreach ($split as $hunk) {
1183 $pos = strlen(strrchr($expanded, "\n")) - 1;
1184 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1186 return substr($expanded, 1) . $tail;
1190 * Split WikiWords in page names.
1192 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1193 * places like page titles. This is rumored to help search engines
1196 * @param $page string The page name.
1198 * @return string The split name.
1200 function SplitPagename ($page) {
1202 if (preg_match("/\s/", $page))
1203 return $page; // Already split --- don't split any more.
1205 // This algorithm is specialized for several languages.
1206 // (Thanks to Pierrick MEIGNEN)
1207 // Improvements for other languages welcome.
1210 // This mess splits between a lower-case letter followed by
1211 // either an upper-case or a numeral; except that it wont
1212 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1213 switch ($GLOBALS['LANG']) {
1218 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1221 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1224 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1225 // This the single-letter words 'I' and 'A' from any following
1226 // capitalized words.
1227 switch ($GLOBALS['LANG']) {
1229 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1232 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1235 // Split at underscore
1236 $RE[] = '/(_)([[:alpha:]])/';
1237 $RE[] = '/([[:alpha:]])(_)/';
1238 // Split numerals from following letters.
1239 $RE[] = '/(\d)([[:alpha:]])/';
1240 // Split at subpage seperators. TBD in WikiTheme.php
1241 $RE[] = "/([^${sep}]+)(${sep})/";
1242 $RE[] = "/(${sep})([^${sep}]+)/";
1244 foreach ($RE as $key)
1245 $RE[$key] = pcre_fix_posix_classes($key);
1248 foreach ($RE as $regexp) {
1249 $page = preg_replace($regexp, '\\1 \\2', $page);
1254 function NoSuchRevision (&$request, $page, $version) {
1255 $html = HTML(HTML::h2(_("Revision Not Found")),
1256 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1257 $version, WikiLink($page, 'auto'))));
1258 include_once('lib/Template.php');
1259 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1265 * Get time offset for local time zone.
1267 * @param $time time_t Get offset for this time. Default: now.
1268 * @param $no_colon boolean Don't put colon between hours and minutes.
1269 * @return string Offset as a string in the format +HH:MM.
1271 function TimezoneOffset ($time = false, $no_colon = false) {
1272 if ($time === false)
1274 $secs = date('Z', $time);
1283 $colon = $no_colon ? '' : ':';
1284 $mins = intval(($secs + 30) / 60);
1285 return sprintf("%s%02d%s%02d",
1286 $sign, $mins / 60, $colon, $mins % 60);
1291 * Format time in ISO-8601 format.
1293 * @param $time time_t Time. Default: now.
1294 * @return string Date and time in ISO-8601 format.
1296 function Iso8601DateTime ($time = false) {
1297 if ($time === false)
1299 $tzoff = TimezoneOffset($time);
1300 $date = date('Y-m-d', $time);
1301 $time = date('H:i:s', $time);
1302 return $date . 'T' . $time . $tzoff;
1306 * Format time in RFC-2822 format.
1308 * @param $time time_t Time. Default: now.
1309 * @return string Date and time in RFC-2822 format.
1311 function Rfc2822DateTime ($time = false) {
1312 if ($time === false)
1314 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1318 * Format time in RFC-1123 format.
1320 * @param $time time_t Time. Default: now.
1321 * @return string Date and time in RFC-1123 format.
1323 function Rfc1123DateTime ($time = false) {
1324 if ($time === false)
1326 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1329 /** Parse date in RFC-1123 format.
1331 * According to RFC 1123 we must accept dates in the following
1334 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1335 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1336 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1338 * (Though we're only allowed to generate dates in the first format.)
1340 function ParseRfc1123DateTime ($timestr) {
1341 $timestr = trim($timestr);
1342 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1343 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1345 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1347 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1348 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1350 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1351 if ($year < 70) $year += 2000;
1352 elseif ($year < 100) $year += 1900;
1354 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1355 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1357 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1364 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1366 return false; // failed
1371 * Format time to standard 'ctime' format.
1373 * @param $time time_t Time. Default: now.
1374 * @return string Date and time.
1376 function CTime ($time = false)
1378 if ($time === false)
1380 return date("D M j H:i:s Y", $time);
1385 * Format number as kilobytes or bytes.
1386 * Short format is used for PageList
1387 * Long format is used in PageInfo
1389 * @param $bytes int. Default: 0.
1390 * @param $longformat bool. Default: false.
1391 * @return class FormattedText (XmlElement.php).
1393 function ByteFormatter ($bytes = 0, $longformat = false) {
1396 if ($bytes < 1024) {
1398 $size = fmt("%s b", $bytes);
1400 $size = fmt("%s bytes", $bytes);
1403 $kb = round($bytes / 1024, 1);
1405 $size = fmt("%s k", $kb);
1407 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1413 * Internationalized printf.
1415 * This is essentially the same as PHP's built-in printf
1416 * with the following exceptions:
1418 * <li> It passes the format string through gettext().
1419 * <li> It supports the argument reordering extensions.
1426 * __printf("Differences between versions %s and %s of %s",
1427 * $new_link, $old_link, $page_link);
1430 * Then in locale/po/de.po, one can reorder the printf arguments:
1433 * msgid "Differences between %s and %s of %s."
1434 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1437 * (Note that while PHP tries to expand $vars within double-quotes,
1438 * the values in msgstr undergo no such expansion, so the '$'s
1441 * One shouldn't use reordered arguments in the default format string.
1442 * Backslashes in the default string would be necessary to escape the
1443 * '$'s, and they'll cause all kinds of trouble....
1445 function __printf ($fmt) {
1446 $args = func_get_args();
1448 echo __vsprintf($fmt, $args);
1452 * Internationalized sprintf.
1454 * This is essentially the same as PHP's built-in printf with the
1455 * following exceptions:
1458 * <li> It passes the format string through gettext().
1459 * <li> It supports the argument reordering extensions.
1464 function __sprintf ($fmt) {
1465 $args = func_get_args();
1467 return __vsprintf($fmt, $args);
1471 * Internationalized vsprintf.
1473 * This is essentially the same as PHP's built-in printf with the
1474 * following exceptions:
1477 * <li> It passes the format string through gettext().
1478 * <li> It supports the argument reordering extensions.
1483 function __vsprintf ($fmt, $args) {
1484 $fmt = gettext($fmt);
1485 // PHP's sprintf doesn't support variable with specifiers,
1486 // like sprintf("%*s", 10, "x"); --- so we won't either.
1488 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1489 // Format string has '%2$s' style argument reordering.
1490 // PHP doesn't support this.
1491 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1492 // literal variable name substitution only to keep locale
1493 // strings uncluttered
1494 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1495 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1497 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1500 // Reorder arguments appropriately.
1501 foreach($m[1] as $argnum) {
1502 if ($argnum < 1 || $argnum > count($args))
1503 trigger_error(sprintf(_("%s: argument index out of range"),
1504 $argnum), E_USER_WARNING);
1505 $newargs[] = $args[$argnum - 1];
1510 // Not all PHP's have vsprintf, so...
1511 array_unshift($args, $fmt);
1512 return call_user_func_array('sprintf', $args);
1515 function file_mtime ($filename) {
1516 if ($stat = @stat($filename))
1522 function sort_file_mtime ($a, $b) {
1523 $ma = file_mtime($a);
1524 $mb = file_mtime($b);
1525 if (!$ma or !$mb or $ma == $mb) return 0;
1526 return ($ma > $mb) ? -1 : 1;
1531 * Build an array in $this->_fileList of files from $dirname.
1532 * Subdirectories are not traversed.
1534 * (This was a function LoadDir in lib/loadsave.php)
1535 * See also http://www.php.net/manual/en/function.readdir.php
1537 function getFiles($exclude='', $sortby='', $limit='') {
1538 $list = $this->_fileList;
1541 require_once('lib/PageList.php');
1542 switch (Pagelist::sortby($sortby, 'db')) {
1543 case 'pagename ASC': break;
1544 case 'pagename DESC':
1545 $list = array_reverse($list);
1548 usort($list,'sort_file_mtime');
1551 usort($list,'sort_file_mtime');
1552 $list = array_reverse($list);
1557 return array_splice($list, 0, $limit);
1561 function _filenameSelector($filename) {
1562 if (! $this->_pattern )
1565 if (! $this->_pcre_pattern )
1566 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1567 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1572 function fileSet($directory, $filepattern = false) {
1573 $this->_fileList = array();
1574 $this->_pattern = $filepattern;
1576 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1578 $this->_case = !isWindows();
1579 $this->_pathsep = '/';
1581 if (empty($directory)) {
1582 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1584 return; // early return
1587 @ $dir_handle = opendir($dir=$directory);
1588 if (empty($dir_handle)) {
1589 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1590 $dir), E_USER_NOTICE);
1591 return; // early return
1594 while ($filename = readdir($dir_handle)) {
1595 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1597 if ($this->_filenameSelector($filename)) {
1598 array_push($this->_fileList, "$filename");
1599 //trigger_error(sprintf(_("found file %s"), $filename),
1600 // E_USER_NOTICE); //debugging
1603 closedir($dir_handle);
1609 // expands a list containing regex's to its matching entries
1610 class ListRegexExpand {
1611 //var $match, $list, $index, $case_sensitive;
1612 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1613 $this->match = $match;
1614 $this->list = &$list;
1615 $this->case_sensitive = $case_sensitive;
1616 //$this->index = false;
1618 function listMatchCallback ($item, $key) {
1619 $quoted = str_replace('/','\/',$item);
1620 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1622 unset($this->list[$this->index]);
1623 $this->list[] = $item;
1626 function expandRegex ($index, &$pages) {
1627 $this->index = $index;
1628 array_walk($pages, array($this, 'listMatchCallback'));
1633 // Convert fileglob to regex style:
1634 // Convert some wildcards to pcre style, escape the rest
1635 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1636 // Fixed bug #994994: "/" in $glob.
1637 function glob_to_pcre ($glob) {
1638 // check simple case: no need to escape
1639 $escape = '\[](){}=!<>|:/';
1640 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1642 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1643 $glob = strtr($glob, "\\", "\xff");
1644 $glob = str_replace("/", "\\/", $glob);
1645 // first convert some unescaped expressions to pcre style: . => \.
1647 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1648 "\\1\xff\\2", $glob);
1651 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1652 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1653 if (!preg_match('/^[\?\*]/', $glob))
1655 if (!preg_match('/[\?\*]$/', $glob))
1658 // Fixes Bug 1182997
1659 // .*? handled above, now escape the rest
1660 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1661 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1663 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1665 $re = preg_replace('/\xff/', '', $re);
1669 function glob_match ($glob, $against, $case_sensitive = true) {
1670 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1674 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1675 $list = explode(',',$input);
1676 // expand wildcards from list of $allnames
1677 if (preg_match('/[\?\*]/',$input)) {
1678 // Optimizing loop invariants:
1679 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1680 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1682 if (preg_match('/[\?\*]/',$f)) {
1684 $expand = new ListRegexExpand($list,
1685 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1686 $expand->expandRegex($i, $allnames);
1693 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1694 function explodePageList($input, $include_empty=false, $sortby='pagename',
1695 $limit='', $exclude='') {
1696 include_once("lib/PageList.php");
1697 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1700 // Class introspections
1703 * Determine whether object is of a specified type.
1704 * In PHP builtin since 4.2.0 as is_a()
1705 * is_a() deprecated in PHP 5, in favor of instanceof operator
1707 * @param $object object An object.
1708 * @param $class string Class name.
1709 * @return bool True iff $object is a $class
1710 * or a sub-type of $class.
1712 function isa ($object, $class) {
1713 //if (check_php_version(5))
1714 // return $object instanceof $class;
1715 if (check_php_version(4,2) and !check_php_version(5))
1716 return is_a($object, $class);
1718 $lclass = check_php_version(5) ? $class : strtolower($class);
1719 return is_object($object)
1720 && ( strtolower(get_class($object)) == strtolower($class)
1721 || is_subclass_of($object, $lclass) );
1724 /** Determine whether (possible) object has method.
1726 * @param $object mixed Object
1727 * @param $method string Method name
1728 * @return bool True iff $object is an object with has method $method.
1730 function can ($object, $method) {
1731 return is_object($object) && method_exists($object, strtolower($method));
1734 /** Determine whether a function is okay to use.
1736 * Some providers (e.g. Lycos) disable some of PHP functions for
1737 * "security reasons." This makes those functions, of course,
1738 * unusable, despite the fact the function_exists() says they
1741 * This function test to see if a function exists and is not
1742 * disallowed by PHP's disable_functions config setting.
1744 * @param string $function_name Function name
1745 * @return bool True iff function can be used.
1747 function function_usable($function_name) {
1749 if (!is_array($disabled)) {
1750 $disabled = array();
1751 // Use get_cfg_var since ini_get() is one of the disabled functions
1752 // (on Lycos, at least.)
1753 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1754 foreach ($split as $f)
1755 $disabled[strtolower($f)] = true;
1758 return ( function_exists($function_name)
1759 and ! isset($disabled[strtolower($function_name)])
1766 * This is used for generating ETags.
1768 function wikihash ($x) {
1769 if (is_scalar($x)) {
1772 elseif (is_array($x)) {
1774 return md5(serialize($x));
1776 elseif (is_object($x)) {
1779 trigger_error("Can't hash $x", E_USER_ERROR);
1784 * Seed the random number generator.
1786 * better_srand() ensures the randomizer is seeded only once.
1788 * How random do you want it? See:
1789 * http://www.php.net/manual/en/function.srand.php
1790 * http://www.php.net/manual/en/function.mt-srand.php
1792 function better_srand($seed = '') {
1793 static $wascalled = FALSE;
1795 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1796 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1798 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1802 function rand_ascii($length = 1) {
1805 for ($i = 1; $i <= $length; $i++) {
1806 // return only typeable 7 bit ascii, avoid quotes
1807 if (function_exists('mt_rand'))
1808 $s .= chr(mt_rand(40, 126));
1810 // the usually bad glibc srand()
1811 $s .= chr(rand(40, 126));
1816 /* by Dan Frankowski.
1818 function rand_ascii_readable ($length = 6) {
1819 // Pick a few random letters or numbers
1822 // Don't use 1lI0O, because they're hard to read
1823 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1824 $letter_len = strlen($letters);
1825 for ($i=0; $i < $length; $i++) {
1826 if (function_exists('mt_rand'))
1827 $word .= $letters[mt_rand(0, $letter_len-1)];
1829 $word .= $letters[rand(0, $letter_len-1)];
1835 * Recursively count all non-empty elements
1836 * in array of any dimension or mixed - i.e.
1837 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1838 * See http://www.php.net/manual/en/function.count.php
1840 function count_all($arg) {
1841 // skip if argument is empty
1843 //print_r($arg); //debugging
1845 // not an array, return 1 (base case)
1848 // else call recursively for all elements $arg
1849 foreach($arg as $key => $val)
1850 $count += count_all($val);
1855 function isSubPage($pagename) {
1856 return (strstr($pagename, SUBPAGE_SEPARATOR));
1859 function subPageSlice($pagename, $pos) {
1860 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1861 $pages = array_slice($pages,$pos,1);
1868 * Class for "popping up" and alert box. (Except that right now, it doesn't
1872 * This is a hackish and needs to be refactored. However it would be nice to
1873 * unify all the different methods we use for showing Alerts and Dialogs.
1874 * (E.g. "Page deleted", login form, ...)
1879 * @param object $request
1880 * @param mixed $head Header ("title") for alert box.
1881 * @param mixed $body The text in the alert box.
1882 * @param hash $buttons An array mapping button labels to URLs.
1883 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1885 function Alert($head, $body, $buttons=false) {
1886 if ($buttons === false)
1889 if (is_array($body)) {
1891 foreach ($body as $li) {
1892 $html->pushContent(HTML::li($li));
1896 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1897 $this->_buttons = $buttons;
1901 * Show the alert box.
1906 $tokens = $this->_tokens;
1907 $tokens['BUTTONS'] = $this->_getButtons();
1909 $request->discardOutput();
1910 $tmpl = new Template('dialog', $request, $tokens);
1916 function _getButtons() {
1919 $buttons = $this->_buttons;
1921 $buttons = array(_("Okay") => $request->getURLtoSelf());
1924 foreach ($buttons as $label => $url)
1925 print "$label $url\n";
1926 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1927 return new XmlContent($out);
1932 // 1.3.9-p1 => 1030.091
1933 // 1.3.10pre => 1030.099
1934 // 1.3.11pre-20041120 => 1030.1120041120
1935 // 1.3.12-rc1 => 1030.119
1936 function phpwiki_version() {
1937 static $PHPWIKI_VERSION;
1938 if (!isset($PHPWIKI_VERSION)) {
1939 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1940 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1941 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1942 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1943 $PHPWIKI_VERSION -= 0.01;
1945 return $PHPWIKI_VERSION;
1948 function phpwiki_gzhandler($ob) {
1949 if (function_exists('gzencode'))
1950 $ob = gzencode($ob);
1951 $GLOBALS['request']->_ob_get_length = strlen($ob);
1952 if (!headers_sent()) {
1953 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1958 function isWikiWord($word) {
1959 global $WikiNameRegexp;
1960 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1961 return preg_match("/^$WikiNameRegexp\$/",$word);
1964 // needed to store serialized objects-values only (perm, pref)
1965 function obj2hash ($obj, $exclude = false, $fields = false) {
1967 if (! $fields ) $fields = get_object_vars($obj);
1968 foreach ($fields as $key => $val) {
1969 if (is_array($exclude)) {
1970 if (in_array($key, $exclude)) continue;
1978 * isUtf8String($string) - cheap utf-8 detection
1980 * segfaults for strings longer than 10kb!
1981 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1982 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1984 function isUtf8String( $s ) {
1985 $ptrASCII = '[\x00-\x7F]';
1986 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1987 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1988 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1989 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1990 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1991 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1995 * Check for UTF-8 URLs; Internet Explorer produces these if you
1996 * type non-ASCII chars in the URL bar or follow unescaped links.
1997 * Requires urldecoded pagename.
1998 * Fixes sf.net bug #953949
2000 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2002 function fixTitleEncoding( $s ) {
2007 if (empty($s)) return $s;
2009 $ishigh = preg_match( '/[\x80-\xff]/', $s);
2011 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2012 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
2014 $isutf = ($ishigh ? isUtf8String($s) : true);
2015 $locharset = strtolower($charset);
2017 if( $locharset != "utf-8" and $ishigh and $isutf )
2018 $s = charset_convert('UTF-8', $locharset, $s);
2019 if ($locharset == "utf-8" and $ishigh and !$isutf )
2020 return utf8_encode( $s );
2022 // Other languages can safely leave this function, or replace
2023 // it with one to detect and convert another legacy encoding.
2028 * MySQL fulltext index doesn't grok utf-8, so we
2029 * need to fold cases and convert to hex.
2030 * src: languages/Language.php:stripForSearch() from mediawiki
2033 function stripForSearch( $string ) {
2034 global $wikiLowerChars;
2035 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2036 return preg_replace(
2037 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2038 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2044 * Workaround for allow_url_fopen, to get the content of an external URI.
2045 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2046 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2048 function url_get_contents( $uri ) {
2049 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2050 return @file_get_contents($uri);
2052 require_once("lib/HttpClient.php");
2053 $bits = parse_url($uri);
2054 $host = $bits['host'];
2055 $port = isset($bits['port']) ? $bits['port'] : 80;
2056 $path = isset($bits['path']) ? $bits['path'] : '/';
2057 if (isset($bits['query'])) {
2058 $path .= '?'.$bits['query'];
2060 $client = new HttpClient($host, $port);
2061 $client->use_gzip = false;
2062 if (!$client->get($path)) {
2065 return $client->getContent();
2071 * Generate consecutively named strings:
2072 * Name, Name2, Name3, ...
2074 function GenerateId($name) {
2075 static $ids = array();
2076 if (empty($ids[$name])) {
2081 return $name . $ids[$name];
2085 // from IncludePage. To be of general use.
2086 // content: string or array of strings
2087 function firstNWordsOfContent( $n, $content ) {
2088 if ($content and $n > 0) {
2089 if (is_array($content)) {
2090 // fixme: return a list of lines then?
2091 //$content = join("\n", $content);
2092 //$return_array = true;
2094 foreach ($content as $line) {
2095 $words = explode(' ', $line);
2096 if ($wordcount + count($words) > $n) {
2097 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2098 . sprintf(_("... (first %s words)"), $n);
2101 $wordcount += count($words);
2107 // fixme: use better whitespace/word seperators
2108 $words = explode(' ', $content);
2109 if (count($words) > $n) {
2110 return join(' ', array_slice($words, 0, $n))
2111 . sprintf(_("... (first %s words)"), $n);
2121 // moved from lib/plugin/IncludePage.php
2122 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2123 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2125 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2126 . " \\s*$\\n?" // possible blank lines
2127 . " ( (?: ^.*\\n? )*? )" // some lines
2128 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2129 implode("\n", $content),
2131 // Strip trailing blanks lines and ---- <hr>s
2132 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2134 $text = $match[1] . $section ."\n". $text;
2135 return explode("\n", $text);
2138 $mesg = $page ." ". $section;
2141 return array(sprintf(_("<%s: no such section>"), $mesg));
2144 // Extract the first $sections sections of the page
2145 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2147 $mycontent = $content;
2150 while ($sections > 0) {
2152 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2153 . " \\s*$\\n?" // possible blank lines
2154 . " ( (?: ^.*\\n? )*? )" // some lines
2155 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2156 implode("\n", $mycontent),
2158 $section = $match[2];
2159 // Strip trailing blanks lines and ---- <hr>s
2160 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2162 $text = $match[1] . $section ."\n". $text;
2165 $mycontent = explode("\n", $match[4]);
2167 if ($sections === 0) {
2168 return explode("\n", $result);
2174 // use this faster version: only load ExternalReferrer if we came from an external referrer
2175 function isExternalReferrer(&$request) {
2176 if ($referrer = $request->get('HTTP_REFERER')) {
2177 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2178 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2179 require_once("lib/ExternalReferrer.php");
2180 $se = new SearchEngines();
2181 return $se->parseSearchQuery($referrer);
2183 //if (DEBUG) return array('query' => 'wiki');
2188 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2190 function loadPhpExtension($extension) {
2191 if (!extension_loaded($extension)) {
2192 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2193 $soname = ($isWindows ? 'php_' : '')
2195 . ($isWindows ? '.dll' : '.so');
2199 return extension_loaded($extension);
2202 function charset_convert($from, $to, $data) {
2204 //$wikicharset = strtolower($CHARSET);
2205 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2206 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2207 return utf8_decode($data);
2208 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2209 return utf8_encode($data);
2211 if (loadPhpExtension("iconv")) {
2212 $tmpdata = iconv($from, $to, $data);
2214 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2218 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2223 function string_starts_with($string, $prefix) {
2224 return (substr($string, 0, strlen($prefix)) == $prefix);
2226 function string_ends_with($string, $suffix) {
2227 return (substr($string, -strlen($suffix)) == $suffix);
2229 function array_remove($arr,$value) {
2230 return array_values(array_diff($arr,array($value)));
2234 * Ensure that the script will have another $secs time left.
2235 * Works only if safe_mode is off.
2236 * For example not to timeout on waiting socket connections.
2237 * Use the socket timeout as arg.
2239 function longer_timeout($secs = 30) {
2240 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2241 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2242 if ($timeleft < $secs)
2243 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2246 function printSimpleTrace($bt) {
2248 echo "\nTraceback:\n";
2249 if (function_exists('debug_print_backtrace')) { // >= 5
2250 debug_print_backtrace();
2252 foreach ($bt as $i => $elem) {
2253 if (!array_key_exists('file', $elem)) {
2256 //echo join(" ",array_values($elem)),"\n";
2257 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2263 * Return the used process memory, in bytes.
2264 * Enable the section which will work for you. They are very slow.
2265 * Special quirks for Windows: Requires cygwin.
2267 function getMemoryUsage() {
2268 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2269 if (function_exists('memory_get_usage') and memory_get_usage()) {
2270 return memory_get_usage();
2271 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2272 $mem = $u['ru_maxrss'];
2273 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2274 // what we want is the process memory only: apache or php (if CGI)
2277 // win32_ps_stat_proc, win32_ps_stat_mem
2278 if (function_exists('win32_ps_list_procs')) {
2279 $info = win32_ps_stat_proc($pid);
2280 $memstr = $info['mem']['working_set_size'];
2282 // This works only if it's a cygwin process (apache or php).
2283 // Requires a newer cygwin
2284 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2286 // if it's native windows use something like this:
2287 // (requires pslist from sysinternals.com, grep, sed and perl)
2288 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2290 return (integer) trim($memstr);
2293 //%MEM: Percentage of total memory in use by this process
2294 //VSZ: Total virtual memory size, in 1K blocks.
2295 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2296 //CPU time used by process since it started.
2297 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2298 $memstr = exec("ps -orss -p $pid|sed 1d");
2299 return (integer) trim($memstr);
2304 * @param var $needle
2305 * @param array $haystack one-dimensional numeric array only, no hash
2307 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2308 It will return false if not found or the index where it was found.
2309 From dennis.decoene@moveit.be http://www.php.net/array_search
2311 function binary_search($needle, $haystack) {
2312 $high = count($haystack);
2315 while (($high - $low) > 1) {
2316 $probe = floor(($high + $low) / 2);
2317 if ($haystack[$probe] < $needle) {
2319 } elseif ($haystack[$probe] == $needle) {
2320 $high = $low = $probe;
2326 if ($high == count($haystack) || $haystack[$high] != $needle) {
2333 function is_localhost($url = false) {
2335 global $HTTP_SERVER_VARS;
2336 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2341 * Take a string and quote it sufficiently to be passed as a Javascript
2342 * string between ''s
2344 function javascript_quote_string($s) {
2345 return str_replace("'", "\'", $s);
2348 function isSerialized($s) {
2349 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2353 * Take a string and return an array of pairs (attribute name, attribute value)
2355 * We allow attributes with or without double quotes (")
2356 * Attribute-value pairs may be separated by space or comma
2357 * Space is normal HTML attributes, comma is for RichTable compatibility
2358 * border=1, cellpadding="5"
2359 * border=1 cellpadding="5"
2360 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2361 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2363 function parse_attributes($line) {
2367 if (empty($line)) return $options;
2368 $line = trim($line);
2369 if (empty($line)) return $options;
2370 $line = trim($line, ",");
2371 if (empty($line)) return $options;
2373 // First we have an attribute name.
2378 while (($i < strlen($line)) && ($line[$i] != '=')) {
2381 $attribute = substr($line, 0, $i);
2382 $attribute = strtolower($attribute);
2384 $line = substr($line, $i+1);
2385 $line = trim ($line);
2386 $line = trim ($line, "=");
2387 $line = trim ($line);
2389 if (empty($line)) return $options;
2391 // Then we have the attribute value.
2394 // Attribute value might be between double quotes
2395 // In that case we have to find the closing double quote
2396 if ($line[0] == '"') {
2397 $i++; // skip first '"'
2398 while (($i < strlen($line)) && ($line[$i] != '"')) {
2401 $value = substr($line, 0, $i);
2402 $value = trim ($value, '"');
2403 $value = trim ($value);
2405 // If there are no double quotes, we have to find the next space or comma
2407 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2410 $value = substr($line, 0, $i);
2411 $value = trim ($value);
2412 $value = trim ($value, ",");
2413 $value = trim ($value);
2416 $options[$attribute] = $value;
2418 $line = substr($line, $i+1);
2419 $line = trim ($line);
2420 $line = trim ($line, ",");
2421 $line = trim ($line);
2423 return $options + parse_attributes($line);
2427 * Returns true if the filename ends with an image suffix.
2428 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2430 function is_image ($filename) {
2432 if (defined('INLINE_IMAGES')) {
2433 $inline_images = INLINE_IMAGES;
2435 $inline_images = "png|jpg|jpeg|gif";
2438 foreach (explode("|", $inline_images) as $suffix) {
2439 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2447 * Compute cell in spreadsheet table
2448 * $table: two-dimensional table
2449 * $i and $j: indexes of cell to compute
2450 * $imax and $jmax: table dimensions
2452 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2454 // What is implemented:
2455 // @@=SUM(R)@@ : sum of cells in current row
2456 // @@=SUM(C)@@ : sum of cells in current column
2457 // @@=AVERAGE(R)@@ : average of cells in current row
2458 // @@=AVERAGE(C)@@ : average of cells in current column
2459 // @@=MAX(R)@@ : maximum value of cells in current row
2460 // @@=MAX(C)@@ : maximum value of cells in current column
2461 // @@=MIN(R)@@ : minimum value of cells in current row
2462 // @@=MIN(C)@@ : minimum value of cells in current column
2463 // @@=COUNT(R)@@ : number of cells in current row
2464 // (numeric or not, excluding headers and current cell)
2465 // @@=COUNT(C)@@ : number of cells in current column
2466 // (numeric or not, excluding headers and current cell)
2472 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2473 for ($index=0; $index<$imax; $index++) {
2474 if (is_numeric($table[$index][$j])) {
2475 $result += $table[$index][$j];
2478 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2480 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2481 for ($index=0; $index<$jmax; $index++) {
2482 if (is_numeric($table[$i][$index])) {
2483 $result += $table[$i][$index];
2486 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2488 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2489 for ($index=0; $index<$imax; $index++) {
2490 if (is_numeric($table[$index][$j])) {
2491 $result += $table[$index][$j];
2495 $result=$result/$counter;
2496 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2498 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2499 for ($index=0; $index<$jmax; $index++) {
2500 if (is_numeric($table[$i][$index])) {
2501 $result += $table[$i][$index];
2505 $result=$result/$counter;
2506 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2508 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2509 for ($index=0; $index<$imax; $index++) {
2510 if (is_numeric($table[$index][$j])) {
2513 $result=$table[$index][$j];
2515 $result = max($result, $table[$index][$j]);
2522 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2524 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2525 for ($index=0; $index<$jmax; $index++) {
2526 if (is_numeric($table[$i][$index])) {
2529 $result=$table[$i][$index];
2531 $result = max($result, $table[$i][$index]);
2538 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2540 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2541 for ($index=0; $index<$imax; $index++) {
2542 if (is_numeric($table[$index][$j])) {
2545 $result=$table[$index][$j];
2547 $result = min($result, $table[$index][$j]);
2554 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2556 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2557 for ($index=0; $index<$jmax; $index++) {
2558 if (is_numeric($table[$i][$index])) {
2561 $result=$table[$i][$index];
2563 $result = min($result, $table[$i][$index]);
2570 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2572 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2573 for ($index=0; $index<$imax; $index++) {
2574 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2578 $result = $counter-1; // exclude self
2579 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2581 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2582 for ($index=0; $index<$jmax; $index++) {
2583 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2587 $result = $counter-1; // exclude self
2588 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2591 return $table[$i][$j];
2595 * Remove accents from given text.
2597 function strip_accents($text) {
2598 $res = utf8_decode($text);
2600 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2601 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2602 return utf8_encode($res);
2605 // (c-file-style: "gnu")
2609 // c-basic-offset: 4
2610 // c-hanging-comment-ender-p: nil
2611 // indent-tabs-mode: nil