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));
489 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
490 $url, $ori_url), E_USER_WARNING);
491 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
492 $file = substr($file, strlen(getUploadDataPath()));
493 $path = getUploadFilePath().$file;
494 if (file_exists($path)) {
495 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
496 $url, $ori_url), E_USER_WARNING);
497 $link->setAttr('src', getUploadDataPath() . $file);
502 if (!$link->getAttr('alt')) {
503 $link->setAttr('alt', $alt);
505 // Check width and height as spam countermeasure
506 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
507 //$width = (int) $width; // px or % or other suffix
508 //$height = (int) $height;
509 if (($width < 3 and $height < 10) or
510 ($height < 3 and $width < 20) or
511 ($height < 7 and $width < 7))
513 trigger_error(_("Invalid image size"), E_USER_WARNING);
518 // Prepare for getimagesize($url)
519 // $url only valid for external urls, otherwise local path
520 // Older php versions crash here with certain png's:
521 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
522 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
523 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
524 if (DISABLE_GETIMAGESIZE)
526 elseif (! preg_match("/\.$force_img$/i", $url))
527 ; // only valid image extensions or scripts assumed to generate images
528 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
529 ; // it's safe to assume that this will fail.
530 elseif (preg_match("/^http/",$url)) { // external url
531 $size = @getimagesize($url);
532 } else { // local file
533 if (file_exists($file = NormalizeLocalFileName($url))) { // here
534 $size = @getimagesize($file);
535 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
536 $size = @getimagesize($file);
537 $link->setAttr('src', rawurldecode($url));
538 } elseif (string_starts_with($url, getUploadDataPath())) { // there
539 $file = substr($file, strlen(getUploadDataPath()));
540 $path = getUploadFilePath().rawurldecode($file);
541 $size = @getimagesize($path);
542 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
543 } else { // elsewhere
544 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
550 if (($width < 3 and $height < 10)
551 or ($height < 3 and $width < 20)
552 or ($height < 7 and $width < 7))
554 trigger_error(_("Invalid image size"), E_USER_WARNING);
559 $link->setAttr('class', 'inlineimage');
561 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
562 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
563 * Note: Allow cgi's (pl,cgi) returning images.
565 if (!preg_match("/\.(".$force_img.")/i", $url)) {
566 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
567 // => HTML::object(array('src' => $url)) ...;
568 return ImgObject($link, $ori_url);
574 * <object> / <embed> tags instead of <img> for all non-image extensions
576 * Called by LinkImage(), not directly.
577 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
578 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
579 * $alt may be an alternate img
580 * TODO: Need to unify with WikiPluginCached::embedObject()
582 * Note that Safari 1.0 will crash with <object>, so use only <embed>
583 * http://www.alleged.org.uk/pdc/2002/svg-object.html
585 * Allowed object tags:
586 * DATA=URI (object data)
587 * CLASSID=URI (location of implementation)
588 * ARCHIVE=CDATA (archive files)
589 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
590 * WIDTH=Length (object width)
591 * HEIGHT=Length (object height)
592 * NAME=CDATA (name for form submission)
593 * USEMAP=URI (client-side image map)
594 * TYPE=ContentType (content-type of object)
595 * CODETYPE=ContentType (content-type of code)
596 * STANDBY=Text (message to show while loading)
597 * TABINDEX=NUMBER (position in tabbing order)
598 * DECLARE (do not instantiate object)
599 * The rest is added as <param name="" value="" /> tags
601 function ImgObject($img, $url) {
602 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
603 $args = split(' ', $url);
605 if (count($args) >= 1) {
606 $url = array_shift($args);
608 foreach ($args as $attr) {
609 foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
610 "codetype,standby,tabindex,declare") as $param)
612 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
613 $img->setAttr($param, $m[1]);
619 // now all remaing args are added as <param> to the object
620 foreach ($args as $attr) {
621 if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
622 $params[] = HTML::param(array('name' => $m[1],
627 $type = $img->getAttr('type');
629 // TODO: map extension to mime-types if type is not given and php < 4.3
630 if (function_exists('mime_content_type'))
631 $type = mime_content_type($url);
633 $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
635 $object->setAttr('class', 'inlineobject');
637 foreach ($params as $param) $object->pushContent($param);
639 if (isBrowserSafari()) {
640 return HTML::embed($object->_attr, $object->_content);
642 $object->pushContent(HTML::embed($object->_attr));
649 // var in php5 deprecated
651 $this->items = array();
654 function push($item) {
655 $this->items[$this->size] = $item;
661 if ($this->size == 0) {
662 return false; // stack is empty
665 return $this->items[$this->size];
674 return $this->items[$this->size - 1];
680 // end class definition
682 function SplitQueryArgs ($query_args = '')
684 // FIXME: use the arg-seperator which might not be &
685 $split_args = split('&', $query_args);
687 while (list($key, $val) = each($split_args))
688 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
689 $args[$m[1]] = $m[2];
693 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
696 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
697 return HTML::strong(array('class' => 'rawurl'),
698 HTML::u(array('class' => 'baduri'),
699 _("BAD phpwiki: URL")));
703 $pagename = urldecode($m[1]);
706 if (empty($pagename) &&
707 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
708 // Convert old style links (to not break diff links in
710 $pagename = urldecode($m[2]);
711 $args = array("action" => $m[1]);
714 $args = SplitQueryArgs($qargs);
717 if (empty($pagename))
718 $pagename = $GLOBALS['request']->getArg('pagename');
720 if (isset($args['action']) && $args['action'] == 'browse')
721 unset($args['action']);
724 if (empty($args['action']))
726 else if (is_safe_action($args['action']))
727 $class = 'wikiaction';
729 if (empty($args['action']) || is_safe_action($args['action']))
730 $class = 'wikiaction';
732 // Don't allow administrative links on unlocked pages.
733 $dbi = $GLOBALS['request']->getDbh();
734 $page = $dbi->getPage($basepage ? $basepage : $pagename);
735 if (!$page->get('locked'))
736 return HTML::span(array('class' => 'wikiunsafe'),
737 HTML::u(_("Lock page to enable link")));
738 $class = 'wikiadmin';
742 $text = HTML::span(array('class' => 'rawurl'), $url);
744 $wikipage = new WikiPageName($pagename);
745 if (!$wikipage->isValid()) {
747 return $WikiTheme->linkBadWikiWord($wikipage, $url);
750 return HTML::a(array('href' => WikiURL($pagename, $args),
756 * A class to assist in parsing wiki pagenames.
758 * Now with subpages and anchors, parsing and passing around
759 * pagenames is more complicated. This should help.
763 /** Short name for page.
765 * This is the value of $name passed to the constructor.
766 * (For use, e.g. as a default label for links to the page.)
770 /** The full page name.
772 * This is the full name of the page (without anchor).
778 * This is the referenced anchor within the page, or the empty string.
784 * @param mixed $name Page name.
785 * WikiDB_Page, WikiDB_PageRevision, or string.
786 * This can be a relative subpage name (like '/SubPage'),
787 * or can be the empty string to refer to the $basename.
789 * @param string $anchor For links to anchors in page.
791 * @param mixed $basename Page name from which to interpret
792 * relative or other non-fully-specified page names.
794 function WikiPageName($name, $basename=false, $anchor=false) {
795 if (is_string($name)) {
796 $this->shortName = $name;
797 if (strstr($name, ':')) {
798 list($moniker, $shortName) = split (":", $name, 2);
799 $map = getInterwikiMap(); // allow overrides to custom maps
800 if (isset($map->_map[$moniker])) {
801 $url = $map->_map[$moniker];
802 if (strstr($url, '%s'))
803 $url = sprintf($url, $shortName);
807 // expand Talk or User, but not to absolute urls!
808 if (strstr($url, '//')) {
809 if ($moniker == 'Talk')
810 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
811 elseif ($moniker == 'User')
816 if (strstr($shortName, '?')) {
817 list($shortName, $dummy) = split("\?", $shortName, 2);
819 $this->shortName = $shortName;
822 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
823 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
825 $name = $this->_pagename($basename) . $name;
827 $name = $this->_normalize_bad_pagename($name);
828 $this->shortName = $name;
833 $name = $this->_pagename($name);
834 $this->shortName = $name;
837 $this->name = $this->_check($name);
838 $this->anchor = (string)$anchor;
845 function getParent() {
847 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
849 return substr($name, 0, -strlen($tail));
852 function isValid($strict = false) {
854 return !isset($this->_errors);
855 return (is_string($this->name) and $this->name != '');
858 function getWarnings() {
860 if (isset($this->_warnings))
861 $warnings = array_merge($warnings, $this->_warnings);
862 if (isset($this->_errors))
863 $warnings = array_merge($warnings, $this->_errors);
867 return sprintf(_("'%s': Bad page name: %s"),
868 $this->shortName, join(', ', $warnings));
871 function _pagename($page) {
872 if (isa($page, 'WikiDB_Page'))
873 return $page->getName();
874 elseif (isa($page, 'WikiDB_PageRevision'))
875 return $page->getPageName();
876 elseif (isa($page, 'WikiPageName'))
878 // '0' or e.g. '1984' should be allowed though
879 if (!is_string($page) and !is_integer($page)) {
880 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
881 $page, gettype($page), get_class($page)),
884 //assert(is_string($page));
888 function _normalize_bad_pagename($name) {
889 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
891 // Punt... You really shouldn't get here.
894 return $request->getArg('pagename');
896 assert($name[0] == SUBPAGE_SEPARATOR);
897 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
898 return substr($name, 1);
902 * Compress internal white-space to single space character.
904 * This leads to problems with loading a foreign charset pagename,
905 * which cannot be deleted anymore, because unknown chars are compressed.
906 * So BEFORE importing a file _check must be done !!!
908 function _check($pagename) {
909 // Compress internal white-space to single space character.
910 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
911 if ($pagename != $orig)
912 $this->_warnings[] = _("White space converted to single space");
914 // Delete any control characters.
915 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
916 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
917 if ($pagename != $orig)
918 $this->_errors[] = _("Control characters not allowed");
921 // Strip leading and trailing white-space.
922 $pagename = trim($pagename);
925 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
926 $pagename = substr($pagename, 1);
927 if ($pagename != $orig)
928 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
930 // ";" is urlencoded, so safe from php arg-delim problems
931 /*if (strstr($pagename, ';')) {
932 $this->_warnings[] = _("';' is deprecated");
933 $pagename = str_replace(';', '', $pagename);
936 // not only for SQL, also to restrict url length
937 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
938 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
939 $this->_errors[] = _("too long");
942 // disallow some chars only on file and cvs
943 if ((DATABASE_TYPE == 'cvs'
944 or DATABASE_TYPE == 'file'
945 or DATABASE_TYPE == 'flatfile')
946 and preg_match('/(:|\.\.)/', $pagename, $m))
948 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
949 $pagename = str_replace('..', '', $pagename);
950 $pagename = str_replace(':', '', $pagename);
958 * Convert old page markup to new-style markup.
960 * @param string $text Old-style wiki markup.
962 * @param string $markup_type
964 * <dt><code>"block"</code> <dd>Convert all markup.
965 * <dt><code>"inline"</code> <dd>Convert only inline markup.
966 * <dt><code>"links"</code> <dd>Convert only link markup.
969 * @return string New-style wiki markup.
971 * @bugs Footnotes don't work quite as before (esp if there are
972 * multiple references to the same footnote. But close enough,
973 * probably for now....
974 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
975 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
976 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
977 * also known to crash, even with Apache1.
979 function ConvertOldMarkup ($text, $markup_type = "block") {
985 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
986 // AnciennesR%E8glesDeFormatage crashes.
987 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
988 // also known to crash, even with Apache1.
990 // I suspect this only to crash with Apache2 and IIS.
991 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
992 and preg_match("/plugin CreateToc/", $text))
994 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
995 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
996 ._("Skipped."), E_USER_WARNING);
998 //if (!DEBUG) return $text;
1003 /*****************************************************************
1004 * Conversions for inline markup:
1011 // escape escaped brackets
1015 // change ! escapes to ~'s.
1016 global $WikiNameRegexp, $request;
1017 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1018 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1019 if (check_php_version(4,3,9)) {
1020 $map = getInterwikiMap();
1021 if ($map_regex = $map->getRegexp())
1022 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1024 $bang_esc[] = $WikiNameRegexp;
1025 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1028 $subs["links"] = array($orig, $repl);
1030 // Temporarily URL-encode pairs of underscores in links to hide
1031 // them from the re for bold markup.
1032 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1033 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1036 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1039 // Convert footnote references.
1040 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1041 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1043 // Convert old style emphases to HTML style emphasis.
1044 $orig[] = '/__(.*?)__/';
1045 $repl[] = '<strong>\\1</strong>';
1046 $orig[] = "/''(.*?)''/";
1047 $repl[] = '<em>\\1</em>';
1049 // Escape nestled markup.
1050 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1053 // in old markup headings only allowed at beginning of line
1057 // Convert URL-encoded pairs of underscores in links back to
1058 // real underscores after bold markup has been converted.
1059 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1060 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1062 $subs["inline"] = array($orig, $repl);
1064 /*****************************************************************
1065 * Patterns which match block markup constructs which take
1066 * special handling...
1070 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1072 $blockpats[] = '\|(?:.*\n\|)*';
1075 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1077 // Footnote definitions
1078 $blockpats[] = '\[\s*(\d+)\s*\]';
1082 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1086 $blockpats[] = '!{1,3}[^!]';
1088 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1089 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1091 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1092 . join("|", $blockpats)
1097 if ($markup_type != "block") {
1098 list ($orig, $repl) = $subs[$markup_type];
1099 return preg_replace($orig, $repl, $text);
1102 list ($orig, $repl) = $subs['inline'];
1105 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1106 // AnciennesR%E8glesDeFormatage and more
1107 // See http://www.pcre.org/pcre.txt LIMITATIONS
1108 while (preg_match($block_re, $text, $m)) {
1109 $text = substr($text, strlen($m[0]));
1110 list (,$leading_text, $block) = $m;
1113 if (strchr(" \t", $block[0])) {
1115 $prefix = "<pre>\n";
1116 $suffix = "\n</pre>\n";
1118 elseif ($block[0] == '|') {
1120 $prefix = "<?plugin OldStyleTable\n";
1123 elseif (strchr("#*;", $block[0])) {
1124 // Old-style list item
1125 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1126 list (,$ind,$bullet) = $m;
1127 $block = substr($block, strlen($m[0]));
1129 $indent = str_repeat(' ', strlen($ind));
1130 if ($bullet[0] == ';') {
1131 //$term = ltrim(substr($bullet, 1));
1132 //return $indent . $term . "\n" . $indent . ' ';
1133 $prefix = $ind . $bullet;
1136 $prefix = $indent . $bullet . ' ';
1138 elseif ($block[0] == '[') {
1139 // Footnote definition
1140 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1142 $block = substr($block, strlen($m[0]));
1143 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1145 elseif ($block[0] == '<') {
1147 // HACK: no inline markup...
1151 elseif ($block[0] == '!') {
1153 preg_match('/^!{1,3}/', $block, $m);
1155 $block = substr($block, strlen($m[0]));
1161 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1162 if ($block) $block = preg_replace($orig, $repl, $block);
1163 $out .= $leading_text;
1168 return $out . preg_replace($orig, $repl, $text);
1174 * Expand tabs in string.
1176 * Converts all tabs to (the appropriate number of) spaces.
1178 * @param string $str
1179 * @param integer $tab_width
1182 function expand_tabs($str, $tab_width = 8) {
1183 $split = split("\t", $str);
1184 $tail = array_pop($split);
1186 foreach ($split as $hunk) {
1188 $pos = strlen(strrchr($expanded, "\n")) - 1;
1189 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1191 return substr($expanded, 1) . $tail;
1195 * Split WikiWords in page names.
1197 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1198 * places like page titles. This is rumored to help search engines
1201 * @param $page string The page name.
1203 * @return string The split name.
1205 function SplitPagename ($page) {
1207 if (preg_match("/\s/", $page))
1208 return $page; // Already split --- don't split any more.
1210 // This algorithm is specialized for several languages.
1211 // (Thanks to Pierrick MEIGNEN)
1212 // Improvements for other languages welcome.
1215 // This mess splits between a lower-case letter followed by
1216 // either an upper-case or a numeral; except that it wont
1217 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1218 switch ($GLOBALS['LANG']) {
1223 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1226 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1229 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1230 // This the single-letter words 'I' and 'A' from any following
1231 // capitalized words.
1232 switch ($GLOBALS['LANG']) {
1234 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1237 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1240 // Split at underscore
1241 $RE[] = '/(_)([[:alpha:]])/';
1242 $RE[] = '/([[:alpha:]])(_)/';
1243 // Split numerals from following letters.
1244 $RE[] = '/(\d)([[:alpha:]])/';
1245 // Split at subpage seperators. TBD in WikiTheme.php
1246 $RE[] = "/([^${sep}]+)(${sep})/";
1247 $RE[] = "/(${sep})([^${sep}]+)/";
1249 foreach ($RE as $key)
1250 $RE[$key] = pcre_fix_posix_classes($key);
1253 foreach ($RE as $regexp) {
1254 $page = preg_replace($regexp, '\\1 \\2', $page);
1259 function NoSuchRevision (&$request, $page, $version) {
1260 $html = HTML(HTML::h2(_("Revision Not Found")),
1261 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1262 $version, WikiLink($page, 'auto'))));
1263 include_once('lib/Template.php');
1264 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1270 * Get time offset for local time zone.
1272 * @param $time time_t Get offset for this time. Default: now.
1273 * @param $no_colon boolean Don't put colon between hours and minutes.
1274 * @return string Offset as a string in the format +HH:MM.
1276 function TimezoneOffset ($time = false, $no_colon = false) {
1277 if ($time === false)
1279 $secs = date('Z', $time);
1288 $colon = $no_colon ? '' : ':';
1289 $mins = intval(($secs + 30) / 60);
1290 return sprintf("%s%02d%s%02d",
1291 $sign, $mins / 60, $colon, $mins % 60);
1296 * Format time in ISO-8601 format.
1298 * @param $time time_t Time. Default: now.
1299 * @return string Date and time in ISO-8601 format.
1301 function Iso8601DateTime ($time = false) {
1302 if ($time === false)
1304 $tzoff = TimezoneOffset($time);
1305 $date = date('Y-m-d', $time);
1306 $time = date('H:i:s', $time);
1307 return $date . 'T' . $time . $tzoff;
1311 * Format time in RFC-2822 format.
1313 * @param $time time_t Time. Default: now.
1314 * @return string Date and time in RFC-2822 format.
1316 function Rfc2822DateTime ($time = false) {
1317 if ($time === false)
1319 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1323 * Format time in RFC-1123 format.
1325 * @param $time time_t Time. Default: now.
1326 * @return string Date and time in RFC-1123 format.
1328 function Rfc1123DateTime ($time = false) {
1329 if ($time === false)
1331 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1334 /** Parse date in RFC-1123 format.
1336 * According to RFC 1123 we must accept dates in the following
1339 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1340 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1341 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1343 * (Though we're only allowed to generate dates in the first format.)
1345 function ParseRfc1123DateTime ($timestr) {
1346 $timestr = trim($timestr);
1347 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1348 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1350 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1352 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1353 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1355 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1356 if ($year < 70) $year += 2000;
1357 elseif ($year < 100) $year += 1900;
1359 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1360 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1362 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1369 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1371 return false; // failed
1376 * Format time to standard 'ctime' format.
1378 * @param $time time_t Time. Default: now.
1379 * @return string Date and time.
1381 function CTime ($time = false)
1383 if ($time === false)
1385 return date("D M j H:i:s Y", $time);
1390 * Format number as kilobytes or bytes.
1391 * Short format is used for PageList
1392 * Long format is used in PageInfo
1394 * @param $bytes int. Default: 0.
1395 * @param $longformat bool. Default: false.
1396 * @return class FormattedText (XmlElement.php).
1398 function ByteFormatter ($bytes = 0, $longformat = false) {
1401 if ($bytes < 1024) {
1403 $size = fmt("%s b", $bytes);
1405 $size = fmt("%s bytes", $bytes);
1408 $kb = round($bytes / 1024, 1);
1410 $size = fmt("%s k", $kb);
1412 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1418 * Internationalized printf.
1420 * This is essentially the same as PHP's built-in printf
1421 * with the following exceptions:
1423 * <li> It passes the format string through gettext().
1424 * <li> It supports the argument reordering extensions.
1431 * __printf("Differences between versions %s and %s of %s",
1432 * $new_link, $old_link, $page_link);
1435 * Then in locale/po/de.po, one can reorder the printf arguments:
1438 * msgid "Differences between %s and %s of %s."
1439 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1442 * (Note that while PHP tries to expand $vars within double-quotes,
1443 * the values in msgstr undergo no such expansion, so the '$'s
1446 * One shouldn't use reordered arguments in the default format string.
1447 * Backslashes in the default string would be necessary to escape the
1448 * '$'s, and they'll cause all kinds of trouble....
1450 function __printf ($fmt) {
1451 $args = func_get_args();
1453 echo __vsprintf($fmt, $args);
1457 * Internationalized sprintf.
1459 * This is essentially the same as PHP's built-in printf with the
1460 * following exceptions:
1463 * <li> It passes the format string through gettext().
1464 * <li> It supports the argument reordering extensions.
1469 function __sprintf ($fmt) {
1470 $args = func_get_args();
1472 return __vsprintf($fmt, $args);
1476 * Internationalized vsprintf.
1478 * This is essentially the same as PHP's built-in printf with the
1479 * following exceptions:
1482 * <li> It passes the format string through gettext().
1483 * <li> It supports the argument reordering extensions.
1488 function __vsprintf ($fmt, $args) {
1489 $fmt = gettext($fmt);
1490 // PHP's sprintf doesn't support variable with specifiers,
1491 // like sprintf("%*s", 10, "x"); --- so we won't either.
1493 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1494 // Format string has '%2$s' style argument reordering.
1495 // PHP doesn't support this.
1496 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1497 // literal variable name substitution only to keep locale
1498 // strings uncluttered
1499 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1500 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1502 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1505 // Reorder arguments appropriately.
1506 foreach($m[1] as $argnum) {
1507 if ($argnum < 1 || $argnum > count($args))
1508 trigger_error(sprintf(_("%s: argument index out of range"),
1509 $argnum), E_USER_WARNING);
1510 $newargs[] = $args[$argnum - 1];
1515 // Not all PHP's have vsprintf, so...
1516 array_unshift($args, $fmt);
1517 return call_user_func_array('sprintf', $args);
1520 function file_mtime ($filename) {
1521 if ($stat = @stat($filename))
1527 function sort_file_mtime ($a, $b) {
1528 $ma = file_mtime($a);
1529 $mb = file_mtime($b);
1530 if (!$ma or !$mb or $ma == $mb) return 0;
1531 return ($ma > $mb) ? -1 : 1;
1536 * Build an array in $this->_fileList of files from $dirname.
1537 * Subdirectories are not traversed.
1539 * (This was a function LoadDir in lib/loadsave.php)
1540 * See also http://www.php.net/manual/en/function.readdir.php
1542 function getFiles($exclude='', $sortby='', $limit='') {
1543 $list = $this->_fileList;
1546 require_once('lib/PageList.php');
1547 switch (Pagelist::sortby($sortby, 'db')) {
1548 case 'pagename ASC': break;
1549 case 'pagename DESC':
1550 $list = array_reverse($list);
1553 usort($list,'sort_file_mtime');
1556 usort($list,'sort_file_mtime');
1557 $list = array_reverse($list);
1562 return array_splice($list, 0, $limit);
1566 function _filenameSelector($filename) {
1567 if (! $this->_pattern )
1570 if (! $this->_pcre_pattern )
1571 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1572 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1577 function fileSet($directory, $filepattern = false) {
1578 $this->_fileList = array();
1579 $this->_pattern = $filepattern;
1581 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1583 $this->_case = !isWindows();
1584 $this->_pathsep = '/';
1586 if (empty($directory)) {
1587 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1589 return; // early return
1592 @ $dir_handle = opendir($dir=$directory);
1593 if (empty($dir_handle)) {
1594 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1595 $dir), E_USER_NOTICE);
1596 return; // early return
1599 while ($filename = readdir($dir_handle)) {
1600 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1602 if ($this->_filenameSelector($filename)) {
1603 array_push($this->_fileList, "$filename");
1604 //trigger_error(sprintf(_("found file %s"), $filename),
1605 // E_USER_NOTICE); //debugging
1608 closedir($dir_handle);
1614 // expands a list containing regex's to its matching entries
1615 class ListRegexExpand {
1616 //var $match, $list, $index, $case_sensitive;
1617 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1618 $this->match = $match;
1619 $this->list = &$list;
1620 $this->case_sensitive = $case_sensitive;
1621 //$this->index = false;
1623 function listMatchCallback ($item, $key) {
1624 $quoted = str_replace('/','\/',$item);
1625 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1627 unset($this->list[$this->index]);
1628 $this->list[] = $item;
1631 function expandRegex ($index, &$pages) {
1632 $this->index = $index;
1633 array_walk($pages, array($this, 'listMatchCallback'));
1638 // Convert fileglob to regex style:
1639 // Convert some wildcards to pcre style, escape the rest
1640 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1641 // Fixed bug #994994: "/" in $glob.
1642 function glob_to_pcre ($glob) {
1643 // check simple case: no need to escape
1644 $escape = '\[](){}=!<>|:/';
1645 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1647 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1648 $glob = strtr($glob, "\\", "\xff");
1649 $glob = str_replace("/", "\\/", $glob);
1650 // first convert some unescaped expressions to pcre style: . => \.
1652 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1653 "\\1\xff\\2", $glob);
1656 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1657 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1658 if (!preg_match('/^[\?\*]/', $glob))
1660 if (!preg_match('/[\?\*]$/', $glob))
1663 // Fixes Bug 1182997
1664 // .*? handled above, now escape the rest
1665 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1666 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1668 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1670 $re = preg_replace('/\xff/', '', $re);
1674 function glob_match ($glob, $against, $case_sensitive = true) {
1675 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1679 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1680 $list = explode(',',$input);
1681 // expand wildcards from list of $allnames
1682 if (preg_match('/[\?\*]/',$input)) {
1683 // Optimizing loop invariants:
1684 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1685 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1687 if (preg_match('/[\?\*]/',$f)) {
1689 $expand = new ListRegexExpand($list,
1690 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1691 $expand->expandRegex($i, $allnames);
1698 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1699 function explodePageList($input, $include_empty=false, $sortby='pagename',
1700 $limit='', $exclude='') {
1701 include_once("lib/PageList.php");
1702 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1705 // Class introspections
1708 * Determine whether object is of a specified type.
1709 * In PHP builtin since 4.2.0 as is_a()
1710 * is_a() deprecated in PHP 5, in favor of instanceof operator
1712 * @param $object object An object.
1713 * @param $class string Class name.
1714 * @return bool True iff $object is a $class
1715 * or a sub-type of $class.
1717 function isa ($object, $class) {
1718 //if (check_php_version(5))
1719 // return $object instanceof $class;
1720 if (check_php_version(4,2) and !check_php_version(5))
1721 return is_a($object, $class);
1723 $lclass = check_php_version(5) ? $class : strtolower($class);
1724 return is_object($object)
1725 && ( strtolower(get_class($object)) == strtolower($class)
1726 || is_subclass_of($object, $lclass) );
1729 /** Determine whether (possible) object has method.
1731 * @param $object mixed Object
1732 * @param $method string Method name
1733 * @return bool True iff $object is an object with has method $method.
1735 function can ($object, $method) {
1736 return is_object($object) && method_exists($object, strtolower($method));
1739 /** Determine whether a function is okay to use.
1741 * Some providers (e.g. Lycos) disable some of PHP functions for
1742 * "security reasons." This makes those functions, of course,
1743 * unusable, despite the fact the function_exists() says they
1746 * This function test to see if a function exists and is not
1747 * disallowed by PHP's disable_functions config setting.
1749 * @param string $function_name Function name
1750 * @return bool True iff function can be used.
1752 function function_usable($function_name) {
1754 if (!is_array($disabled)) {
1755 $disabled = array();
1756 // Use get_cfg_var since ini_get() is one of the disabled functions
1757 // (on Lycos, at least.)
1758 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1759 foreach ($split as $f)
1760 $disabled[strtolower($f)] = true;
1763 return ( function_exists($function_name)
1764 and ! isset($disabled[strtolower($function_name)])
1771 * This is used for generating ETags.
1773 function wikihash ($x) {
1774 if (is_scalar($x)) {
1777 elseif (is_array($x)) {
1779 return md5(serialize($x));
1781 elseif (is_object($x)) {
1784 trigger_error("Can't hash $x", E_USER_ERROR);
1789 * Seed the random number generator.
1791 * better_srand() ensures the randomizer is seeded only once.
1793 * How random do you want it? See:
1794 * http://www.php.net/manual/en/function.srand.php
1795 * http://www.php.net/manual/en/function.mt-srand.php
1797 function better_srand($seed = '') {
1798 static $wascalled = FALSE;
1800 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1801 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1803 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1807 function rand_ascii($length = 1) {
1810 for ($i = 1; $i <= $length; $i++) {
1811 // return only typeable 7 bit ascii, avoid quotes
1812 if (function_exists('mt_rand'))
1813 $s .= chr(mt_rand(40, 126));
1815 // the usually bad glibc srand()
1816 $s .= chr(rand(40, 126));
1821 /* by Dan Frankowski.
1823 function rand_ascii_readable ($length = 6) {
1824 // Pick a few random letters or numbers
1827 // Don't use 1lI0O, because they're hard to read
1828 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1829 $letter_len = strlen($letters);
1830 for ($i=0; $i < $length; $i++) {
1831 if (function_exists('mt_rand'))
1832 $word .= $letters[mt_rand(0, $letter_len-1)];
1834 $word .= $letters[rand(0, $letter_len-1)];
1840 * Recursively count all non-empty elements
1841 * in array of any dimension or mixed - i.e.
1842 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1843 * See http://www.php.net/manual/en/function.count.php
1845 function count_all($arg) {
1846 // skip if argument is empty
1848 //print_r($arg); //debugging
1850 // not an array, return 1 (base case)
1853 // else call recursively for all elements $arg
1854 foreach($arg as $key => $val)
1855 $count += count_all($val);
1860 function isSubPage($pagename) {
1861 return (strstr($pagename, SUBPAGE_SEPARATOR));
1864 function subPageSlice($pagename, $pos) {
1865 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1866 $pages = array_slice($pages,$pos,1);
1873 * Class for "popping up" and alert box. (Except that right now, it doesn't
1877 * This is a hackish and needs to be refactored. However it would be nice to
1878 * unify all the different methods we use for showing Alerts and Dialogs.
1879 * (E.g. "Page deleted", login form, ...)
1884 * @param object $request
1885 * @param mixed $head Header ("title") for alert box.
1886 * @param mixed $body The text in the alert box.
1887 * @param hash $buttons An array mapping button labels to URLs.
1888 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1890 function Alert($head, $body, $buttons=false) {
1891 if ($buttons === false)
1894 if (is_array($body)) {
1896 foreach ($body as $li) {
1897 $html->pushContent(HTML::li($li));
1901 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1902 $this->_buttons = $buttons;
1906 * Show the alert box.
1911 $tokens = $this->_tokens;
1912 $tokens['BUTTONS'] = $this->_getButtons();
1914 $request->discardOutput();
1915 $tmpl = new Template('dialog', $request, $tokens);
1921 function _getButtons() {
1924 $buttons = $this->_buttons;
1926 $buttons = array(_("Okay") => $request->getURLtoSelf());
1929 foreach ($buttons as $label => $url)
1930 print "$label $url\n";
1931 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1932 return new XmlContent($out);
1937 // 1.3.9-p1 => 1030.091
1938 // 1.3.10pre => 1030.099
1939 // 1.3.11pre-20041120 => 1030.1120041120
1940 // 1.3.12-rc1 => 1030.119
1941 function phpwiki_version() {
1942 static $PHPWIKI_VERSION;
1943 if (!isset($PHPWIKI_VERSION)) {
1944 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1945 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1946 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1947 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1948 $PHPWIKI_VERSION -= 0.01;
1950 return $PHPWIKI_VERSION;
1953 function phpwiki_gzhandler($ob) {
1954 if (function_exists('gzencode'))
1955 $ob = gzencode($ob);
1956 $GLOBALS['request']->_ob_get_length = strlen($ob);
1957 if (!headers_sent()) {
1958 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1963 function isWikiWord($word) {
1964 global $WikiNameRegexp;
1965 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1966 return preg_match("/^$WikiNameRegexp\$/",$word);
1969 // needed to store serialized objects-values only (perm, pref)
1970 function obj2hash ($obj, $exclude = false, $fields = false) {
1972 if (! $fields ) $fields = get_object_vars($obj);
1973 foreach ($fields as $key => $val) {
1974 if (is_array($exclude)) {
1975 if (in_array($key, $exclude)) continue;
1983 * isUtf8String($string) - cheap utf-8 detection
1985 * segfaults for strings longer than 10kb!
1986 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1987 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1989 function isUtf8String( $s ) {
1990 $ptrASCII = '[\x00-\x7F]';
1991 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1992 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1993 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1994 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1995 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1996 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2000 * Check for UTF-8 URLs; Internet Explorer produces these if you
2001 * type non-ASCII chars in the URL bar or follow unescaped links.
2002 * Requires urldecoded pagename.
2003 * Fixes sf.net bug #953949
2005 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2007 function fixTitleEncoding( $s ) {
2012 if (empty($s)) return $s;
2014 $ishigh = preg_match( '/[\x80-\xff]/', $s);
2016 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2017 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
2019 $isutf = ($ishigh ? isUtf8String($s) : true);
2020 $locharset = strtolower($charset);
2022 if( $locharset != "utf-8" and $ishigh and $isutf )
2023 $s = charset_convert('UTF-8', $locharset, $s);
2024 if ($locharset == "utf-8" and $ishigh and !$isutf )
2025 return utf8_encode( $s );
2027 // Other languages can safely leave this function, or replace
2028 // it with one to detect and convert another legacy encoding.
2033 * MySQL fulltext index doesn't grok utf-8, so we
2034 * need to fold cases and convert to hex.
2035 * src: languages/Language.php:stripForSearch() from mediawiki
2038 function stripForSearch( $string ) {
2039 global $wikiLowerChars;
2040 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2041 return preg_replace(
2042 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2043 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2049 * Workaround for allow_url_fopen, to get the content of an external URI.
2050 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2051 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2053 function url_get_contents( $uri ) {
2054 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2055 return @file_get_contents($uri);
2057 require_once("lib/HttpClient.php");
2058 $bits = parse_url($uri);
2059 $host = $bits['host'];
2060 $port = isset($bits['port']) ? $bits['port'] : 80;
2061 $path = isset($bits['path']) ? $bits['path'] : '/';
2062 if (isset($bits['query'])) {
2063 $path .= '?'.$bits['query'];
2065 $client = new HttpClient($host, $port);
2066 $client->use_gzip = false;
2067 if (!$client->get($path)) {
2070 return $client->getContent();
2076 * Generate consecutively named strings:
2077 * Name, Name2, Name3, ...
2079 function GenerateId($name) {
2080 static $ids = array();
2081 if (empty($ids[$name])) {
2086 return $name . $ids[$name];
2090 // from IncludePage. To be of general use.
2091 // content: string or array of strings
2092 function firstNWordsOfContent( $n, $content ) {
2093 if ($content and $n > 0) {
2094 if (is_array($content)) {
2095 // fixme: return a list of lines then?
2096 //$content = join("\n", $content);
2097 //$return_array = true;
2099 foreach ($content as $line) {
2100 $words = explode(' ', $line);
2101 if ($wordcount + count($words) > $n) {
2102 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2103 . sprintf(_("... (first %s words)"), $n);
2106 $wordcount += count($words);
2112 // fixme: use better whitespace/word seperators
2113 $words = explode(' ', $content);
2114 if (count($words) > $n) {
2115 return join(' ', array_slice($words, 0, $n))
2116 . sprintf(_("... (first %s words)"), $n);
2126 // moved from lib/plugin/IncludePage.php
2127 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2128 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2130 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2131 . " \\s*$\\n?" // possible blank lines
2132 . " ( (?: ^.*\\n? )*? )" // some lines
2133 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2134 implode("\n", $content),
2136 // Strip trailing blanks lines and ---- <hr>s
2137 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2139 $text = $match[1] . $section ."\n". $text;
2140 return explode("\n", $text);
2143 $mesg = $page ." ". $section;
2146 return array(sprintf(_("<%s: no such section>"), $mesg));
2149 // Extract the first $sections sections of the page
2150 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2152 $mycontent = $content;
2155 while ($sections > 0) {
2157 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2158 . " \\s*$\\n?" // possible blank lines
2159 . " ( (?: ^.*\\n? )*? )" // some lines
2160 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2161 implode("\n", $mycontent),
2163 $section = $match[2];
2164 // Strip trailing blanks lines and ---- <hr>s
2165 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2167 $text = $match[1] . $section ."\n". $text;
2170 $mycontent = explode("\n", $match[4]);
2172 if ($sections === 0) {
2173 return explode("\n", $result);
2179 // use this faster version: only load ExternalReferrer if we came from an external referrer
2180 function isExternalReferrer(&$request) {
2181 if ($referrer = $request->get('HTTP_REFERER')) {
2182 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2183 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2184 require_once("lib/ExternalReferrer.php");
2185 $se = new SearchEngines();
2186 return $se->parseSearchQuery($referrer);
2188 //if (DEBUG) return array('query' => 'wiki');
2193 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2195 function loadPhpExtension($extension) {
2196 if (!extension_loaded($extension)) {
2197 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2198 $soname = ($isWindows ? 'php_' : '')
2200 . ($isWindows ? '.dll' : '.so');
2204 return extension_loaded($extension);
2207 function charset_convert($from, $to, $data) {
2209 //$wikicharset = strtolower($CHARSET);
2210 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2211 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2212 return utf8_decode($data);
2213 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2214 return utf8_encode($data);
2216 if (loadPhpExtension("iconv")) {
2217 $tmpdata = iconv($from, $to, $data);
2219 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2223 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2228 function string_starts_with($string, $prefix) {
2229 return (substr($string, 0, strlen($prefix)) == $prefix);
2231 function string_ends_with($string, $suffix) {
2232 return (substr($string, -strlen($suffix)) == $suffix);
2234 function array_remove($arr,$value) {
2235 return array_values(array_diff($arr,array($value)));
2239 * Ensure that the script will have another $secs time left.
2240 * Works only if safe_mode is off.
2241 * For example not to timeout on waiting socket connections.
2242 * Use the socket timeout as arg.
2244 function longer_timeout($secs = 30) {
2245 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2246 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2247 if ($timeleft < $secs)
2248 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2251 function printSimpleTrace($bt) {
2253 echo "\nTraceback:\n";
2254 if (function_exists('debug_print_backtrace')) { // >= 5
2255 debug_print_backtrace();
2257 foreach ($bt as $i => $elem) {
2258 if (!array_key_exists('file', $elem)) {
2261 //echo join(" ",array_values($elem)),"\n";
2262 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2268 * Return the used process memory, in bytes.
2269 * Enable the section which will work for you. They are very slow.
2270 * Special quirks for Windows: Requires cygwin.
2272 function getMemoryUsage() {
2273 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2274 if (function_exists('memory_get_usage') and memory_get_usage()) {
2275 return memory_get_usage();
2276 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2277 $mem = $u['ru_maxrss'];
2278 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2279 // what we want is the process memory only: apache or php (if CGI)
2282 // win32_ps_stat_proc, win32_ps_stat_mem
2283 if (function_exists('win32_ps_list_procs')) {
2284 $info = win32_ps_stat_proc($pid);
2285 $memstr = $info['mem']['working_set_size'];
2287 // This works only if it's a cygwin process (apache or php).
2288 // Requires a newer cygwin
2289 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2291 // if it's native windows use something like this:
2292 // (requires pslist from sysinternals.com, grep, sed and perl)
2293 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2295 return (integer) trim($memstr);
2298 //%MEM: Percentage of total memory in use by this process
2299 //VSZ: Total virtual memory size, in 1K blocks.
2300 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2301 //CPU time used by process since it started.
2302 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2303 $memstr = exec("ps -orss -p $pid|sed 1d");
2304 return (integer) trim($memstr);
2309 * @param var $needle
2310 * @param array $haystack one-dimensional numeric array only, no hash
2312 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2313 It will return false if not found or the index where it was found.
2314 From dennis.decoene@moveit.be http://www.php.net/array_search
2316 function binary_search($needle, $haystack) {
2317 $high = count($haystack);
2320 while (($high - $low) > 1) {
2321 $probe = floor(($high + $low) / 2);
2322 if ($haystack[$probe] < $needle) {
2324 } elseif ($haystack[$probe] == $needle) {
2325 $high = $low = $probe;
2331 if ($high == count($haystack) || $haystack[$high] != $needle) {
2338 function is_localhost($url = false) {
2340 global $HTTP_SERVER_VARS;
2341 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2346 * Take a string and quote it sufficiently to be passed as a Javascript
2347 * string between ''s
2349 function javascript_quote_string($s) {
2350 return str_replace("'", "\'", $s);
2353 function isSerialized($s) {
2354 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2358 * Take a string and return an array of pairs (attribute name, attribute value)
2360 * We allow attributes with or without double quotes (")
2361 * Attribute-value pairs may be separated by space or comma
2362 * Space is normal HTML attributes, comma is for RichTable compatibility
2363 * border=1, cellpadding="5"
2364 * border=1 cellpadding="5"
2365 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2366 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2368 function parse_attributes($line) {
2372 if (empty($line)) return $options;
2373 $line = trim($line);
2374 if (empty($line)) return $options;
2375 $line = trim($line, ",");
2376 if (empty($line)) return $options;
2378 // First we have an attribute name.
2383 while (($i < strlen($line)) && ($line[$i] != '=')) {
2386 $attribute = substr($line, 0, $i);
2387 $attribute = strtolower($attribute);
2389 $line = substr($line, $i+1);
2390 $line = trim ($line);
2391 $line = trim ($line, "=");
2392 $line = trim ($line);
2394 if (empty($line)) return $options;
2396 // Then we have the attribute value.
2399 // Attribute value might be between double quotes
2400 // In that case we have to find the closing double quote
2401 if ($line[0] == '"') {
2402 $i++; // skip first '"'
2403 while (($i < strlen($line)) && ($line[$i] != '"')) {
2406 $value = substr($line, 0, $i);
2407 $value = trim ($value, '"');
2408 $value = trim ($value);
2410 // If there are no double quotes, we have to find the next space or comma
2412 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2415 $value = substr($line, 0, $i);
2416 $value = trim ($value);
2417 $value = trim ($value, ",");
2418 $value = trim ($value);
2421 $options[$attribute] = $value;
2423 $line = substr($line, $i+1);
2424 $line = trim ($line);
2425 $line = trim ($line, ",");
2426 $line = trim ($line);
2428 return $options + parse_attributes($line);
2432 * Returns true if the filename ends with an image suffix.
2433 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2435 function is_image ($filename) {
2437 if (defined('INLINE_IMAGES')) {
2438 $inline_images = INLINE_IMAGES;
2440 $inline_images = "png|jpg|jpeg|gif";
2443 foreach (explode("|", $inline_images) as $suffix) {
2444 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2452 * Compute cell in spreadsheet table
2453 * $table: two-dimensional table
2454 * $i and $j: indexes of cell to compute
2455 * $imax and $jmax: table dimensions
2457 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2459 // What is implemented:
2460 // @@=SUM(R)@@ : sum of cells in current row
2461 // @@=SUM(C)@@ : sum of cells in current column
2462 // @@=AVERAGE(R)@@ : average of cells in current row
2463 // @@=AVERAGE(C)@@ : average of cells in current column
2464 // @@=MAX(R)@@ : maximum value of cells in current row
2465 // @@=MAX(C)@@ : maximum value of cells in current column
2466 // @@=MIN(R)@@ : minimum value of cells in current row
2467 // @@=MIN(C)@@ : minimum value of cells in current column
2468 // @@=COUNT(R)@@ : number of cells in current row
2469 // (numeric or not, excluding headers and current cell)
2470 // @@=COUNT(C)@@ : number of cells in current column
2471 // (numeric or not, excluding headers and current cell)
2477 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2478 for ($index=0; $index<$imax; $index++) {
2479 if (is_numeric($table[$index][$j])) {
2480 $result += $table[$index][$j];
2483 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2485 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2486 for ($index=0; $index<$jmax; $index++) {
2487 if (is_numeric($table[$i][$index])) {
2488 $result += $table[$i][$index];
2491 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2493 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2494 for ($index=0; $index<$imax; $index++) {
2495 if (is_numeric($table[$index][$j])) {
2496 $result += $table[$index][$j];
2500 $result=$result/$counter;
2501 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2503 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2504 for ($index=0; $index<$jmax; $index++) {
2505 if (is_numeric($table[$i][$index])) {
2506 $result += $table[$i][$index];
2510 $result=$result/$counter;
2511 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2513 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2514 for ($index=0; $index<$imax; $index++) {
2515 if (is_numeric($table[$index][$j])) {
2518 $result=$table[$index][$j];
2520 $result = max($result, $table[$index][$j]);
2527 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2529 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2530 for ($index=0; $index<$jmax; $index++) {
2531 if (is_numeric($table[$i][$index])) {
2534 $result=$table[$i][$index];
2536 $result = max($result, $table[$i][$index]);
2543 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2545 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2546 for ($index=0; $index<$imax; $index++) {
2547 if (is_numeric($table[$index][$j])) {
2550 $result=$table[$index][$j];
2552 $result = min($result, $table[$index][$j]);
2559 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2561 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2562 for ($index=0; $index<$jmax; $index++) {
2563 if (is_numeric($table[$i][$index])) {
2566 $result=$table[$i][$index];
2568 $result = min($result, $table[$i][$index]);
2575 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2577 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2578 for ($index=0; $index<$imax; $index++) {
2579 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2583 $result = $counter-1; // exclude self
2584 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2586 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2587 for ($index=0; $index<$jmax; $index++) {
2588 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2592 $result = $counter-1; // exclude self
2593 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2596 return $table[$i][$j];
2600 * Remove accents from given text.
2602 function strip_accents($text) {
2603 $res = utf8_decode($text);
2605 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2606 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2607 return utf8_encode($res);
2610 // (c-file-style: "gnu")
2614 // c-basic-offset: 4
2615 // c-hanging-comment-ender-p: nil
2616 // indent-tabs-mode: nil