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)
76 isActionPage ($filename)
80 obj2hash ($obj, $exclude = false, $fields = false)
83 url_get_contents ($uri)
85 firstNWordsOfContent ($n, $content)
86 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
89 charset_convert($from, $to, $data)
90 string_starts_with($string, $prefix)
91 string_ends_with($string, $suffix)
92 array_remove($arr,$value)
93 longer_timeout($secs=30)
96 binary_search($needle, $haystack)
98 javascript_quote_string($s)
100 parse_attributes($line)
103 compute_tablecell ($table, $i, $j, $imax, $jmax)
105 function: LinkInterWikiLink($link, $linktext)
106 moved to: lib/interwiki.php
107 function: linkExistingWikiWord($wikiword, $linktext, $version)
108 moved to: lib/WikiTheme.php
109 function: LinkUnknownWikiWord($wikiword, $linktext)
110 moved to: lib/WikiTheme.php
111 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
112 gone see: lib/plugin/RecentChanges.php
114 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
115 else define('_PHPWIKI_STDLIB_LOADED', true);
117 define('MAX_PAGENAME_LENGTH', 100);
120 * Convert string to a valid XML identifier.
122 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
124 * We would like to have, e.g. named anchors within wiki pages
125 * names like "Table of Contents" --- clearly not a valid XML
126 * fragment identifier.
128 * This function implements a one-to-one map from {any string}
129 * to {valid XML identifiers}.
132 * converting all bytes not in [A-Za-z0-9:_-],
133 * and any leading byte not in [A-Za-z] to 'xbb.',
134 * where 'bb' is the hexadecimal representation of the
137 * As a special case, the empty string is converted to 'empty.'
142 function MangleXmlIdentifier($str) {
146 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
147 "'x' . sprintf('%02x', ord('\\0')) . '.'",
151 function UnMangleXmlIdentifier($str) {
152 if ($str == 'empty.')
154 return preg_replace('/x(\w\w)\./e',
155 "sprintf('%c', hex('\\0'))",
160 * Returns a name for the WIKI_ID cookie that should be unique on the host.
161 * But for it to be unique you must have set a unique WIKI_NAME in your
162 * configuration file.
163 * @return string The name of the WIKI_ID cookie to use for this wiki.
165 function GetCookieName() {
166 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
170 * Generates a valid URL for a given Wiki pagename.
171 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
172 * If a WikiDB_Page object function will extract the name to link to.
173 * If a WikiDB_PageRevision object function will extract the name to link to.
175 * @param boolean $get_abs_url Default value is false.
176 * @return string The absolute URL to the page passed as $pagename.
178 function WikiURL($pagename, $args = '', $get_abs_url = false) {
179 global $request, $WikiTheme;
182 if (is_object($pagename)) {
183 if (isa($pagename, 'WikiDB_Page')) {
184 $pagename = $pagename->getName();
186 elseif (isa($pagename, 'WikiDB_PageRevision')) {
187 $page = $pagename->getPage();
188 $args['version'] = $pagename->getVersion();
189 $pagename = $page->getName();
191 elseif (isa($pagename, 'WikiPageName')) {
192 $anchor = $pagename->anchor;
193 $pagename = $pagename->name;
195 $anchor = $pagename->anchor;
196 $pagename = $pagename->name;
199 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
201 $args = 'start_debug=' . $request->getArg('start_debug');
202 elseif (is_array($args))
203 $args['start_debug'] = $request->getArg('start_debug');
205 $args .= '&start_debug=' . $request->getArg('start_debug');
207 if (is_array($args)) {
209 foreach ($args as $key => $val) {
210 // avoid default args
211 if (USE_PATH_INFO and $key == 'pagename')
213 elseif ($key == 'action' and $val == 'browse')
215 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
216 $enc_args[] = urlencode($key) . '=' . urlencode($val);
218 $args = join('&', $enc_args);
221 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
222 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
223 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
225 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
226 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
227 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
230 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
232 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
242 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
243 $url .= "?pagename=" . rawurlencode($pagename);
248 $url .= "#" . MangleXmlIdentifier($anchor);
252 /** Convert relative URL to absolute URL.
254 * This converts a relative URL to one of PhpWiki's support files
255 * to an absolute one.
258 * @return string Absolute URL
260 function AbsoluteURL ($url) {
261 if (preg_match('/^https?:/', $url))
263 if ($url[0] != '/') {
264 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
265 while ($base != '/' and substr($url, 0, 3) == "../") {
266 $url = substr($url, 3);
267 $base = dirname($base);
273 return SERVER_URL . $url;
276 function DataURL ($url) {
277 if (preg_match('/^https?:/', $url))
279 $url = NormalizeWebFileName($url);
280 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
281 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
282 return AbsoluteURL($url);
286 * Generates icon in front of links.
288 * @param string $protocol_or_url URL or protocol to determine which icon to use.
290 * @return HtmlElement HtmlElement object that contains data to create img link to
291 * icon for use with url or protocol passed to the function. False if no img to be
294 function IconForLink($protocol_or_url) {
296 if (0 and $filename_suffix == false) {
297 // display apache style icon for file type instead of protocol icon
298 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
299 // - document: html, htm, text, txt, rtf, pdf, doc
300 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
301 // - audio: mp3,mp2,aiff,aif,au
302 // - multimedia: mpeg,mpg,mov,qt
304 list ($proto) = explode(':', $protocol_or_url, 2);
305 $src = $WikiTheme->getLinkIconURL($proto);
307 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
314 * Glue icon in front of or after text.
315 * Pref: 'noLinkIcons' - ignore icon if set
316 * WikiTheme: 'LinkIcons' - 'yes' at front
317 * - 'no' display no icon
318 * - 'front' display at left
319 * - 'after' display at right
321 * @param string $protocol_or_url Protocol or URL. Used to determine the
323 * @param string $text The text.
324 * @return XmlContent.
326 function PossiblyGlueIconToText($proto_or_url, $text) {
327 global $request, $WikiTheme;
328 if ($request->getPref('noLinkIcons'))
330 $icon = IconForLink($proto_or_url);
333 if ($where = $WikiTheme->getLinkIconAttr()) {
334 if ($where == 'no') return $text;
335 if ($where != 'after') $where = 'front';
339 if ($where == 'after') {
340 // span the icon only to the last word (tie them together),
341 // to let the previous words wrap on line breaks.
342 if (!is_object($text)) {
343 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
344 list (, $prefix, $last_word) = $m;
350 $text = HTML::span(array('style' => 'white-space: nowrap'),
351 $last_word, HTML::Raw(' '), $icon);
353 $text = HTML($prefix, $text);
356 // span the icon only to the first word (tie them together),
357 // to let the next words wrap on line breaks
358 if (!is_object($text)) {
359 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
360 list (, $first_word, $tail) = $m;
366 $text = HTML::span(array('style' => 'white-space: nowrap'),
369 $text = HTML($text, $tail);
374 * Determines if the url passed to function is safe, by detecting if the characters
375 * '<', '>', or '"' are present.
376 * Check against their urlencoded values also.
378 * @param string $url URL to check for unsafe characters.
379 * @return boolean True if same, false else.
381 function IsSafeURL($url) {
382 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
386 * Generates an HtmlElement object to store data for a link.
388 * @param string $url URL that the link will point to.
389 * @param string $linktext Text to be displayed as link.
390 * @return HtmlElement HtmlElement object that contains data to construct an html link.
392 function LinkURL($url, $linktext = '') {
393 // FIXME: Is this needed (or sufficient?)
394 if(! IsSafeURL($url)) {
395 $link = HTML::span(array('class' => 'error'), _("BAD URL -- remove all of <, >, \""));
400 $linktext = preg_replace("/mailto:/A", "", $url);
401 $args = array('href' => $url);
402 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
403 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
404 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
406 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
413 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
414 * Disallows sizes which are too small.
415 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
417 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
419 function LinkImage($url, $alt = "") {
420 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
421 // Disallow tags in img src urls. Typical CSS attacks.
422 // FIXME: Is this needed (or sufficient?)
423 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
425 // support new syntax: [prefix/image.jpg size=50% border=n]
426 if (empty($alt)) $alt = "";
429 $arr = explode(' ',$url);
430 if (!empty($arr)) $url = $arr[0];
431 if (! IsSafeURL($url)) {
432 $link = HTML::span(array('class' => 'error'), _("BAD URL -- remove all of <, >, \""));
435 // spaces in inline images must be %20 encoded!
436 $link = HTML::img(array('src' => $url));
438 // Extract attributes
439 $arr = parse_attributes(strstr($ori_url, " "));
440 foreach ($arr as $attr => $value) {
441 // These attributes take strings: lang, id, title, alt
442 if (($attr == "lang")
444 || ($attr == "title")
445 || ($attr == "alt")) {
446 $link->setAttr($attr, $value);
448 // align = bottom|middle|top|left|right
449 elseif (($attr == "align")
450 && (($value == "bottom")
451 || ($value == "middle")
453 || ($value == "left")
454 || ($value == "right"))) {
455 $link->setAttr($attr, $value);
457 // These attributes take a number (pixels): border, hspace, vspace
458 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
459 && (is_numeric($value))) {
460 $link->setAttr($attr, (int)$value);
462 // These attributes take a number (pixels) or a percentage: height, width
463 elseif ((($attr == "height") || ($attr == "width"))
464 && (preg_match('/\d+[%p]?x?/', $value))) {
465 $link->setAttr($attr, $value);
467 // We allow size=50% and size=20x30
468 // We replace this with "width" and "height" HTML attributes
469 elseif ($attr == "size") {
470 if (preg_match('/(\d+%)/', $value, $m)) {
471 $link->setAttr('width',$m[1]);
472 $link->setAttr('height',$m[1]);
473 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
474 $link->setAttr('width',$m[1]);
475 $link->setAttr('height',$m[2]);
479 $link = HTML::span(array('class' => 'error'),
480 sprintf(_("Invalid image attribute \"%s\" %s=%s"),
481 $url, $attr, $value));
485 // Correct silently the most common error
486 if ($url != $ori_url and empty($arr) and !preg_match("/^http/",$url)) {
487 // space belongs to the path
488 $file = NormalizeLocalFileName($ori_url);
489 if (file_exists($file)) {
490 $link = HTML::img(array('src' => $ori_url));
492 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
493 $url, $ori_url), E_USER_WARNING);
494 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
495 $file = substr($file, strlen(getUploadDataPath()));
496 $path = getUploadFilePath().$file;
497 if (file_exists($path)) {
498 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
499 $url, $ori_url), E_USER_WARNING);
500 $link->setAttr('src', getUploadDataPath() . $file);
505 if (!$link->getAttr('alt')) {
506 $link->setAttr('alt', $alt);
508 // Check width and height as spam countermeasure
509 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
510 //$width = (int) $width; // px or % or other suffix
511 //$height = (int) $height;
512 if (($width < 3 and $height < 10) or
513 ($height < 3 and $width < 20) or
514 ($height < 7 and $width < 7))
516 $link = HTML::span(array('class' => 'error'),
517 _("Invalid image size"));
522 // Prepare for getimagesize($url)
523 // $url only valid for external urls, otherwise local path
524 // Older php versions crash here with certain png's:
525 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
526 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
527 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
528 if (DISABLE_GETIMAGESIZE)
530 elseif (! preg_match("/\.$force_img$/i", $url))
531 ; // only valid image extensions or scripts assumed to generate images
532 elseif (preg_match("/^http/",$url)) { // external url
533 $size = @getimagesize($url);
534 } else { // local file
535 if (file_exists($file = NormalizeLocalFileName($url))) { // here
536 $size = @getimagesize($file);
537 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
538 $size = @getimagesize($file);
539 $link->setAttr('src', rawurldecode($url));
540 } elseif (string_starts_with($url, getUploadDataPath())) { // there
541 $file = substr($file, strlen(getUploadDataPath()));
542 $path = getUploadFilePath().rawurldecode($file);
543 $size = @getimagesize($path);
544 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
545 } else { // elsewhere
547 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
553 if (($width < 3 and $height < 10)
554 or ($height < 3 and $width < 20)
555 or ($height < 7 and $width < 7))
557 $link = HTML::span(array('class' => 'error'),
558 _("Invalid image size"));
563 $link->setAttr('class', 'inlineimage');
565 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
566 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
567 * Note: Allow cgi's (pl,cgi) returning images.
569 if (!preg_match("/\.(".$force_img.")/i", $url)) {
570 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
571 // => HTML::object(array('src' => $url)) ...;
572 return ImgObject($link, $ori_url);
578 * <object> / <embed> tags instead of <img> for all non-image extensions
580 * Called by LinkImage(), not directly.
581 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
582 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
583 * $alt may be an alternate img
584 * TODO: Need to unify with WikiPluginCached::embedObject()
586 * Note that Safari 1.0 will crash with <object>, so use only <embed>
587 * http://www.alleged.org.uk/pdc/2002/svg-object.html
589 * Allowed object tags:
590 * DATA=URI (object data)
591 * CLASSID=URI (location of implementation)
592 * ARCHIVE=CDATA (archive files)
593 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
594 * WIDTH=Length (object width)
595 * HEIGHT=Length (object height)
596 * NAME=CDATA (name for form submission)
597 * USEMAP=URI (client-side image map)
598 * TYPE=ContentType (content-type of object)
599 * CODETYPE=ContentType (content-type of code)
600 * STANDBY=Text (message to show while loading)
601 * TABINDEX=NUMBER (position in tabbing order)
602 * DECLARE (do not instantiate object)
603 * The rest is added as <param name="" value="" /> tags
605 function ImgObject($img, $url) {
606 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
607 $params = explode(",","data,classid,archive,codebase,name,usemap,type,".
608 "codetype,standby,tabindex,declare");
609 if (is_array($url)) {
612 foreach ($args as $attr => $value) {
613 foreach ($params as $param) {
614 if ($param == $attr) {
615 $img->setAttr($param, $value);
616 if (isset($found[$param])) $found[$param]++;
617 else $found[$param] = 1;
622 // now all remaining args are added as <param> to the object
624 foreach ($args as $attr => $value) {
625 if (!isset($found[$attr])) {
626 $params[] = HTML::param(array('name' => $attr,
630 $url = $img->getAttr('src');
631 $force_img = "png|jpg|gif|jpeg|bmp";
632 if (!preg_match("/\.(".$force_img.")/i", $url)) {
633 $img->setAttr('src', false);
636 $args = explode(' ', $url);
637 if (count($args) >= 1) {
638 $url = array_shift($args);
640 foreach ($args as $attr) {
641 foreach ($params as $param) {
642 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
643 $img->setAttr($param, $m[1]);
644 if (isset($found[$param])) $found[$param]++;
645 else $found[$param] = 1;
650 // now all remaining args are added as <param> to the object
652 foreach ($args as $attr) {
653 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
654 $params[] = HTML::param(array('name' => $m[1],
660 $type = $img->getAttr('type');
662 // TODO: map extension to mime-types if type is not given and php < 4.3
663 if (function_exists('mime_content_type'))
664 $type = mime_content_type($url);
666 $object = HTML::object(array_merge($img->_attr,
667 array('type' => $type)), //'src' => $url
669 $object->setAttr('class', 'inlineobject');
671 foreach ($params as $param) $object->pushContent($param);
673 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
674 return HTML::embed($object->_attr, $object->_content);
676 $object->pushContent(HTML::embed($object->_attr));
683 // var in php5 deprecated
685 $this->items = array();
688 function push($item) {
689 $this->items[$this->size] = $item;
695 if ($this->size == 0) {
696 return false; // stack is empty
699 return $this->items[$this->size];
708 return $this->items[$this->size - 1];
714 // end class definition
716 function SplitQueryArgs ($query_args = '')
718 // FIXME: use the arg-seperator which might not be &
719 $split_args = explode('&', $query_args);
721 while (list($key, $val) = each($split_args))
722 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
723 $args[$m[1]] = $m[2];
727 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
730 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
731 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
735 $pagename = urldecode($m[1]);
738 if (empty($pagename) &&
739 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
740 // Convert old style links (to not break diff links in
742 $pagename = urldecode($m[2]);
743 $args = array("action" => $m[1]);
746 $args = SplitQueryArgs($qargs);
749 if (empty($pagename))
750 $pagename = $GLOBALS['request']->getArg('pagename');
752 if (isset($args['action']) && $args['action'] == 'browse')
753 unset($args['action']);
756 if (empty($args['action']))
758 else if (is_safe_action($args['action']))
759 $class = 'wikiaction';
761 if (empty($args['action']) || is_safe_action($args['action']))
762 $class = 'wikiaction';
764 // Don't allow administrative links on unlocked pages.
765 $dbi = $GLOBALS['request']->getDbh();
766 $page = $dbi->getPage($basepage ? $basepage : $pagename);
767 if (!$page->get('locked'))
768 return HTML::span(array('class' => 'wikiunsafe'),
769 HTML::u(_("Lock page to enable link")));
770 $class = 'wikiadmin';
774 $text = HTML::span(array('class' => 'rawurl'), $url);
776 $wikipage = new WikiPageName($pagename);
777 if (!$wikipage->isValid()) {
779 return $WikiTheme->linkBadWikiWord($wikipage, $url);
782 return HTML::a(array('href' => WikiURL($pagename, $args),
788 * A class to assist in parsing wiki pagenames.
790 * Now with subpages and anchors, parsing and passing around
791 * pagenames is more complicated. This should help.
795 /** Short name for page.
797 * This is the value of $name passed to the constructor.
798 * (For use, e.g. as a default label for links to the page.)
802 /** The full page name.
804 * This is the full name of the page (without anchor).
810 * This is the referenced anchor within the page, or the empty string.
816 * @param mixed $name Page name.
817 * WikiDB_Page, WikiDB_PageRevision, or string.
818 * This can be a relative subpage name (like '/SubPage'),
819 * or can be the empty string to refer to the $basename.
821 * @param string $anchor For links to anchors in page.
823 * @param mixed $basename Page name from which to interpret
824 * relative or other non-fully-specified page names.
826 function WikiPageName($name, $basename=false, $anchor=false) {
827 if (is_string($name)) {
828 $this->shortName = $name;
829 if (strstr($name, ':')) {
830 list($moniker, $shortName) = explode (":", $name, 2);
831 $map = getInterwikiMap(); // allow overrides to custom maps
832 if (isset($map->_map[$moniker])) {
833 $url = $map->_map[$moniker];
834 if (strstr($url, '%s'))
835 $url = sprintf($url, $shortName);
839 // expand Talk or User, but not to absolute urls!
840 if (strstr($url, '//')) {
841 if ($moniker == 'Talk')
842 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
843 elseif ($moniker == 'User')
848 if (strstr($shortName, '?')) {
849 list($shortName, $dummy) = explode("\?", $shortName, 2);
851 $this->shortName = $shortName;
854 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
855 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
857 $name = $this->_pagename($basename) . $name;
859 $name = $this->_normalize_bad_pagename($name);
860 $this->shortName = $name;
865 $name = $this->_pagename($name);
866 $this->shortName = $name;
869 $this->name = $this->_check($name);
870 $this->anchor = (string)$anchor;
877 function getParent() {
879 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
881 return substr($name, 0, -strlen($tail));
884 function isValid($strict = false) {
886 return !isset($this->_errors);
887 return (is_string($this->name) and $this->name != '');
890 function getWarnings() {
892 if (isset($this->_warnings))
893 $warnings = array_merge($warnings, $this->_warnings);
894 if (isset($this->_errors))
895 $warnings = array_merge($warnings, $this->_errors);
899 return sprintf(_("'%s': Bad page name: %s"),
900 $this->shortName, join(', ', $warnings));
903 function _pagename($page) {
904 if (isa($page, 'WikiDB_Page'))
905 return $page->getName();
906 elseif (isa($page, 'WikiDB_PageRevision'))
907 return $page->getPageName();
908 elseif (isa($page, 'WikiPageName'))
910 // '0' or e.g. '1984' should be allowed though
911 if (!is_string($page) and !is_integer($page)) {
912 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
913 $page, gettype($page), get_class($page)),
916 //assert(is_string($page));
920 function _normalize_bad_pagename($name) {
921 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
923 // Punt... You really shouldn't get here.
926 return $request->getArg('pagename');
928 assert($name[0] == SUBPAGE_SEPARATOR);
929 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
930 return substr($name, 1);
934 * Compress internal white-space to single space character.
936 * This leads to problems with loading a foreign charset pagename,
937 * which cannot be deleted anymore, because unknown chars are compressed.
938 * So BEFORE importing a file _check must be done !!!
940 function _check($pagename) {
941 // Compress internal white-space to single space character.
942 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
943 if ($pagename != $orig)
944 $this->_warnings[] = _("White space converted to single space");
946 // Delete any control characters.
947 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
948 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
949 if ($pagename != $orig)
950 $this->_errors[] = _("Control characters not allowed");
953 // Strip leading and trailing white-space.
954 $pagename = trim($pagename);
957 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
958 $pagename = substr($pagename, 1);
959 if ($pagename != $orig)
960 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
962 // ";" is urlencoded, so safe from php arg-delim problems
963 /*if (strstr($pagename, ';')) {
964 $this->_warnings[] = _("';' is deprecated");
965 $pagename = str_replace(';', '', $pagename);
968 // not only for SQL, also to restrict url length
969 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
970 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
971 $this->_errors[] = _("too long");
974 // disallow some chars only on file and cvs
975 if ((DATABASE_TYPE == 'cvs'
976 or DATABASE_TYPE == 'file'
977 or DATABASE_TYPE == 'flatfile')
978 and preg_match('/(:|\.\.)/', $pagename, $m))
980 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
981 $pagename = str_replace('..', '', $pagename);
982 $pagename = str_replace(':', '', $pagename);
990 * Convert old page markup to new-style markup.
992 * @param string $text Old-style wiki markup.
994 * @param string $markup_type
996 * <dt><code>"block"</code> <dd>Convert all markup.
997 * <dt><code>"inline"</code> <dd>Convert only inline markup.
998 * <dt><code>"links"</code> <dd>Convert only link markup.
1001 * @return string New-style wiki markup.
1003 * @bugs Footnotes don't work quite as before (esp if there are
1004 * multiple references to the same footnote. But close enough,
1005 * probably for now....
1006 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
1007 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
1008 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1009 * also known to crash, even with Apache1.
1011 function ConvertOldMarkup ($text, $markup_type = "block") {
1017 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
1018 // AnciennesR%E8glesDeFormatage crashes.
1019 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1020 // also known to crash, even with Apache1.
1021 $debug_skip = false;
1022 // I suspect this only to crash with Apache2 and IIS.
1023 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
1024 and preg_match("/plugin CreateToc/", $text))
1026 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
1027 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
1028 ._("Skipped."), E_USER_WARNING);
1030 //if (!DEBUG) return $text;
1035 /*****************************************************************
1036 * Conversions for inline markup:
1043 // escape escaped brackets
1047 // change ! escapes to ~'s.
1048 global $WikiNameRegexp, $request;
1049 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1050 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1051 $map = getInterwikiMap();
1052 if ($map_regex = $map->getRegexp())
1053 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1054 $bang_esc[] = $WikiNameRegexp;
1055 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1058 $subs["links"] = array($orig, $repl);
1060 // Temporarily URL-encode pairs of underscores in links to hide
1061 // them from the re for bold markup.
1062 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1063 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1066 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1069 // Convert footnote references.
1070 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1071 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1073 // Convert old style emphases to HTML style emphasis.
1074 $orig[] = '/__(.*?)__/';
1075 $repl[] = '<strong>\\1</strong>';
1076 $orig[] = "/''(.*?)''/";
1077 $repl[] = '<em>\\1</em>';
1079 // Escape nestled markup.
1080 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1083 // in old markup headings only allowed at beginning of line
1087 // Convert URL-encoded pairs of underscores in links back to
1088 // real underscores after bold markup has been converted.
1089 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1090 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1092 $subs["inline"] = array($orig, $repl);
1094 /*****************************************************************
1095 * Patterns which match block markup constructs which take
1096 * special handling...
1100 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1102 $blockpats[] = '\|(?:.*\n\|)*';
1105 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1107 // Footnote definitions
1108 $blockpats[] = '\[\s*(\d+)\s*\]';
1112 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1116 $blockpats[] = '!{1,3}[^!]';
1118 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1119 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1121 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1122 . join("|", $blockpats)
1127 if ($markup_type != "block") {
1128 list ($orig, $repl) = $subs[$markup_type];
1129 return preg_replace($orig, $repl, $text);
1132 list ($orig, $repl) = $subs['inline'];
1135 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1136 // AnciennesR%E8glesDeFormatage and more
1137 // See http://www.pcre.org/pcre.txt LIMITATIONS
1138 while (preg_match($block_re, $text, $m)) {
1139 $text = substr($text, strlen($m[0]));
1140 list (,$leading_text, $block) = $m;
1143 if (strchr(" \t", $block[0])) {
1145 $prefix = "<pre>\n";
1146 $suffix = "\n</pre>\n";
1148 elseif ($block[0] == '|') {
1150 $prefix = "<?plugin OldStyleTable\n";
1153 elseif (strchr("#*;", $block[0])) {
1154 // Old-style list item
1155 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1156 list (,$ind,$bullet) = $m;
1157 $block = substr($block, strlen($m[0]));
1159 $indent = str_repeat(' ', strlen($ind));
1160 if ($bullet[0] == ';') {
1161 //$term = ltrim(substr($bullet, 1));
1162 //return $indent . $term . "\n" . $indent . ' ';
1163 $prefix = $ind . $bullet;
1166 $prefix = $indent . $bullet . ' ';
1168 elseif ($block[0] == '[') {
1169 // Footnote definition
1170 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1172 $block = substr($block, strlen($m[0]));
1173 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1175 elseif ($block[0] == '<') {
1177 // HACK: no inline markup...
1181 elseif ($block[0] == '!') {
1183 preg_match('/^!{1,3}/', $block, $m);
1185 $block = substr($block, strlen($m[0]));
1191 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1192 if ($block) $block = preg_replace($orig, $repl, $block);
1193 $out .= $leading_text;
1198 return $out . preg_replace($orig, $repl, $text);
1204 * Expand tabs in string.
1206 * Converts all tabs to (the appropriate number of) spaces.
1208 * @param string $str
1209 * @param integer $tab_width
1212 function expand_tabs($str, $tab_width = 8) {
1213 $split = explode("\t", $str);
1214 $tail = array_pop($split);
1216 foreach ($split as $hunk) {
1218 $pos = strlen(strrchr($expanded, "\n")) - 1;
1219 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1221 return substr($expanded, 1) . $tail;
1225 * Split WikiWords in page names.
1227 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1228 * places like page titles. This is rumored to help search engines
1231 * @param $page string The page name.
1233 * @return string The split name.
1235 function SplitPagename ($page) {
1237 if (preg_match("/\s/", $page))
1238 return $page; // Already split --- don't split any more.
1240 // This algorithm is specialized for several languages.
1241 // (Thanks to Pierrick MEIGNEN)
1242 // Improvements for other languages welcome.
1245 // This mess splits between a lower-case letter followed by
1246 // either an upper-case or a numeral; except that it wont
1247 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1248 switch ($GLOBALS['LANG']) {
1253 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1256 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1259 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1260 // This the single-letter words 'I' and 'A' from any following
1261 // capitalized words.
1262 switch ($GLOBALS['LANG']) {
1264 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1267 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1270 // Split at underscore
1271 $RE[] = '/(_)([[:alpha:]])/';
1272 $RE[] = '/([[:alpha:]])(_)/';
1273 // Split numerals from following letters.
1274 $RE[] = '/(\d)([[:alpha:]])/';
1275 // Split at subpage seperators. TBD in WikiTheme.php
1276 $RE[] = "/([^${sep}]+)(${sep})/";
1277 $RE[] = "/(${sep})([^${sep}]+)/";
1279 foreach ($RE as $key)
1283 foreach ($RE as $regexp) {
1284 $page = preg_replace($regexp, '\\1 \\2', $page);
1289 function NoSuchRevision (&$request, $page, $version) {
1290 $html = HTML(HTML::h2(_("Revision Not Found")),
1291 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1292 $version, WikiLink($page, 'auto'))));
1293 include_once('lib/Template.php');
1294 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1300 * Get time offset for local time zone.
1302 * @param $time time_t Get offset for this time. Default: now.
1303 * @param $no_colon boolean Don't put colon between hours and minutes.
1304 * @return string Offset as a string in the format +HH:MM.
1306 function TimezoneOffset ($time = false, $no_colon = false) {
1307 if ($time === false)
1309 $secs = date('Z', $time);
1318 $colon = $no_colon ? '' : ':';
1319 $mins = intval(($secs + 30) / 60);
1320 return sprintf("%s%02d%s%02d",
1321 $sign, $mins / 60, $colon, $mins % 60);
1326 * Format time in ISO-8601 format.
1328 * @param $time time_t Time. Default: now.
1329 * @return string Date and time in ISO-8601 format.
1331 function Iso8601DateTime ($time = false) {
1332 if ($time === false)
1334 $tzoff = TimezoneOffset($time);
1335 $date = date('Y-m-d', $time);
1336 $time = date('H:i:s', $time);
1337 return $date . 'T' . $time . $tzoff;
1341 * Format time in RFC-2822 format.
1343 * @param $time time_t Time. Default: now.
1344 * @return string Date and time in RFC-2822 format.
1346 function Rfc2822DateTime ($time = false) {
1347 if ($time === false)
1349 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1353 * Format time in RFC-1123 format.
1355 * @param $time time_t Time. Default: now.
1356 * @return string Date and time in RFC-1123 format.
1358 function Rfc1123DateTime ($time = false) {
1359 if ($time === false)
1361 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1364 /** Parse date in RFC-1123 format.
1366 * According to RFC 1123 we must accept dates in the following
1369 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1370 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1371 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1373 * (Though we're only allowed to generate dates in the first format.)
1375 function ParseRfc1123DateTime ($timestr) {
1376 $timestr = trim($timestr);
1377 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1378 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1380 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1382 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1383 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1385 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1386 if ($year < 70) $year += 2000;
1387 elseif ($year < 100) $year += 1900;
1389 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1390 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1392 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1399 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1401 return false; // failed
1406 * Format time to standard 'ctime' format.
1408 * @param $time time_t Time. Default: now.
1409 * @return string Date and time.
1411 function CTime ($time = false)
1413 if ($time === false)
1415 return date("D M j H:i:s Y", $time);
1420 * Format number as kilobytes or bytes.
1421 * Short format is used for PageList
1422 * Long format is used in PageInfo
1424 * @param $bytes int. Default: 0.
1425 * @param $longformat bool. Default: false.
1426 * @return class FormattedText (XmlElement.php).
1428 function ByteFormatter ($bytes = 0, $longformat = false) {
1431 if ($bytes < 1024) {
1433 $size = fmt("%s b", $bytes);
1435 $size = fmt("%s bytes", $bytes);
1438 $kb = round($bytes / 1024, 1);
1440 $size = fmt("%s k", $kb);
1442 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1448 * Internationalized printf.
1450 * This is essentially the same as PHP's built-in printf
1451 * with the following exceptions:
1453 * <li> It passes the format string through gettext().
1454 * <li> It supports the argument reordering extensions.
1461 * __printf("Differences between versions %s and %s of %s",
1462 * $new_link, $old_link, $page_link);
1465 * Then in locale/po/de.po, one can reorder the printf arguments:
1468 * msgid "Differences between %s and %s of %s."
1469 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1472 * (Note that while PHP tries to expand $vars within double-quotes,
1473 * the values in msgstr undergo no such expansion, so the '$'s
1476 * One shouldn't use reordered arguments in the default format string.
1477 * Backslashes in the default string would be necessary to escape the
1478 * '$'s, and they'll cause all kinds of trouble....
1480 function __printf ($fmt) {
1481 $args = func_get_args();
1483 echo __vsprintf($fmt, $args);
1487 * Internationalized sprintf.
1489 * This is essentially the same as PHP's built-in printf with the
1490 * following exceptions:
1493 * <li> It passes the format string through gettext().
1494 * <li> It supports the argument reordering extensions.
1499 function __sprintf ($fmt) {
1500 $args = func_get_args();
1502 return __vsprintf($fmt, $args);
1506 * Internationalized vsprintf.
1508 * This is essentially the same as PHP's built-in printf with the
1509 * following exceptions:
1512 * <li> It passes the format string through gettext().
1513 * <li> It supports the argument reordering extensions.
1518 function __vsprintf ($fmt, $args) {
1519 $fmt = gettext($fmt);
1520 // PHP's sprintf doesn't support variable with specifiers,
1521 // like sprintf("%*s", 10, "x"); --- so we won't either.
1523 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1524 // Format string has '%2$s' style argument reordering.
1525 // PHP doesn't support this.
1526 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1527 // literal variable name substitution only to keep locale
1528 // strings uncluttered
1529 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1530 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1532 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1535 // Reorder arguments appropriately.
1536 foreach($m[1] as $argnum) {
1537 if ($argnum < 1 || $argnum > count($args))
1538 trigger_error(sprintf(_("%s: argument index out of range"),
1539 $argnum), E_USER_WARNING);
1540 $newargs[] = $args[$argnum - 1];
1545 // Not all PHP's have vsprintf, so...
1546 array_unshift($args, $fmt);
1547 return call_user_func_array('sprintf', $args);
1550 function file_mtime ($filename) {
1551 if ($stat = @stat($filename))
1557 function sort_file_mtime ($a, $b) {
1558 $ma = file_mtime($a);
1559 $mb = file_mtime($b);
1560 if (!$ma or !$mb or $ma == $mb) return 0;
1561 return ($ma > $mb) ? -1 : 1;
1566 * Build an array in $this->_fileList of files from $dirname.
1567 * Subdirectories are not traversed.
1569 * (This was a function LoadDir in lib/loadsave.php)
1570 * See also http://www.php.net/manual/en/function.readdir.php
1572 function getFiles($exclude='', $sortby='', $limit='') {
1573 $list = $this->_fileList;
1576 require_once('lib/PageList.php');
1577 switch (Pagelist::sortby($sortby, 'db')) {
1578 case 'pagename ASC': break;
1579 case 'pagename DESC':
1580 $list = array_reverse($list);
1583 usort($list,'sort_file_mtime');
1586 usort($list,'sort_file_mtime');
1587 $list = array_reverse($list);
1592 return array_splice($list, 0, $limit);
1596 function _filenameSelector($filename) {
1597 if (! $this->_pattern )
1600 if (! $this->_pcre_pattern )
1601 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1602 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1607 function fileSet($directory, $filepattern = false) {
1608 $this->_fileList = array();
1609 $this->_pattern = $filepattern;
1611 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1613 $this->_case = !isWindows();
1614 $this->_pathsep = '/';
1616 if (empty($directory)) {
1617 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1619 return; // early return
1622 @ $dir_handle = opendir($dir=$directory);
1623 if (empty($dir_handle)) {
1624 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1625 $dir), E_USER_NOTICE);
1626 return; // early return
1629 while ($filename = readdir($dir_handle)) {
1630 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1632 if ($this->_filenameSelector($filename)) {
1633 array_push($this->_fileList, "$filename");
1634 //trigger_error(sprintf(_("found file %s"), $filename),
1635 // E_USER_NOTICE); //debugging
1638 closedir($dir_handle);
1644 // expands a list containing regex's to its matching entries
1645 class ListRegexExpand {
1646 //var $match, $list, $index, $case_sensitive;
1647 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1648 $this->match = $match;
1649 $this->list = &$list;
1650 $this->case_sensitive = $case_sensitive;
1651 //$this->index = false;
1653 function listMatchCallback ($item, $key) {
1654 $quoted = str_replace('/','\/',$item);
1655 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1657 unset($this->list[$this->index]);
1658 $this->list[] = $item;
1661 function expandRegex ($index, &$pages) {
1662 $this->index = $index;
1663 array_walk($pages, array($this, 'listMatchCallback'));
1668 // Convert fileglob to regex style:
1669 // Convert some wildcards to pcre style, escape the rest
1670 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1671 // Fixed bug #994994: "/" in $glob.
1672 function glob_to_pcre ($glob) {
1673 // check simple case: no need to escape
1674 $escape = '\[](){}=!<>|:/';
1675 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1677 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1678 $glob = strtr($glob, "\\", "\xff");
1679 $glob = str_replace("/", "\\/", $glob);
1680 // first convert some unescaped expressions to pcre style: . => \.
1682 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1683 "\\1\xff\\2", $glob);
1686 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1687 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1688 if (!preg_match('/^[\?\*]/', $glob))
1690 if (!preg_match('/[\?\*]$/', $glob))
1693 // Fixes Bug 1182997
1694 // .*? handled above, now escape the rest
1695 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1696 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1698 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1700 $re = preg_replace('/\xff/', '', $re);
1704 function glob_match ($glob, $against, $case_sensitive = true) {
1705 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1709 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1710 $list = explode(',',$input);
1711 // expand wildcards from list of $allnames
1712 if (preg_match('/[\?\*]/',$input)) {
1713 // Optimizing loop invariants:
1714 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1715 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1717 if (preg_match('/[\?\*]/',$f)) {
1719 $expand = new ListRegexExpand($list,
1720 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1721 $expand->expandRegex($i, $allnames);
1728 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1729 function explodePageList($input, $include_empty=false, $sortby='pagename',
1730 $limit='', $exclude='') {
1731 include_once("lib/PageList.php");
1732 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1735 // Class introspections
1738 * Determine whether object is of a specified type.
1739 * In PHP builtin since 4.2.0 as is_a()
1740 * is_a() deprecated in PHP 5, in favor of instanceof operator
1742 * @param $object object An object.
1743 * @param $class string Class name.
1744 * @return bool True iff $object is a $class
1745 * or a sub-type of $class.
1747 function isa ($object, $class) {
1748 //if (check_php_version(5))
1749 // return $object instanceof $class;
1750 if (!check_php_version(5))
1751 return is_a($object, $class);
1753 $lclass = check_php_version(5) ? $class : strtolower($class);
1754 return is_object($object)
1755 && ( strtolower(get_class($object)) == strtolower($class)
1756 || is_subclass_of($object, $lclass) );
1759 /** Determine whether (possible) object has method.
1761 * @param $object mixed Object
1762 * @param $method string Method name
1763 * @return bool True iff $object is an object with has method $method.
1765 function can ($object, $method) {
1766 return is_object($object) && method_exists($object, strtolower($method));
1769 /** Determine whether a function is okay to use.
1771 * Some providers (e.g. Lycos) disable some of PHP functions for
1772 * "security reasons." This makes those functions, of course,
1773 * unusable, despite the fact the function_exists() says they
1776 * This function test to see if a function exists and is not
1777 * disallowed by PHP's disable_functions config setting.
1779 * @param string $function_name Function name
1780 * @return bool True iff function can be used.
1782 function function_usable($function_name) {
1784 if (!is_array($disabled)) {
1785 $disabled = array();
1786 // Use get_cfg_var since ini_get() is one of the disabled functions
1787 // (on Lycos, at least.)
1788 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1789 foreach ($split as $f)
1790 $disabled[strtolower($f)] = true;
1793 return ( function_exists($function_name)
1794 and ! isset($disabled[strtolower($function_name)])
1801 * This is used for generating ETags.
1803 function wikihash ($x) {
1804 if (is_scalar($x)) {
1807 elseif (is_array($x)) {
1809 return md5(serialize($x));
1811 elseif (is_object($x)) {
1814 trigger_error("Can't hash $x", E_USER_ERROR);
1819 * Seed the random number generator.
1821 * better_srand() ensures the randomizer is seeded only once.
1823 * How random do you want it? See:
1824 * http://www.php.net/manual/en/function.srand.php
1825 * http://www.php.net/manual/en/function.mt-srand.php
1827 function better_srand($seed = '') {
1828 static $wascalled = FALSE;
1830 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1831 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1833 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1837 function rand_ascii($length = 1) {
1840 for ($i = 1; $i <= $length; $i++) {
1841 // return only typeable 7 bit ascii, avoid quotes
1842 if (function_exists('mt_rand'))
1843 $s .= chr(mt_rand(40, 126));
1845 // the usually bad glibc srand()
1846 $s .= chr(rand(40, 126));
1851 /* by Dan Frankowski.
1853 function rand_ascii_readable ($length = 6) {
1854 // Pick a few random letters or numbers
1857 // Don't use 1lI0O, because they're hard to read
1858 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1859 $letter_len = strlen($letters);
1860 for ($i=0; $i < $length; $i++) {
1861 if (function_exists('mt_rand'))
1862 $word .= $letters[mt_rand(0, $letter_len-1)];
1864 $word .= $letters[rand(0, $letter_len-1)];
1870 * Recursively count all non-empty elements
1871 * in array of any dimension or mixed - i.e.
1872 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1873 * See http://www.php.net/manual/en/function.count.php
1875 function count_all($arg) {
1876 // skip if argument is empty
1878 //print_r($arg); //debugging
1880 // not an array, return 1 (base case)
1883 // else call recursively for all elements $arg
1884 foreach($arg as $key => $val)
1885 $count += count_all($val);
1890 function isSubPage($pagename) {
1891 return (strstr($pagename, SUBPAGE_SEPARATOR));
1894 function subPageSlice($pagename, $pos) {
1895 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1896 $pages = array_slice($pages,$pos,1);
1900 function isActionPage($filename) {
1902 global $AllActionPages;
1904 return (in_array($filename, $AllActionPages));
1910 * Class for "popping up" and alert box. (Except that right now, it doesn't
1914 * This is a hackish and needs to be refactored. However it would be nice to
1915 * unify all the different methods we use for showing Alerts and Dialogs.
1916 * (E.g. "Page deleted", login form, ...)
1921 * @param object $request
1922 * @param mixed $head Header ("title") for alert box.
1923 * @param mixed $body The text in the alert box.
1924 * @param hash $buttons An array mapping button labels to URLs.
1925 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1927 function Alert($head, $body, $buttons=false) {
1928 if ($buttons === false)
1931 if (is_array($body)) {
1933 foreach ($body as $li) {
1934 $html->pushContent(HTML::li($li));
1938 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1939 $this->_buttons = $buttons;
1943 * Show the alert box.
1948 $tokens = $this->_tokens;
1949 $tokens['BUTTONS'] = $this->_getButtons();
1951 $request->discardOutput();
1952 $tmpl = new Template('dialog', $request, $tokens);
1958 function _getButtons() {
1961 $buttons = $this->_buttons;
1963 $buttons = array(_("Okay") => $request->getURLtoSelf());
1966 foreach ($buttons as $label => $url)
1967 print "$label $url\n";
1968 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1969 return new XmlContent($out);
1974 // 1.3.9-p1 => 1030.091
1975 // 1.3.10pre => 1030.099
1976 // 1.3.11pre-20041120 => 1030.1120041120
1977 // 1.3.12-rc1 => 1030.119
1978 function phpwiki_version() {
1979 static $PHPWIKI_VERSION;
1980 if (!isset($PHPWIKI_VERSION)) {
1981 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1982 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1983 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1984 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1985 $PHPWIKI_VERSION -= 0.01;
1987 return $PHPWIKI_VERSION;
1990 function phpwiki_gzhandler($ob) {
1991 if (function_exists('gzencode'))
1992 $ob = gzencode($ob);
1993 $GLOBALS['request']->_ob_get_length = strlen($ob);
1994 if (!headers_sent()) {
1995 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
2000 function isWikiWord($word) {
2001 global $WikiNameRegexp;
2002 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
2003 return preg_match("/^$WikiNameRegexp\$/",$word);
2006 // needed to store serialized objects-values only (perm, pref)
2007 function obj2hash ($obj, $exclude = false, $fields = false) {
2009 if (! $fields ) $fields = get_object_vars($obj);
2010 foreach ($fields as $key => $val) {
2011 if (is_array($exclude)) {
2012 if (in_array($key, $exclude)) continue;
2020 * isAsciiString($string)
2022 function isAsciiString($s) {
2023 $ptrASCII = '[\x00-\x7F]';
2024 return preg_match("/^($ptrASCII)*$/s", $s);
2028 * isUtf8String($string) - cheap utf-8 detection
2030 * segfaults for strings longer than 10kb!
2031 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
2032 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
2034 function isUtf8String( $s ) {
2035 $ptrASCII = '[\x00-\x7F]';
2036 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
2037 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
2038 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
2039 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
2040 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
2041 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2045 * Check for UTF-8 URLs; Internet Explorer produces these if you
2046 * type non-ASCII chars in the URL bar or follow unescaped links.
2047 * Requires urldecoded pagename.
2048 * Fixes sf.net bug #953949
2050 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2052 function fixTitleEncoding( $s ) {
2057 if (empty($s)) return $s;
2059 $ishigh = preg_match( '/[\x80-\xff]/', $s);
2061 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2062 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
2064 $isutf = ($ishigh ? isUtf8String($s) : true);
2065 $locharset = strtolower($charset);
2067 if( $locharset != "utf-8" and $ishigh and $isutf )
2068 $s = charset_convert('UTF-8', $locharset, $s);
2069 if ($locharset == "utf-8" and $ishigh and !$isutf )
2070 return utf8_encode( $s );
2072 // Other languages can safely leave this function, or replace
2073 // it with one to detect and convert another legacy encoding.
2078 * MySQL fulltext index doesn't grok utf-8, so we
2079 * need to fold cases and convert to hex.
2080 * src: languages/Language.php:stripForSearch() from mediawiki
2083 function stripForSearch( $string ) {
2084 global $wikiLowerChars;
2085 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2086 return preg_replace(
2087 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2088 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2094 * Workaround for allow_url_fopen, to get the content of an external URI.
2095 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2096 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2098 function url_get_contents( $uri ) {
2099 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2100 return @file_get_contents($uri);
2102 require_once("lib/HttpClient.php");
2103 $bits = parse_url($uri);
2104 $host = $bits['host'];
2105 $port = isset($bits['port']) ? $bits['port'] : 80;
2106 $path = isset($bits['path']) ? $bits['path'] : '/';
2107 if (isset($bits['query'])) {
2108 $path .= '?'.$bits['query'];
2110 $client = new HttpClient($host, $port);
2111 $client->use_gzip = false;
2112 if (!$client->get($path)) {
2115 return $client->getContent();
2121 * Generate consecutively named strings:
2122 * Name, Name2, Name3, ...
2124 function GenerateId($name) {
2125 static $ids = array();
2126 if (empty($ids[$name])) {
2131 return $name . $ids[$name];
2135 // from IncludePage. To be of general use.
2136 // content: string or array of strings
2137 function firstNWordsOfContent( $n, $content ) {
2138 if ($content and $n > 0) {
2139 if (is_array($content)) {
2140 // fixme: return a list of lines then?
2141 //$content = join("\n", $content);
2142 //$return_array = true;
2144 foreach ($content as $line) {
2145 $words = explode(' ', $line);
2146 if ($wordcount + count($words) > $n) {
2147 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2148 . sprintf(_("... (first %s words)"), $n);
2151 $wordcount += count($words);
2157 // fixme: use better whitespace/word seperators
2158 $words = explode(' ', $content);
2159 if (count($words) > $n) {
2160 return join(' ', array_slice($words, 0, $n))
2161 . sprintf(_("... (first %s words)"), $n);
2171 // moved from lib/plugin/IncludePage.php
2172 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2173 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2175 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
2176 . " \\s*$\\n?" // possible blank lines
2177 . " ( (?: ^.*\\n? )*? )" // some lines
2178 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2179 implode("\n", $content),
2181 // Strip trailing blanks lines and ---- <hr>s
2182 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2184 $text = $match[1] . $section ."\n". $text;
2185 return explode("\n", $text);
2188 $mesg = $page ." ". $section;
2191 return array(sprintf(_("<%s: no such section>"), $mesg));
2194 // Extract the first $sections sections of the page
2195 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2197 $mycontent = $content;
2200 while ($sections > 0) {
2202 if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
2203 . " \\s*$\\n?" // possible blank lines
2204 . " ( (?: ^.*\\n? )*? )" // some lines
2205 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2206 implode("\n", $mycontent),
2208 $section = $match[2];
2209 // Strip trailing blanks lines and ---- <hr>s
2210 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2212 $text = $match[1] . $section ."\n". $text;
2215 $mycontent = explode("\n", $match[4]);
2217 if ($sections === 0) {
2218 return explode("\n", $result);
2224 // use this faster version: only load ExternalReferrer if we came from an external referrer
2225 function isExternalReferrer(&$request) {
2226 if ($referrer = $request->get('HTTP_REFERER')) {
2227 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2228 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2229 require_once("lib/ExternalReferrer.php");
2230 $se = new SearchEngines();
2231 return $se->parseSearchQuery($referrer);
2233 //if (DEBUG) return array('query' => 'wiki');
2238 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2240 function loadPhpExtension($extension) {
2241 if (!extension_loaded($extension)) {
2242 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2243 $soname = ($isWindows ? 'php_' : '')
2245 . ($isWindows ? '.dll' : '.so');
2249 return extension_loaded($extension);
2252 function charset_convert($from, $to, $data) {
2254 //$wikicharset = strtolower($CHARSET);
2255 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2256 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2257 return utf8_decode($data);
2258 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2259 return utf8_encode($data);
2261 if (loadPhpExtension("iconv")) {
2262 $tmpdata = iconv($from, $to, $data);
2264 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2268 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2273 function string_starts_with($string, $prefix) {
2274 return (substr($string, 0, strlen($prefix)) == $prefix);
2276 function string_ends_with($string, $suffix) {
2277 return (substr($string, -strlen($suffix)) == $suffix);
2279 function array_remove($arr,$value) {
2280 return array_values(array_diff($arr,array($value)));
2284 * Ensure that the script will have another $secs time left.
2285 * Works only if safe_mode is off.
2286 * For example not to timeout on waiting socket connections.
2287 * Use the socket timeout as arg.
2289 function longer_timeout($secs = 30) {
2290 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2291 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2292 if ($timeleft < $secs)
2293 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2296 function printSimpleTrace($bt) {
2298 echo "\nTraceback:\n";
2299 if (function_exists('debug_print_backtrace')) { // >= 5
2300 debug_print_backtrace();
2302 foreach ($bt as $i => $elem) {
2303 if (!array_key_exists('file', $elem)) {
2306 //echo join(" ",array_values($elem)),"\n";
2307 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2313 * Return the used process memory, in bytes.
2314 * Enable the section which will work for you. They are very slow.
2315 * Special quirks for Windows: Requires cygwin.
2317 function getMemoryUsage() {
2318 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2319 if (function_exists('memory_get_usage') and memory_get_usage()) {
2320 return memory_get_usage();
2321 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2322 $mem = $u['ru_maxrss'];
2323 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2324 // what we want is the process memory only: apache or php (if CGI)
2327 // win32_ps_stat_proc, win32_ps_stat_mem
2328 if (function_exists('win32_ps_list_procs')) {
2329 $info = win32_ps_stat_proc($pid);
2330 $memstr = $info['mem']['working_set_size'];
2332 // This works only if it's a cygwin process (apache or php).
2333 // Requires a newer cygwin
2334 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2336 // if it's native windows use something like this:
2337 // (requires pslist from sysinternals.com, grep, sed and perl)
2338 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2340 return (integer) trim($memstr);
2343 //%MEM: Percentage of total memory in use by this process
2344 //VSZ: Total virtual memory size, in 1K blocks.
2345 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2346 //CPU time used by process since it started.
2347 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2348 $memstr = exec("ps -orss -p $pid|sed 1d");
2349 return (integer) trim($memstr);
2354 * @param var $needle
2355 * @param array $haystack one-dimensional numeric array only, no hash
2357 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2358 It will return false if not found or the index where it was found.
2359 From dennis.decoene@moveit.be http://www.php.net/array_search
2361 function binary_search($needle, $haystack) {
2362 $high = count($haystack);
2365 while (($high - $low) > 1) {
2366 $probe = floor(($high + $low) / 2);
2367 if ($haystack[$probe] < $needle) {
2369 } elseif ($haystack[$probe] == $needle) {
2370 $high = $low = $probe;
2376 if ($high == count($haystack) || $haystack[$high] != $needle) {
2383 function is_localhost($url = false) {
2385 global $HTTP_SERVER_VARS;
2386 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2391 * Take a string and quote it sufficiently to be passed as a Javascript
2392 * string between ''s
2394 function javascript_quote_string($s) {
2395 return str_replace("'", "\'", $s);
2398 function isSerialized($s) {
2399 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2403 * Take a string and return an array of pairs (attribute name, attribute value)
2405 * We allow attributes with or without double quotes (")
2406 * Attribute-value pairs may be separated by space or comma
2407 * Space is normal HTML attributes, comma is for RichTable compatibility
2408 * border=1, cellpadding="5"
2409 * border=1 cellpadding="5"
2410 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2411 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2413 function parse_attributes($line) {
2417 if (empty($line)) return $options;
2418 $line = trim($line);
2419 if (empty($line)) return $options;
2420 $line = trim($line, ",");
2421 if (empty($line)) return $options;
2423 // First we have an attribute name.
2428 while (($i < strlen($line)) && ($line[$i] != '=')) {
2431 $attribute = substr($line, 0, $i);
2432 $attribute = strtolower($attribute);
2434 $line = substr($line, $i+1);
2435 $line = trim ($line);
2436 $line = trim ($line, "=");
2437 $line = trim ($line);
2439 if (empty($line)) return $options;
2441 // Then we have the attribute value.
2444 // Attribute value might be between double quotes
2445 // In that case we have to find the closing double quote
2446 if ($line[0] == '"') {
2447 $i++; // skip first '"'
2448 while (($i < strlen($line)) && ($line[$i] != '"')) {
2451 $value = substr($line, 0, $i);
2452 $value = trim ($value, '"');
2453 $value = trim ($value);
2455 // If there are no double quotes, we have to find the next space or comma
2457 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2460 $value = substr($line, 0, $i);
2461 $value = trim ($value);
2462 $value = trim ($value, ",");
2463 $value = trim ($value);
2466 $options[$attribute] = $value;
2468 $line = substr($line, $i+1);
2469 $line = trim ($line);
2470 $line = trim ($line, ",");
2471 $line = trim ($line);
2473 return $options + parse_attributes($line);
2477 * Returns true if the filename ends with an image suffix.
2478 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2480 function is_image ($filename) {
2482 if (defined('INLINE_IMAGES')) {
2483 $inline_images = INLINE_IMAGES;
2485 $inline_images = "png|jpg|jpeg|gif";
2488 foreach (explode("|", $inline_images) as $suffix) {
2489 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2497 * Returns true if the filename ends with an video suffix.
2498 * Currently only FLV and OGG
2500 function is_video ($filename) {
2502 return string_ends_with(strtolower($filename), ".flv")
2503 or string_ends_with(strtolower($filename), ".ogg");
2507 * Compute cell in spreadsheet table
2508 * $table: two-dimensional table
2509 * $i and $j: indexes of cell to compute
2510 * $imax and $jmax: table dimensions
2512 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2514 // What is implemented:
2515 // @@=SUM(R)@@ : sum of cells in current row
2516 // @@=SUM(C)@@ : sum of cells in current column
2517 // @@=AVERAGE(R)@@ : average of cells in current row
2518 // @@=AVERAGE(C)@@ : average of cells in current column
2519 // @@=MAX(R)@@ : maximum value of cells in current row
2520 // @@=MAX(C)@@ : maximum value of cells in current column
2521 // @@=MIN(R)@@ : minimum value of cells in current row
2522 // @@=MIN(C)@@ : minimum value of cells in current column
2523 // @@=COUNT(R)@@ : number of cells in current row
2524 // (numeric or not, excluding headers and current cell)
2525 // @@=COUNT(C)@@ : number of cells in current column
2526 // (numeric or not, excluding headers and current cell)
2532 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2533 for ($index=0; $index<$imax; $index++) {
2534 if (is_numeric($table[$index][$j])) {
2535 $result += $table[$index][$j];
2538 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2540 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2541 for ($index=0; $index<$jmax; $index++) {
2542 if (is_numeric($table[$i][$index])) {
2543 $result += $table[$i][$index];
2546 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2548 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2549 for ($index=0; $index<$imax; $index++) {
2550 if (is_numeric($table[$index][$j])) {
2551 $result += $table[$index][$j];
2555 $result=$result/$counter;
2556 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2558 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2559 for ($index=0; $index<$jmax; $index++) {
2560 if (is_numeric($table[$i][$index])) {
2561 $result += $table[$i][$index];
2565 $result=$result/$counter;
2566 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2568 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2569 for ($index=0; $index<$imax; $index++) {
2570 if (is_numeric($table[$index][$j])) {
2573 $result=$table[$index][$j];
2575 $result = max($result, $table[$index][$j]);
2582 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2584 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2585 for ($index=0; $index<$jmax; $index++) {
2586 if (is_numeric($table[$i][$index])) {
2589 $result=$table[$i][$index];
2591 $result = max($result, $table[$i][$index]);
2598 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2600 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2601 for ($index=0; $index<$imax; $index++) {
2602 if (is_numeric($table[$index][$j])) {
2605 $result=$table[$index][$j];
2607 $result = min($result, $table[$index][$j]);
2614 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2616 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2617 for ($index=0; $index<$jmax; $index++) {
2618 if (is_numeric($table[$i][$index])) {
2621 $result=$table[$i][$index];
2623 $result = min($result, $table[$i][$index]);
2630 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2632 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2633 for ($index=0; $index<$imax; $index++) {
2634 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2638 $result = $counter-1; // exclude self
2639 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2641 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2642 for ($index=0; $index<$jmax; $index++) {
2643 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2647 $result = $counter-1; // exclude self
2648 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2651 return $table[$i][$j];
2655 * Remove accents from given text.
2657 function strip_accents($text) {
2658 $res = utf8_decode($text);
2660 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2661 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2662 return utf8_encode($res);
2665 // (c-file-style: "gnu")
2669 // c-basic-offset: 4
2670 // c-hanging-comment-ender-p: nil
2671 // indent-tabs-mode: nil