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)
102 compute_tablecell ($table, $i, $j, $imax, $jmax)
104 function: LinkInterWikiLink($link, $linktext)
105 moved to: lib/interwiki.php
106 function: linkExistingWikiWord($wikiword, $linktext, $version)
107 moved to: lib/WikiTheme.php
108 function: LinkUnknownWikiWord($wikiword, $linktext)
109 moved to: lib/WikiTheme.php
110 function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
111 gone see: lib/plugin/RecentChanges.php
113 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
114 else define('_PHPWIKI_STDLIB_LOADED', true);
116 define('MAX_PAGENAME_LENGTH', 100);
119 * Convert string to a valid XML identifier.
121 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
123 * We would like to have, e.g. named anchors within wiki pages
124 * names like "Table of Contents" --- clearly not a valid XML
125 * fragment identifier.
127 * This function implements a one-to-one map from {any string}
128 * to {valid XML identifiers}.
131 * converting all bytes not in [A-Za-z0-9:_-],
132 * and any leading byte not in [A-Za-z] to 'xbb.',
133 * where 'bb' is the hexadecimal representation of the
136 * As a special case, the empty string is converted to 'empty.'
141 function MangleXmlIdentifier($str) {
145 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
146 "'x' . sprintf('%02x', ord('\\0')) . '.'",
150 function UnMangleXmlIdentifier($str) {
151 if ($str == 'empty.')
153 return preg_replace('/x(\w\w)\./e',
154 "sprintf('%c', hex('\\0'))",
159 * Returns a name for the WIKI_ID cookie that should be unique on the host.
160 * But for it to be unique you must have set a unique WIKI_NAME in your
161 * configuration file.
162 * @return string The name of the WIKI_ID cookie to use for this wiki.
164 function GetCookieName() {
165 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
169 * Generates a valid URL for a given Wiki pagename.
170 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
171 * If a WikiDB_Page object function will extract the name to link to.
172 * If a WikiDB_PageRevision object function will extract the name to link to.
174 * @param boolean $get_abs_url Default value is false.
175 * @return string The absolute URL to the page passed as $pagename.
177 function WikiURL($pagename, $args = '', $get_abs_url = false) {
178 global $request, $WikiTheme;
181 if (is_object($pagename)) {
182 if (isa($pagename, 'WikiDB_Page')) {
183 $pagename = $pagename->getName();
185 elseif (isa($pagename, 'WikiDB_PageRevision')) {
186 $page = $pagename->getPage();
187 $args['version'] = $pagename->getVersion();
188 $pagename = $page->getName();
190 elseif (isa($pagename, 'WikiPageName')) {
191 $anchor = $pagename->anchor;
192 $pagename = $pagename->name;
194 $anchor = $pagename->anchor;
195 $pagename = $pagename->name;
198 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
200 $args = 'start_debug=' . $request->getArg('start_debug');
201 elseif (is_array($args))
202 $args['start_debug'] = $request->getArg('start_debug');
204 $args .= '&start_debug=' . $request->getArg('start_debug');
206 if (is_array($args)) {
208 foreach ($args as $key => $val) {
209 // avoid default args
210 if (USE_PATH_INFO and $key == 'pagename')
212 elseif ($key == 'action' and $val == 'browse')
214 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
215 $enc_args[] = urlencode($key) . '=' . urlencode($val);
217 $args = join('&', $enc_args);
220 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
221 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
222 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
224 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
225 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
226 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
229 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
231 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
241 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
242 $url .= "?pagename=" . rawurlencode($pagename);
247 $url .= "#" . MangleXmlIdentifier($anchor);
251 /** Convert relative URL to absolute URL.
253 * This converts a relative URL to one of PhpWiki's support files
254 * to an absolute one.
257 * @return string Absolute URL
259 function AbsoluteURL ($url) {
260 if (preg_match('/^https?:/', $url))
262 if ($url[0] != '/') {
263 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
264 while ($base != '/' and substr($url, 0, 3) == "../") {
265 $url = substr($url, 3);
266 $base = dirname($base);
272 return SERVER_URL . $url;
275 function DataURL ($url) {
276 if (preg_match('/^https?:/', $url))
278 $url = NormalizeWebFileName($url);
279 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
280 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
281 return AbsoluteURL($url);
285 * Generates icon in front of links.
287 * @param string $protocol_or_url URL or protocol to determine which icon to use.
289 * @return HtmlElement HtmlElement object that contains data to create img link to
290 * icon for use with url or protocol passed to the function. False if no img to be
293 function IconForLink($protocol_or_url) {
295 if (0 and $filename_suffix == false) {
296 // display apache style icon for file type instead of protocol icon
297 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
298 // - document: html, htm, text, txt, rtf, pdf, doc
299 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
300 // - audio: mp3,mp2,aiff,aif,au
301 // - multimedia: mpeg,mpg,mov,qt
303 list ($proto) = explode(':', $protocol_or_url, 2);
304 $src = $WikiTheme->getLinkIconURL($proto);
306 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
313 * Glue icon in front of or after text.
314 * Pref: 'noLinkIcons' - ignore icon if set
315 * WikiTheme: 'LinkIcons' - 'yes' at front
316 * - 'no' display no icon
317 * - 'front' display at left
318 * - 'after' display at right
320 * @param string $protocol_or_url Protocol or URL. Used to determine the
322 * @param string $text The text.
323 * @return XmlContent.
325 function PossiblyGlueIconToText($proto_or_url, $text) {
326 global $request, $WikiTheme;
327 if ($request->getPref('noLinkIcons'))
329 $icon = IconForLink($proto_or_url);
332 if ($where = $WikiTheme->getLinkIconAttr()) {
333 if ($where == 'no') return $text;
334 if ($where != 'after') $where = 'front';
338 if ($where == 'after') {
339 // span the icon only to the last word (tie them together),
340 // to let the previous words wrap on line breaks.
341 if (!is_object($text)) {
342 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
343 list (, $prefix, $last_word) = $m;
349 $text = HTML::span(array('style' => 'white-space: nowrap'),
350 $last_word, HTML::Raw(' '), $icon);
352 $text = HTML($prefix, $text);
355 // span the icon only to the first word (tie them together),
356 // to let the next words wrap on line breaks
357 if (!is_object($text)) {
358 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
359 list (, $first_word, $tail) = $m;
365 $text = HTML::span(array('style' => 'white-space: nowrap'),
368 $text = HTML($text, $tail);
373 * Determines if the url passed to function is safe, by detecting if the characters
374 * '<', '>', or '"' are present.
375 * Check against their urlencoded values also.
377 * @param string $url URL to check for unsafe characters.
378 * @return boolean True if same, false else.
380 function IsSafeURL($url) {
381 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
385 * Generates an HtmlElement object to store data for a link.
387 * @param string $url URL that the link will point to.
388 * @param string $linktext Text to be displayed as link.
389 * @return HtmlElement HtmlElement object that contains data to construct an html link.
391 function LinkURL($url, $linktext = '') {
392 // FIXME: Is this needed (or sufficient?)
393 if(! IsSafeURL($url)) {
394 $link = HTML::span(array('class' => 'error'), _("BAD URL -- remove all of <, >, \""));
399 $linktext = preg_replace("/mailto:/A", "", $url);
400 $args = array('href' => $url);
401 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
402 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
403 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
405 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
412 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
413 * Disallows sizes which are too small.
414 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
416 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
418 function LinkImage($url, $alt = "") {
419 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
420 // Disallow tags in img src urls. Typical CSS attacks.
421 // FIXME: Is this needed (or sufficient?)
422 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
424 // support new syntax: [prefix/image.jpg size=50% border=n]
425 if (empty($alt)) $alt = "";
428 $arr = split(' ',$url);
429 if (!empty($arr)) $url = $arr[0];
430 if (! IsSafeURL($url)) {
431 $link = HTML::span(array('class' => 'error'), _("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 == "height") || ($attr == "width"))
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 $params = explode(",","data,classid,archive,codebase,name,usemap,type,".
604 "codetype,standby,tabindex,declare");
605 if (is_array($url)) {
608 foreach ($args as $attr => $value) {
609 foreach ($params as $param) {
610 if ($param == $attr) {
611 $img->setAttr($param, $value);
612 if (isset($found[$param])) $found[$param]++;
613 else $found[$param] = 1;
618 // now all remaining args are added as <param> to the object
620 foreach ($args as $attr => $value) {
621 if (!isset($found[$attr])) {
622 $params[] = HTML::param(array('name' => $attr,
626 $url = $img->getAttr('src');
627 $force_img = "png|jpg|gif|jpeg|bmp";
628 if (!preg_match("/\.(".$force_img.")/i", $url)) {
629 $img->setAttr('src', false);
632 $args = split(' ', $url);
633 if (count($args) >= 1) {
634 $url = array_shift($args);
636 foreach ($args as $attr) {
637 foreach ($params as $param) {
638 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
639 $img->setAttr($param, $m[1]);
640 if (isset($found[$param])) $found[$param]++;
641 else $found[$param] = 1;
646 // now all remaining args are added as <param> to the object
648 foreach ($args as $attr) {
649 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
650 $params[] = HTML::param(array('name' => $m[1],
656 $type = $img->getAttr('type');
658 // TODO: map extension to mime-types if type is not given and php < 4.3
659 if (function_exists('mime_content_type'))
660 $type = mime_content_type($url);
662 $object = HTML::object(array_merge($img->_attr,
663 array('type' => $type)), //'src' => $url
665 $object->setAttr('class', 'inlineobject');
667 foreach ($params as $param) $object->pushContent($param);
669 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
670 return HTML::embed($object->_attr, $object->_content);
672 $object->pushContent(HTML::embed($object->_attr));
679 // var in php5 deprecated
681 $this->items = array();
684 function push($item) {
685 $this->items[$this->size] = $item;
691 if ($this->size == 0) {
692 return false; // stack is empty
695 return $this->items[$this->size];
704 return $this->items[$this->size - 1];
710 // end class definition
712 function SplitQueryArgs ($query_args = '')
714 // FIXME: use the arg-seperator which might not be &
715 $split_args = split('&', $query_args);
717 while (list($key, $val) = each($split_args))
718 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
719 $args[$m[1]] = $m[2];
723 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
726 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
727 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
731 $pagename = urldecode($m[1]);
734 if (empty($pagename) &&
735 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
736 // Convert old style links (to not break diff links in
738 $pagename = urldecode($m[2]);
739 $args = array("action" => $m[1]);
742 $args = SplitQueryArgs($qargs);
745 if (empty($pagename))
746 $pagename = $GLOBALS['request']->getArg('pagename');
748 if (isset($args['action']) && $args['action'] == 'browse')
749 unset($args['action']);
752 if (empty($args['action']))
754 else if (is_safe_action($args['action']))
755 $class = 'wikiaction';
757 if (empty($args['action']) || is_safe_action($args['action']))
758 $class = 'wikiaction';
760 // Don't allow administrative links on unlocked pages.
761 $dbi = $GLOBALS['request']->getDbh();
762 $page = $dbi->getPage($basepage ? $basepage : $pagename);
763 if (!$page->get('locked'))
764 return HTML::span(array('class' => 'wikiunsafe'),
765 HTML::u(_("Lock page to enable link")));
766 $class = 'wikiadmin';
770 $text = HTML::span(array('class' => 'rawurl'), $url);
772 $wikipage = new WikiPageName($pagename);
773 if (!$wikipage->isValid()) {
775 return $WikiTheme->linkBadWikiWord($wikipage, $url);
778 return HTML::a(array('href' => WikiURL($pagename, $args),
784 * A class to assist in parsing wiki pagenames.
786 * Now with subpages and anchors, parsing and passing around
787 * pagenames is more complicated. This should help.
791 /** Short name for page.
793 * This is the value of $name passed to the constructor.
794 * (For use, e.g. as a default label for links to the page.)
798 /** The full page name.
800 * This is the full name of the page (without anchor).
806 * This is the referenced anchor within the page, or the empty string.
812 * @param mixed $name Page name.
813 * WikiDB_Page, WikiDB_PageRevision, or string.
814 * This can be a relative subpage name (like '/SubPage'),
815 * or can be the empty string to refer to the $basename.
817 * @param string $anchor For links to anchors in page.
819 * @param mixed $basename Page name from which to interpret
820 * relative or other non-fully-specified page names.
822 function WikiPageName($name, $basename=false, $anchor=false) {
823 if (is_string($name)) {
824 $this->shortName = $name;
825 if (strstr($name, ':')) {
826 list($moniker, $shortName) = split (":", $name, 2);
827 $map = getInterwikiMap(); // allow overrides to custom maps
828 if (isset($map->_map[$moniker])) {
829 $url = $map->_map[$moniker];
830 if (strstr($url, '%s'))
831 $url = sprintf($url, $shortName);
835 // expand Talk or User, but not to absolute urls!
836 if (strstr($url, '//')) {
837 if ($moniker == 'Talk')
838 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
839 elseif ($moniker == 'User')
844 if (strstr($shortName, '?')) {
845 list($shortName, $dummy) = split("\?", $shortName, 2);
847 $this->shortName = $shortName;
850 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
851 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
853 $name = $this->_pagename($basename) . $name;
855 $name = $this->_normalize_bad_pagename($name);
856 $this->shortName = $name;
861 $name = $this->_pagename($name);
862 $this->shortName = $name;
865 $this->name = $this->_check($name);
866 $this->anchor = (string)$anchor;
873 function getParent() {
875 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
877 return substr($name, 0, -strlen($tail));
880 function isValid($strict = false) {
882 return !isset($this->_errors);
883 return (is_string($this->name) and $this->name != '');
886 function getWarnings() {
888 if (isset($this->_warnings))
889 $warnings = array_merge($warnings, $this->_warnings);
890 if (isset($this->_errors))
891 $warnings = array_merge($warnings, $this->_errors);
895 return sprintf(_("'%s': Bad page name: %s"),
896 $this->shortName, join(', ', $warnings));
899 function _pagename($page) {
900 if (isa($page, 'WikiDB_Page'))
901 return $page->getName();
902 elseif (isa($page, 'WikiDB_PageRevision'))
903 return $page->getPageName();
904 elseif (isa($page, 'WikiPageName'))
906 // '0' or e.g. '1984' should be allowed though
907 if (!is_string($page) and !is_integer($page)) {
908 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
909 $page, gettype($page), get_class($page)),
912 //assert(is_string($page));
916 function _normalize_bad_pagename($name) {
917 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
919 // Punt... You really shouldn't get here.
922 return $request->getArg('pagename');
924 assert($name[0] == SUBPAGE_SEPARATOR);
925 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
926 return substr($name, 1);
930 * Compress internal white-space to single space character.
932 * This leads to problems with loading a foreign charset pagename,
933 * which cannot be deleted anymore, because unknown chars are compressed.
934 * So BEFORE importing a file _check must be done !!!
936 function _check($pagename) {
937 // Compress internal white-space to single space character.
938 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
939 if ($pagename != $orig)
940 $this->_warnings[] = _("White space converted to single space");
942 // Delete any control characters.
943 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
944 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
945 if ($pagename != $orig)
946 $this->_errors[] = _("Control characters not allowed");
949 // Strip leading and trailing white-space.
950 $pagename = trim($pagename);
953 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
954 $pagename = substr($pagename, 1);
955 if ($pagename != $orig)
956 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
958 // ";" is urlencoded, so safe from php arg-delim problems
959 /*if (strstr($pagename, ';')) {
960 $this->_warnings[] = _("';' is deprecated");
961 $pagename = str_replace(';', '', $pagename);
964 // not only for SQL, also to restrict url length
965 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
966 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
967 $this->_errors[] = _("too long");
970 // disallow some chars only on file and cvs
971 if ((DATABASE_TYPE == 'cvs'
972 or DATABASE_TYPE == 'file'
973 or DATABASE_TYPE == 'flatfile')
974 and preg_match('/(:|\.\.)/', $pagename, $m))
976 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
977 $pagename = str_replace('..', '', $pagename);
978 $pagename = str_replace(':', '', $pagename);
986 * Convert old page markup to new-style markup.
988 * @param string $text Old-style wiki markup.
990 * @param string $markup_type
992 * <dt><code>"block"</code> <dd>Convert all markup.
993 * <dt><code>"inline"</code> <dd>Convert only inline markup.
994 * <dt><code>"links"</code> <dd>Convert only link markup.
997 * @return string New-style wiki markup.
999 * @bugs Footnotes don't work quite as before (esp if there are
1000 * multiple references to the same footnote. But close enough,
1001 * probably for now....
1002 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
1003 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
1004 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1005 * also known to crash, even with Apache1.
1007 function ConvertOldMarkup ($text, $markup_type = "block") {
1013 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
1014 // AnciennesR%E8glesDeFormatage crashes.
1015 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1016 // also known to crash, even with Apache1.
1017 $debug_skip = false;
1018 // I suspect this only to crash with Apache2 and IIS.
1019 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
1020 and preg_match("/plugin CreateToc/", $text))
1022 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
1023 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
1024 ._("Skipped."), E_USER_WARNING);
1026 //if (!DEBUG) return $text;
1031 /*****************************************************************
1032 * Conversions for inline markup:
1039 // escape escaped brackets
1043 // change ! escapes to ~'s.
1044 global $WikiNameRegexp, $request;
1045 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1046 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1047 if (check_php_version(4,3,9)) {
1048 $map = getInterwikiMap();
1049 if ($map_regex = $map->getRegexp())
1050 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1052 $bang_esc[] = $WikiNameRegexp;
1053 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1056 $subs["links"] = array($orig, $repl);
1058 // Temporarily URL-encode pairs of underscores in links to hide
1059 // them from the re for bold markup.
1060 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1061 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1064 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1067 // Convert footnote references.
1068 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1069 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1071 // Convert old style emphases to HTML style emphasis.
1072 $orig[] = '/__(.*?)__/';
1073 $repl[] = '<strong>\\1</strong>';
1074 $orig[] = "/''(.*?)''/";
1075 $repl[] = '<em>\\1</em>';
1077 // Escape nestled markup.
1078 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1081 // in old markup headings only allowed at beginning of line
1085 // Convert URL-encoded pairs of underscores in links back to
1086 // real underscores after bold markup has been converted.
1087 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1088 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1090 $subs["inline"] = array($orig, $repl);
1092 /*****************************************************************
1093 * Patterns which match block markup constructs which take
1094 * special handling...
1098 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1100 $blockpats[] = '\|(?:.*\n\|)*';
1103 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1105 // Footnote definitions
1106 $blockpats[] = '\[\s*(\d+)\s*\]';
1110 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1114 $blockpats[] = '!{1,3}[^!]';
1116 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1117 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1119 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1120 . join("|", $blockpats)
1125 if ($markup_type != "block") {
1126 list ($orig, $repl) = $subs[$markup_type];
1127 return preg_replace($orig, $repl, $text);
1130 list ($orig, $repl) = $subs['inline'];
1133 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1134 // AnciennesR%E8glesDeFormatage and more
1135 // See http://www.pcre.org/pcre.txt LIMITATIONS
1136 while (preg_match($block_re, $text, $m)) {
1137 $text = substr($text, strlen($m[0]));
1138 list (,$leading_text, $block) = $m;
1141 if (strchr(" \t", $block[0])) {
1143 $prefix = "<pre>\n";
1144 $suffix = "\n</pre>\n";
1146 elseif ($block[0] == '|') {
1148 $prefix = "<?plugin OldStyleTable\n";
1151 elseif (strchr("#*;", $block[0])) {
1152 // Old-style list item
1153 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1154 list (,$ind,$bullet) = $m;
1155 $block = substr($block, strlen($m[0]));
1157 $indent = str_repeat(' ', strlen($ind));
1158 if ($bullet[0] == ';') {
1159 //$term = ltrim(substr($bullet, 1));
1160 //return $indent . $term . "\n" . $indent . ' ';
1161 $prefix = $ind . $bullet;
1164 $prefix = $indent . $bullet . ' ';
1166 elseif ($block[0] == '[') {
1167 // Footnote definition
1168 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1170 $block = substr($block, strlen($m[0]));
1171 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1173 elseif ($block[0] == '<') {
1175 // HACK: no inline markup...
1179 elseif ($block[0] == '!') {
1181 preg_match('/^!{1,3}/', $block, $m);
1183 $block = substr($block, strlen($m[0]));
1189 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1190 if ($block) $block = preg_replace($orig, $repl, $block);
1191 $out .= $leading_text;
1196 return $out . preg_replace($orig, $repl, $text);
1202 * Expand tabs in string.
1204 * Converts all tabs to (the appropriate number of) spaces.
1206 * @param string $str
1207 * @param integer $tab_width
1210 function expand_tabs($str, $tab_width = 8) {
1211 $split = split("\t", $str);
1212 $tail = array_pop($split);
1214 foreach ($split as $hunk) {
1216 $pos = strlen(strrchr($expanded, "\n")) - 1;
1217 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1219 return substr($expanded, 1) . $tail;
1223 * Split WikiWords in page names.
1225 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1226 * places like page titles. This is rumored to help search engines
1229 * @param $page string The page name.
1231 * @return string The split name.
1233 function SplitPagename ($page) {
1235 if (preg_match("/\s/", $page))
1236 return $page; // Already split --- don't split any more.
1238 // This algorithm is specialized for several languages.
1239 // (Thanks to Pierrick MEIGNEN)
1240 // Improvements for other languages welcome.
1243 // This mess splits between a lower-case letter followed by
1244 // either an upper-case or a numeral; except that it wont
1245 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1246 switch ($GLOBALS['LANG']) {
1251 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1254 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1257 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1258 // This the single-letter words 'I' and 'A' from any following
1259 // capitalized words.
1260 switch ($GLOBALS['LANG']) {
1262 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1265 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1268 // Split at underscore
1269 $RE[] = '/(_)([[:alpha:]])/';
1270 $RE[] = '/([[:alpha:]])(_)/';
1271 // Split numerals from following letters.
1272 $RE[] = '/(\d)([[:alpha:]])/';
1273 // Split at subpage seperators. TBD in WikiTheme.php
1274 $RE[] = "/([^${sep}]+)(${sep})/";
1275 $RE[] = "/(${sep})([^${sep}]+)/";
1277 foreach ($RE as $key)
1278 $RE[$key] = pcre_fix_posix_classes($key);
1281 foreach ($RE as $regexp) {
1282 $page = preg_replace($regexp, '\\1 \\2', $page);
1287 function NoSuchRevision (&$request, $page, $version) {
1288 $html = HTML(HTML::h2(_("Revision Not Found")),
1289 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1290 $version, WikiLink($page, 'auto'))));
1291 include_once('lib/Template.php');
1292 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1298 * Get time offset for local time zone.
1300 * @param $time time_t Get offset for this time. Default: now.
1301 * @param $no_colon boolean Don't put colon between hours and minutes.
1302 * @return string Offset as a string in the format +HH:MM.
1304 function TimezoneOffset ($time = false, $no_colon = false) {
1305 if ($time === false)
1307 $secs = date('Z', $time);
1316 $colon = $no_colon ? '' : ':';
1317 $mins = intval(($secs + 30) / 60);
1318 return sprintf("%s%02d%s%02d",
1319 $sign, $mins / 60, $colon, $mins % 60);
1324 * Format time in ISO-8601 format.
1326 * @param $time time_t Time. Default: now.
1327 * @return string Date and time in ISO-8601 format.
1329 function Iso8601DateTime ($time = false) {
1330 if ($time === false)
1332 $tzoff = TimezoneOffset($time);
1333 $date = date('Y-m-d', $time);
1334 $time = date('H:i:s', $time);
1335 return $date . 'T' . $time . $tzoff;
1339 * Format time in RFC-2822 format.
1341 * @param $time time_t Time. Default: now.
1342 * @return string Date and time in RFC-2822 format.
1344 function Rfc2822DateTime ($time = false) {
1345 if ($time === false)
1347 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1351 * Format time in RFC-1123 format.
1353 * @param $time time_t Time. Default: now.
1354 * @return string Date and time in RFC-1123 format.
1356 function Rfc1123DateTime ($time = false) {
1357 if ($time === false)
1359 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1362 /** Parse date in RFC-1123 format.
1364 * According to RFC 1123 we must accept dates in the following
1367 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1368 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1369 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1371 * (Though we're only allowed to generate dates in the first format.)
1373 function ParseRfc1123DateTime ($timestr) {
1374 $timestr = trim($timestr);
1375 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1376 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1378 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1380 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1381 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1383 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1384 if ($year < 70) $year += 2000;
1385 elseif ($year < 100) $year += 1900;
1387 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1388 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1390 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1397 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1399 return false; // failed
1404 * Format time to standard 'ctime' format.
1406 * @param $time time_t Time. Default: now.
1407 * @return string Date and time.
1409 function CTime ($time = false)
1411 if ($time === false)
1413 return date("D M j H:i:s Y", $time);
1418 * Format number as kilobytes or bytes.
1419 * Short format is used for PageList
1420 * Long format is used in PageInfo
1422 * @param $bytes int. Default: 0.
1423 * @param $longformat bool. Default: false.
1424 * @return class FormattedText (XmlElement.php).
1426 function ByteFormatter ($bytes = 0, $longformat = false) {
1429 if ($bytes < 1024) {
1431 $size = fmt("%s b", $bytes);
1433 $size = fmt("%s bytes", $bytes);
1436 $kb = round($bytes / 1024, 1);
1438 $size = fmt("%s k", $kb);
1440 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1446 * Internationalized printf.
1448 * This is essentially the same as PHP's built-in printf
1449 * with the following exceptions:
1451 * <li> It passes the format string through gettext().
1452 * <li> It supports the argument reordering extensions.
1459 * __printf("Differences between versions %s and %s of %s",
1460 * $new_link, $old_link, $page_link);
1463 * Then in locale/po/de.po, one can reorder the printf arguments:
1466 * msgid "Differences between %s and %s of %s."
1467 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1470 * (Note that while PHP tries to expand $vars within double-quotes,
1471 * the values in msgstr undergo no such expansion, so the '$'s
1474 * One shouldn't use reordered arguments in the default format string.
1475 * Backslashes in the default string would be necessary to escape the
1476 * '$'s, and they'll cause all kinds of trouble....
1478 function __printf ($fmt) {
1479 $args = func_get_args();
1481 echo __vsprintf($fmt, $args);
1485 * Internationalized sprintf.
1487 * This is essentially the same as PHP's built-in printf with the
1488 * following exceptions:
1491 * <li> It passes the format string through gettext().
1492 * <li> It supports the argument reordering extensions.
1497 function __sprintf ($fmt) {
1498 $args = func_get_args();
1500 return __vsprintf($fmt, $args);
1504 * Internationalized vsprintf.
1506 * This is essentially the same as PHP's built-in printf with the
1507 * following exceptions:
1510 * <li> It passes the format string through gettext().
1511 * <li> It supports the argument reordering extensions.
1516 function __vsprintf ($fmt, $args) {
1517 $fmt = gettext($fmt);
1518 // PHP's sprintf doesn't support variable with specifiers,
1519 // like sprintf("%*s", 10, "x"); --- so we won't either.
1521 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1522 // Format string has '%2$s' style argument reordering.
1523 // PHP doesn't support this.
1524 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1525 // literal variable name substitution only to keep locale
1526 // strings uncluttered
1527 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1528 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1530 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1533 // Reorder arguments appropriately.
1534 foreach($m[1] as $argnum) {
1535 if ($argnum < 1 || $argnum > count($args))
1536 trigger_error(sprintf(_("%s: argument index out of range"),
1537 $argnum), E_USER_WARNING);
1538 $newargs[] = $args[$argnum - 1];
1543 // Not all PHP's have vsprintf, so...
1544 array_unshift($args, $fmt);
1545 return call_user_func_array('sprintf', $args);
1548 function file_mtime ($filename) {
1549 if ($stat = @stat($filename))
1555 function sort_file_mtime ($a, $b) {
1556 $ma = file_mtime($a);
1557 $mb = file_mtime($b);
1558 if (!$ma or !$mb or $ma == $mb) return 0;
1559 return ($ma > $mb) ? -1 : 1;
1564 * Build an array in $this->_fileList of files from $dirname.
1565 * Subdirectories are not traversed.
1567 * (This was a function LoadDir in lib/loadsave.php)
1568 * See also http://www.php.net/manual/en/function.readdir.php
1570 function getFiles($exclude='', $sortby='', $limit='') {
1571 $list = $this->_fileList;
1574 require_once('lib/PageList.php');
1575 switch (Pagelist::sortby($sortby, 'db')) {
1576 case 'pagename ASC': break;
1577 case 'pagename DESC':
1578 $list = array_reverse($list);
1581 usort($list,'sort_file_mtime');
1584 usort($list,'sort_file_mtime');
1585 $list = array_reverse($list);
1590 return array_splice($list, 0, $limit);
1594 function _filenameSelector($filename) {
1595 if (! $this->_pattern )
1598 if (! $this->_pcre_pattern )
1599 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1600 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1605 function fileSet($directory, $filepattern = false) {
1606 $this->_fileList = array();
1607 $this->_pattern = $filepattern;
1609 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1611 $this->_case = !isWindows();
1612 $this->_pathsep = '/';
1614 if (empty($directory)) {
1615 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1617 return; // early return
1620 @ $dir_handle = opendir($dir=$directory);
1621 if (empty($dir_handle)) {
1622 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1623 $dir), E_USER_NOTICE);
1624 return; // early return
1627 while ($filename = readdir($dir_handle)) {
1628 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1630 if ($this->_filenameSelector($filename)) {
1631 array_push($this->_fileList, "$filename");
1632 //trigger_error(sprintf(_("found file %s"), $filename),
1633 // E_USER_NOTICE); //debugging
1636 closedir($dir_handle);
1642 // expands a list containing regex's to its matching entries
1643 class ListRegexExpand {
1644 //var $match, $list, $index, $case_sensitive;
1645 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1646 $this->match = $match;
1647 $this->list = &$list;
1648 $this->case_sensitive = $case_sensitive;
1649 //$this->index = false;
1651 function listMatchCallback ($item, $key) {
1652 $quoted = str_replace('/','\/',$item);
1653 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1655 unset($this->list[$this->index]);
1656 $this->list[] = $item;
1659 function expandRegex ($index, &$pages) {
1660 $this->index = $index;
1661 array_walk($pages, array($this, 'listMatchCallback'));
1666 // Convert fileglob to regex style:
1667 // Convert some wildcards to pcre style, escape the rest
1668 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1669 // Fixed bug #994994: "/" in $glob.
1670 function glob_to_pcre ($glob) {
1671 // check simple case: no need to escape
1672 $escape = '\[](){}=!<>|:/';
1673 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1675 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1676 $glob = strtr($glob, "\\", "\xff");
1677 $glob = str_replace("/", "\\/", $glob);
1678 // first convert some unescaped expressions to pcre style: . => \.
1680 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1681 "\\1\xff\\2", $glob);
1684 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1685 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1686 if (!preg_match('/^[\?\*]/', $glob))
1688 if (!preg_match('/[\?\*]$/', $glob))
1691 // Fixes Bug 1182997
1692 // .*? handled above, now escape the rest
1693 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1694 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1696 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1698 $re = preg_replace('/\xff/', '', $re);
1702 function glob_match ($glob, $against, $case_sensitive = true) {
1703 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1707 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1708 $list = explode(',',$input);
1709 // expand wildcards from list of $allnames
1710 if (preg_match('/[\?\*]/',$input)) {
1711 // Optimizing loop invariants:
1712 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1713 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1715 if (preg_match('/[\?\*]/',$f)) {
1717 $expand = new ListRegexExpand($list,
1718 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1719 $expand->expandRegex($i, $allnames);
1726 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1727 function explodePageList($input, $include_empty=false, $sortby='pagename',
1728 $limit='', $exclude='') {
1729 include_once("lib/PageList.php");
1730 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1733 // Class introspections
1736 * Determine whether object is of a specified type.
1737 * In PHP builtin since 4.2.0 as is_a()
1738 * is_a() deprecated in PHP 5, in favor of instanceof operator
1740 * @param $object object An object.
1741 * @param $class string Class name.
1742 * @return bool True iff $object is a $class
1743 * or a sub-type of $class.
1745 function isa ($object, $class) {
1746 //if (check_php_version(5))
1747 // return $object instanceof $class;
1748 if (check_php_version(4,2) and !check_php_version(5))
1749 return is_a($object, $class);
1751 $lclass = check_php_version(5) ? $class : strtolower($class);
1752 return is_object($object)
1753 && ( strtolower(get_class($object)) == strtolower($class)
1754 || is_subclass_of($object, $lclass) );
1757 /** Determine whether (possible) object has method.
1759 * @param $object mixed Object
1760 * @param $method string Method name
1761 * @return bool True iff $object is an object with has method $method.
1763 function can ($object, $method) {
1764 return is_object($object) && method_exists($object, strtolower($method));
1767 /** Determine whether a function is okay to use.
1769 * Some providers (e.g. Lycos) disable some of PHP functions for
1770 * "security reasons." This makes those functions, of course,
1771 * unusable, despite the fact the function_exists() says they
1774 * This function test to see if a function exists and is not
1775 * disallowed by PHP's disable_functions config setting.
1777 * @param string $function_name Function name
1778 * @return bool True iff function can be used.
1780 function function_usable($function_name) {
1782 if (!is_array($disabled)) {
1783 $disabled = array();
1784 // Use get_cfg_var since ini_get() is one of the disabled functions
1785 // (on Lycos, at least.)
1786 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1787 foreach ($split as $f)
1788 $disabled[strtolower($f)] = true;
1791 return ( function_exists($function_name)
1792 and ! isset($disabled[strtolower($function_name)])
1799 * This is used for generating ETags.
1801 function wikihash ($x) {
1802 if (is_scalar($x)) {
1805 elseif (is_array($x)) {
1807 return md5(serialize($x));
1809 elseif (is_object($x)) {
1812 trigger_error("Can't hash $x", E_USER_ERROR);
1817 * Seed the random number generator.
1819 * better_srand() ensures the randomizer is seeded only once.
1821 * How random do you want it? See:
1822 * http://www.php.net/manual/en/function.srand.php
1823 * http://www.php.net/manual/en/function.mt-srand.php
1825 function better_srand($seed = '') {
1826 static $wascalled = FALSE;
1828 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1829 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1831 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1835 function rand_ascii($length = 1) {
1838 for ($i = 1; $i <= $length; $i++) {
1839 // return only typeable 7 bit ascii, avoid quotes
1840 if (function_exists('mt_rand'))
1841 $s .= chr(mt_rand(40, 126));
1843 // the usually bad glibc srand()
1844 $s .= chr(rand(40, 126));
1849 /* by Dan Frankowski.
1851 function rand_ascii_readable ($length = 6) {
1852 // Pick a few random letters or numbers
1855 // Don't use 1lI0O, because they're hard to read
1856 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1857 $letter_len = strlen($letters);
1858 for ($i=0; $i < $length; $i++) {
1859 if (function_exists('mt_rand'))
1860 $word .= $letters[mt_rand(0, $letter_len-1)];
1862 $word .= $letters[rand(0, $letter_len-1)];
1868 * Recursively count all non-empty elements
1869 * in array of any dimension or mixed - i.e.
1870 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1871 * See http://www.php.net/manual/en/function.count.php
1873 function count_all($arg) {
1874 // skip if argument is empty
1876 //print_r($arg); //debugging
1878 // not an array, return 1 (base case)
1881 // else call recursively for all elements $arg
1882 foreach($arg as $key => $val)
1883 $count += count_all($val);
1888 function isSubPage($pagename) {
1889 return (strstr($pagename, SUBPAGE_SEPARATOR));
1892 function subPageSlice($pagename, $pos) {
1893 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1894 $pages = array_slice($pages,$pos,1);
1901 * Class for "popping up" and alert box. (Except that right now, it doesn't
1905 * This is a hackish and needs to be refactored. However it would be nice to
1906 * unify all the different methods we use for showing Alerts and Dialogs.
1907 * (E.g. "Page deleted", login form, ...)
1912 * @param object $request
1913 * @param mixed $head Header ("title") for alert box.
1914 * @param mixed $body The text in the alert box.
1915 * @param hash $buttons An array mapping button labels to URLs.
1916 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1918 function Alert($head, $body, $buttons=false) {
1919 if ($buttons === false)
1922 if (is_array($body)) {
1924 foreach ($body as $li) {
1925 $html->pushContent(HTML::li($li));
1929 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1930 $this->_buttons = $buttons;
1934 * Show the alert box.
1939 $tokens = $this->_tokens;
1940 $tokens['BUTTONS'] = $this->_getButtons();
1942 $request->discardOutput();
1943 $tmpl = new Template('dialog', $request, $tokens);
1949 function _getButtons() {
1952 $buttons = $this->_buttons;
1954 $buttons = array(_("Okay") => $request->getURLtoSelf());
1957 foreach ($buttons as $label => $url)
1958 print "$label $url\n";
1959 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1960 return new XmlContent($out);
1965 // 1.3.9-p1 => 1030.091
1966 // 1.3.10pre => 1030.099
1967 // 1.3.11pre-20041120 => 1030.1120041120
1968 // 1.3.12-rc1 => 1030.119
1969 function phpwiki_version() {
1970 static $PHPWIKI_VERSION;
1971 if (!isset($PHPWIKI_VERSION)) {
1972 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1973 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1974 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1975 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1976 $PHPWIKI_VERSION -= 0.01;
1978 return $PHPWIKI_VERSION;
1981 function phpwiki_gzhandler($ob) {
1982 if (function_exists('gzencode'))
1983 $ob = gzencode($ob);
1984 $GLOBALS['request']->_ob_get_length = strlen($ob);
1985 if (!headers_sent()) {
1986 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1991 function isWikiWord($word) {
1992 global $WikiNameRegexp;
1993 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1994 return preg_match("/^$WikiNameRegexp\$/",$word);
1997 // needed to store serialized objects-values only (perm, pref)
1998 function obj2hash ($obj, $exclude = false, $fields = false) {
2000 if (! $fields ) $fields = get_object_vars($obj);
2001 foreach ($fields as $key => $val) {
2002 if (is_array($exclude)) {
2003 if (in_array($key, $exclude)) continue;
2011 * isAsciiString($string)
2013 function isAsciiString($s) {
2014 $ptrASCII = '[\x00-\x7F]';
2015 return preg_match("/^($ptrASCII)*$/s", $s);
2019 * isUtf8String($string) - cheap utf-8 detection
2021 * segfaults for strings longer than 10kb!
2022 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
2023 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
2025 function isUtf8String( $s ) {
2026 $ptrASCII = '[\x00-\x7F]';
2027 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
2028 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
2029 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
2030 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
2031 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
2032 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2036 * Check for UTF-8 URLs; Internet Explorer produces these if you
2037 * type non-ASCII chars in the URL bar or follow unescaped links.
2038 * Requires urldecoded pagename.
2039 * Fixes sf.net bug #953949
2041 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2043 function fixTitleEncoding( $s ) {
2048 if (empty($s)) return $s;
2050 $ishigh = preg_match( '/[\x80-\xff]/', $s);
2052 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2053 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
2055 $isutf = ($ishigh ? isUtf8String($s) : true);
2056 $locharset = strtolower($charset);
2058 if( $locharset != "utf-8" and $ishigh and $isutf )
2059 $s = charset_convert('UTF-8', $locharset, $s);
2060 if ($locharset == "utf-8" and $ishigh and !$isutf )
2061 return utf8_encode( $s );
2063 // Other languages can safely leave this function, or replace
2064 // it with one to detect and convert another legacy encoding.
2069 * MySQL fulltext index doesn't grok utf-8, so we
2070 * need to fold cases and convert to hex.
2071 * src: languages/Language.php:stripForSearch() from mediawiki
2074 function stripForSearch( $string ) {
2075 global $wikiLowerChars;
2076 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2077 return preg_replace(
2078 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2079 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2085 * Workaround for allow_url_fopen, to get the content of an external URI.
2086 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2087 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2089 function url_get_contents( $uri ) {
2090 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2091 return @file_get_contents($uri);
2093 require_once("lib/HttpClient.php");
2094 $bits = parse_url($uri);
2095 $host = $bits['host'];
2096 $port = isset($bits['port']) ? $bits['port'] : 80;
2097 $path = isset($bits['path']) ? $bits['path'] : '/';
2098 if (isset($bits['query'])) {
2099 $path .= '?'.$bits['query'];
2101 $client = new HttpClient($host, $port);
2102 $client->use_gzip = false;
2103 if (!$client->get($path)) {
2106 return $client->getContent();
2112 * Generate consecutively named strings:
2113 * Name, Name2, Name3, ...
2115 function GenerateId($name) {
2116 static $ids = array();
2117 if (empty($ids[$name])) {
2122 return $name . $ids[$name];
2126 // from IncludePage. To be of general use.
2127 // content: string or array of strings
2128 function firstNWordsOfContent( $n, $content ) {
2129 if ($content and $n > 0) {
2130 if (is_array($content)) {
2131 // fixme: return a list of lines then?
2132 //$content = join("\n", $content);
2133 //$return_array = true;
2135 foreach ($content as $line) {
2136 $words = explode(' ', $line);
2137 if ($wordcount + count($words) > $n) {
2138 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2139 . sprintf(_("... (first %s words)"), $n);
2142 $wordcount += count($words);
2148 // fixme: use better whitespace/word seperators
2149 $words = explode(' ', $content);
2150 if (count($words) > $n) {
2151 return join(' ', array_slice($words, 0, $n))
2152 . sprintf(_("... (first %s words)"), $n);
2162 // moved from lib/plugin/IncludePage.php
2163 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2164 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2166 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2167 . " \\s*$\\n?" // possible blank lines
2168 . " ( (?: ^.*\\n? )*? )" // some lines
2169 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2170 implode("\n", $content),
2172 // Strip trailing blanks lines and ---- <hr>s
2173 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2175 $text = $match[1] . $section ."\n". $text;
2176 return explode("\n", $text);
2179 $mesg = $page ." ". $section;
2182 return array(sprintf(_("<%s: no such section>"), $mesg));
2185 // Extract the first $sections sections of the page
2186 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2188 $mycontent = $content;
2191 while ($sections > 0) {
2193 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2194 . " \\s*$\\n?" // possible blank lines
2195 . " ( (?: ^.*\\n? )*? )" // some lines
2196 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2197 implode("\n", $mycontent),
2199 $section = $match[2];
2200 // Strip trailing blanks lines and ---- <hr>s
2201 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2203 $text = $match[1] . $section ."\n". $text;
2206 $mycontent = explode("\n", $match[4]);
2208 if ($sections === 0) {
2209 return explode("\n", $result);
2215 // use this faster version: only load ExternalReferrer if we came from an external referrer
2216 function isExternalReferrer(&$request) {
2217 if ($referrer = $request->get('HTTP_REFERER')) {
2218 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2219 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2220 require_once("lib/ExternalReferrer.php");
2221 $se = new SearchEngines();
2222 return $se->parseSearchQuery($referrer);
2224 //if (DEBUG) return array('query' => 'wiki');
2229 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2231 function loadPhpExtension($extension) {
2232 if (!extension_loaded($extension)) {
2233 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2234 $soname = ($isWindows ? 'php_' : '')
2236 . ($isWindows ? '.dll' : '.so');
2240 return extension_loaded($extension);
2243 function charset_convert($from, $to, $data) {
2245 //$wikicharset = strtolower($CHARSET);
2246 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2247 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2248 return utf8_decode($data);
2249 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2250 return utf8_encode($data);
2252 if (loadPhpExtension("iconv")) {
2253 $tmpdata = iconv($from, $to, $data);
2255 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2259 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2264 function string_starts_with($string, $prefix) {
2265 return (substr($string, 0, strlen($prefix)) == $prefix);
2267 function string_ends_with($string, $suffix) {
2268 return (substr($string, -strlen($suffix)) == $suffix);
2270 function array_remove($arr,$value) {
2271 return array_values(array_diff($arr,array($value)));
2275 * Ensure that the script will have another $secs time left.
2276 * Works only if safe_mode is off.
2277 * For example not to timeout on waiting socket connections.
2278 * Use the socket timeout as arg.
2280 function longer_timeout($secs = 30) {
2281 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2282 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2283 if ($timeleft < $secs)
2284 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2287 function printSimpleTrace($bt) {
2289 echo "\nTraceback:\n";
2290 if (function_exists('debug_print_backtrace')) { // >= 5
2291 debug_print_backtrace();
2293 foreach ($bt as $i => $elem) {
2294 if (!array_key_exists('file', $elem)) {
2297 //echo join(" ",array_values($elem)),"\n";
2298 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2304 * Return the used process memory, in bytes.
2305 * Enable the section which will work for you. They are very slow.
2306 * Special quirks for Windows: Requires cygwin.
2308 function getMemoryUsage() {
2309 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2310 if (function_exists('memory_get_usage') and memory_get_usage()) {
2311 return memory_get_usage();
2312 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2313 $mem = $u['ru_maxrss'];
2314 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2315 // what we want is the process memory only: apache or php (if CGI)
2318 // win32_ps_stat_proc, win32_ps_stat_mem
2319 if (function_exists('win32_ps_list_procs')) {
2320 $info = win32_ps_stat_proc($pid);
2321 $memstr = $info['mem']['working_set_size'];
2323 // This works only if it's a cygwin process (apache or php).
2324 // Requires a newer cygwin
2325 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2327 // if it's native windows use something like this:
2328 // (requires pslist from sysinternals.com, grep, sed and perl)
2329 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2331 return (integer) trim($memstr);
2334 //%MEM: Percentage of total memory in use by this process
2335 //VSZ: Total virtual memory size, in 1K blocks.
2336 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2337 //CPU time used by process since it started.
2338 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2339 $memstr = exec("ps -orss -p $pid|sed 1d");
2340 return (integer) trim($memstr);
2345 * @param var $needle
2346 * @param array $haystack one-dimensional numeric array only, no hash
2348 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2349 It will return false if not found or the index where it was found.
2350 From dennis.decoene@moveit.be http://www.php.net/array_search
2352 function binary_search($needle, $haystack) {
2353 $high = count($haystack);
2356 while (($high - $low) > 1) {
2357 $probe = floor(($high + $low) / 2);
2358 if ($haystack[$probe] < $needle) {
2360 } elseif ($haystack[$probe] == $needle) {
2361 $high = $low = $probe;
2367 if ($high == count($haystack) || $haystack[$high] != $needle) {
2374 function is_localhost($url = false) {
2376 global $HTTP_SERVER_VARS;
2377 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2382 * Take a string and quote it sufficiently to be passed as a Javascript
2383 * string between ''s
2385 function javascript_quote_string($s) {
2386 return str_replace("'", "\'", $s);
2389 function isSerialized($s) {
2390 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2394 * Take a string and return an array of pairs (attribute name, attribute value)
2396 * We allow attributes with or without double quotes (")
2397 * Attribute-value pairs may be separated by space or comma
2398 * Space is normal HTML attributes, comma is for RichTable compatibility
2399 * border=1, cellpadding="5"
2400 * border=1 cellpadding="5"
2401 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2402 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2404 function parse_attributes($line) {
2408 if (empty($line)) return $options;
2409 $line = trim($line);
2410 if (empty($line)) return $options;
2411 $line = trim($line, ",");
2412 if (empty($line)) return $options;
2414 // First we have an attribute name.
2419 while (($i < strlen($line)) && ($line[$i] != '=')) {
2422 $attribute = substr($line, 0, $i);
2423 $attribute = strtolower($attribute);
2425 $line = substr($line, $i+1);
2426 $line = trim ($line);
2427 $line = trim ($line, "=");
2428 $line = trim ($line);
2430 if (empty($line)) return $options;
2432 // Then we have the attribute value.
2435 // Attribute value might be between double quotes
2436 // In that case we have to find the closing double quote
2437 if ($line[0] == '"') {
2438 $i++; // skip first '"'
2439 while (($i < strlen($line)) && ($line[$i] != '"')) {
2442 $value = substr($line, 0, $i);
2443 $value = trim ($value, '"');
2444 $value = trim ($value);
2446 // If there are no double quotes, we have to find the next space or comma
2448 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2451 $value = substr($line, 0, $i);
2452 $value = trim ($value);
2453 $value = trim ($value, ",");
2454 $value = trim ($value);
2457 $options[$attribute] = $value;
2459 $line = substr($line, $i+1);
2460 $line = trim ($line);
2461 $line = trim ($line, ",");
2462 $line = trim ($line);
2464 return $options + parse_attributes($line);
2468 * Returns true if the filename ends with an image suffix.
2469 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2471 function is_image ($filename) {
2473 if (defined('INLINE_IMAGES')) {
2474 $inline_images = INLINE_IMAGES;
2476 $inline_images = "png|jpg|jpeg|gif";
2479 foreach (explode("|", $inline_images) as $suffix) {
2480 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2488 * Returns true if the filename ends with an video suffix.
2489 * Currently only FLV
2491 function is_video ($filename) {
2493 return string_ends_with(strtolower($filename), ".flv")
2494 or string_ends_with(strtolower($filename), ".ogg");
2499 * Compute cell in spreadsheet table
2500 * $table: two-dimensional table
2501 * $i and $j: indexes of cell to compute
2502 * $imax and $jmax: table dimensions
2504 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2506 // What is implemented:
2507 // @@=SUM(R)@@ : sum of cells in current row
2508 // @@=SUM(C)@@ : sum of cells in current column
2509 // @@=AVERAGE(R)@@ : average of cells in current row
2510 // @@=AVERAGE(C)@@ : average of cells in current column
2511 // @@=MAX(R)@@ : maximum value of cells in current row
2512 // @@=MAX(C)@@ : maximum value of cells in current column
2513 // @@=MIN(R)@@ : minimum value of cells in current row
2514 // @@=MIN(C)@@ : minimum value of cells in current column
2515 // @@=COUNT(R)@@ : number of cells in current row
2516 // (numeric or not, excluding headers and current cell)
2517 // @@=COUNT(C)@@ : number of cells in current column
2518 // (numeric or not, excluding headers and current cell)
2524 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2525 for ($index=0; $index<$imax; $index++) {
2526 if (is_numeric($table[$index][$j])) {
2527 $result += $table[$index][$j];
2530 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2532 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2533 for ($index=0; $index<$jmax; $index++) {
2534 if (is_numeric($table[$i][$index])) {
2535 $result += $table[$i][$index];
2538 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2540 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2541 for ($index=0; $index<$imax; $index++) {
2542 if (is_numeric($table[$index][$j])) {
2543 $result += $table[$index][$j];
2547 $result=$result/$counter;
2548 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2550 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2551 for ($index=0; $index<$jmax; $index++) {
2552 if (is_numeric($table[$i][$index])) {
2553 $result += $table[$i][$index];
2557 $result=$result/$counter;
2558 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2560 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2561 for ($index=0; $index<$imax; $index++) {
2562 if (is_numeric($table[$index][$j])) {
2565 $result=$table[$index][$j];
2567 $result = max($result, $table[$index][$j]);
2574 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2576 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2577 for ($index=0; $index<$jmax; $index++) {
2578 if (is_numeric($table[$i][$index])) {
2581 $result=$table[$i][$index];
2583 $result = max($result, $table[$i][$index]);
2590 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2592 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2593 for ($index=0; $index<$imax; $index++) {
2594 if (is_numeric($table[$index][$j])) {
2597 $result=$table[$index][$j];
2599 $result = min($result, $table[$index][$j]);
2606 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2608 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2609 for ($index=0; $index<$jmax; $index++) {
2610 if (is_numeric($table[$i][$index])) {
2613 $result=$table[$i][$index];
2615 $result = min($result, $table[$i][$index]);
2622 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2624 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2625 for ($index=0; $index<$imax; $index++) {
2626 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2630 $result = $counter-1; // exclude self
2631 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2633 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2634 for ($index=0; $index<$jmax; $index++) {
2635 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2639 $result = $counter-1; // exclude self
2640 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2643 return $table[$i][$j];
2647 * Remove accents from given text.
2649 function strip_accents($text) {
2650 $res = utf8_decode($text);
2652 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2653 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2654 return utf8_encode($res);
2657 // (c-file-style: "gnu")
2661 // c-basic-offset: 4
2662 // c-hanging-comment-ender-p: nil
2663 // indent-tabs-mode: nil