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 $link = HTML::span(array('class' => 'error'),
479 sprintf(_("Invalid image attribute \"%s\" %s=%s"),
480 $url, $attr, $value));
484 // Correct silently the most common error
485 if ($url != $ori_url and empty($arr) and !preg_match("/^http/",$url)) {
486 // space belongs to the path
487 $file = NormalizeLocalFileName($ori_url);
488 if (file_exists($file)) {
489 $link = HTML::img(array('src' => $ori_url));
491 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
492 $url, $ori_url), E_USER_WARNING);
493 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
494 $file = substr($file, strlen(getUploadDataPath()));
495 $path = getUploadFilePath().$file;
496 if (file_exists($path)) {
497 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
498 $url, $ori_url), E_USER_WARNING);
499 $link->setAttr('src', getUploadDataPath() . $file);
504 if (!$link->getAttr('alt')) {
505 $link->setAttr('alt', $alt);
507 // Check width and height as spam countermeasure
508 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
509 //$width = (int) $width; // px or % or other suffix
510 //$height = (int) $height;
511 if (($width < 3 and $height < 10) or
512 ($height < 3 and $width < 20) or
513 ($height < 7 and $width < 7))
515 $link = HTML::span(array('class' => 'error'),
516 _("Invalid image size"));
521 // Prepare for getimagesize($url)
522 // $url only valid for external urls, otherwise local path
523 // Older php versions crash here with certain png's:
524 // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
525 // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
526 // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
527 if (DISABLE_GETIMAGESIZE)
529 elseif (! preg_match("/\.$force_img$/i", $url))
530 ; // only valid image extensions or scripts assumed to generate images
531 elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
532 ; // it's safe to assume that this will fail.
533 elseif (preg_match("/^http/",$url)) { // external url
534 $size = @getimagesize($url);
535 } else { // local file
536 if (file_exists($file = NormalizeLocalFileName($url))) { // here
537 $size = @getimagesize($file);
538 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
539 $size = @getimagesize($file);
540 $link->setAttr('src', rawurldecode($url));
541 } elseif (string_starts_with($url, getUploadDataPath())) { // there
542 $file = substr($file, strlen(getUploadDataPath()));
543 $path = getUploadFilePath().rawurldecode($file);
544 $size = @getimagesize($path);
545 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
546 } 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 = split(' ', $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 = split('&', $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) = split (":", $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) = split("\?", $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 if (check_php_version(4,3,9)) {
1052 $map = getInterwikiMap();
1053 if ($map_regex = $map->getRegexp())
1054 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1056 $bang_esc[] = $WikiNameRegexp;
1057 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1060 $subs["links"] = array($orig, $repl);
1062 // Temporarily URL-encode pairs of underscores in links to hide
1063 // them from the re for bold markup.
1064 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1065 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1068 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1071 // Convert footnote references.
1072 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1073 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1075 // Convert old style emphases to HTML style emphasis.
1076 $orig[] = '/__(.*?)__/';
1077 $repl[] = '<strong>\\1</strong>';
1078 $orig[] = "/''(.*?)''/";
1079 $repl[] = '<em>\\1</em>';
1081 // Escape nestled markup.
1082 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1085 // in old markup headings only allowed at beginning of line
1089 // Convert URL-encoded pairs of underscores in links back to
1090 // real underscores after bold markup has been converted.
1091 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1092 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1094 $subs["inline"] = array($orig, $repl);
1096 /*****************************************************************
1097 * Patterns which match block markup constructs which take
1098 * special handling...
1102 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1104 $blockpats[] = '\|(?:.*\n\|)*';
1107 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1109 // Footnote definitions
1110 $blockpats[] = '\[\s*(\d+)\s*\]';
1114 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1118 $blockpats[] = '!{1,3}[^!]';
1120 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1121 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1123 $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1124 . join("|", $blockpats)
1129 if ($markup_type != "block") {
1130 list ($orig, $repl) = $subs[$markup_type];
1131 return preg_replace($orig, $repl, $text);
1134 list ($orig, $repl) = $subs['inline'];
1137 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1138 // AnciennesR%E8glesDeFormatage and more
1139 // See http://www.pcre.org/pcre.txt LIMITATIONS
1140 while (preg_match($block_re, $text, $m)) {
1141 $text = substr($text, strlen($m[0]));
1142 list (,$leading_text, $block) = $m;
1145 if (strchr(" \t", $block[0])) {
1147 $prefix = "<pre>\n";
1148 $suffix = "\n</pre>\n";
1150 elseif ($block[0] == '|') {
1152 $prefix = "<?plugin OldStyleTable\n";
1155 elseif (strchr("#*;", $block[0])) {
1156 // Old-style list item
1157 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1158 list (,$ind,$bullet) = $m;
1159 $block = substr($block, strlen($m[0]));
1161 $indent = str_repeat(' ', strlen($ind));
1162 if ($bullet[0] == ';') {
1163 //$term = ltrim(substr($bullet, 1));
1164 //return $indent . $term . "\n" . $indent . ' ';
1165 $prefix = $ind . $bullet;
1168 $prefix = $indent . $bullet . ' ';
1170 elseif ($block[0] == '[') {
1171 // Footnote definition
1172 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1174 $block = substr($block, strlen($m[0]));
1175 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1177 elseif ($block[0] == '<') {
1179 // HACK: no inline markup...
1183 elseif ($block[0] == '!') {
1185 preg_match('/^!{1,3}/', $block, $m);
1187 $block = substr($block, strlen($m[0]));
1193 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1194 if ($block) $block = preg_replace($orig, $repl, $block);
1195 $out .= $leading_text;
1200 return $out . preg_replace($orig, $repl, $text);
1206 * Expand tabs in string.
1208 * Converts all tabs to (the appropriate number of) spaces.
1210 * @param string $str
1211 * @param integer $tab_width
1214 function expand_tabs($str, $tab_width = 8) {
1215 $split = split("\t", $str);
1216 $tail = array_pop($split);
1218 foreach ($split as $hunk) {
1220 $pos = strlen(strrchr($expanded, "\n")) - 1;
1221 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1223 return substr($expanded, 1) . $tail;
1227 * Split WikiWords in page names.
1229 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1230 * places like page titles. This is rumored to help search engines
1233 * @param $page string The page name.
1235 * @return string The split name.
1237 function SplitPagename ($page) {
1239 if (preg_match("/\s/", $page))
1240 return $page; // Already split --- don't split any more.
1242 // This algorithm is specialized for several languages.
1243 // (Thanks to Pierrick MEIGNEN)
1244 // Improvements for other languages welcome.
1247 // This mess splits between a lower-case letter followed by
1248 // either an upper-case or a numeral; except that it wont
1249 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1250 switch ($GLOBALS['LANG']) {
1255 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1258 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1261 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1262 // This the single-letter words 'I' and 'A' from any following
1263 // capitalized words.
1264 switch ($GLOBALS['LANG']) {
1266 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1269 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1272 // Split at underscore
1273 $RE[] = '/(_)([[:alpha:]])/';
1274 $RE[] = '/([[:alpha:]])(_)/';
1275 // Split numerals from following letters.
1276 $RE[] = '/(\d)([[:alpha:]])/';
1277 // Split at subpage seperators. TBD in WikiTheme.php
1278 $RE[] = "/([^${sep}]+)(${sep})/";
1279 $RE[] = "/(${sep})([^${sep}]+)/";
1281 foreach ($RE as $key)
1282 $RE[$key] = pcre_fix_posix_classes($key);
1285 foreach ($RE as $regexp) {
1286 $page = preg_replace($regexp, '\\1 \\2', $page);
1291 function NoSuchRevision (&$request, $page, $version) {
1292 $html = HTML(HTML::h2(_("Revision Not Found")),
1293 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1294 $version, WikiLink($page, 'auto'))));
1295 include_once('lib/Template.php');
1296 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1302 * Get time offset for local time zone.
1304 * @param $time time_t Get offset for this time. Default: now.
1305 * @param $no_colon boolean Don't put colon between hours and minutes.
1306 * @return string Offset as a string in the format +HH:MM.
1308 function TimezoneOffset ($time = false, $no_colon = false) {
1309 if ($time === false)
1311 $secs = date('Z', $time);
1320 $colon = $no_colon ? '' : ':';
1321 $mins = intval(($secs + 30) / 60);
1322 return sprintf("%s%02d%s%02d",
1323 $sign, $mins / 60, $colon, $mins % 60);
1328 * Format time in ISO-8601 format.
1330 * @param $time time_t Time. Default: now.
1331 * @return string Date and time in ISO-8601 format.
1333 function Iso8601DateTime ($time = false) {
1334 if ($time === false)
1336 $tzoff = TimezoneOffset($time);
1337 $date = date('Y-m-d', $time);
1338 $time = date('H:i:s', $time);
1339 return $date . 'T' . $time . $tzoff;
1343 * Format time in RFC-2822 format.
1345 * @param $time time_t Time. Default: now.
1346 * @return string Date and time in RFC-2822 format.
1348 function Rfc2822DateTime ($time = false) {
1349 if ($time === false)
1351 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1355 * Format time in RFC-1123 format.
1357 * @param $time time_t Time. Default: now.
1358 * @return string Date and time in RFC-1123 format.
1360 function Rfc1123DateTime ($time = false) {
1361 if ($time === false)
1363 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1366 /** Parse date in RFC-1123 format.
1368 * According to RFC 1123 we must accept dates in the following
1371 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1372 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1373 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1375 * (Though we're only allowed to generate dates in the first format.)
1377 function ParseRfc1123DateTime ($timestr) {
1378 $timestr = trim($timestr);
1379 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1380 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1382 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1384 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1385 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1387 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1388 if ($year < 70) $year += 2000;
1389 elseif ($year < 100) $year += 1900;
1391 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1392 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1394 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1401 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1403 return false; // failed
1408 * Format time to standard 'ctime' format.
1410 * @param $time time_t Time. Default: now.
1411 * @return string Date and time.
1413 function CTime ($time = false)
1415 if ($time === false)
1417 return date("D M j H:i:s Y", $time);
1422 * Format number as kilobytes or bytes.
1423 * Short format is used for PageList
1424 * Long format is used in PageInfo
1426 * @param $bytes int. Default: 0.
1427 * @param $longformat bool. Default: false.
1428 * @return class FormattedText (XmlElement.php).
1430 function ByteFormatter ($bytes = 0, $longformat = false) {
1433 if ($bytes < 1024) {
1435 $size = fmt("%s b", $bytes);
1437 $size = fmt("%s bytes", $bytes);
1440 $kb = round($bytes / 1024, 1);
1442 $size = fmt("%s k", $kb);
1444 $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1450 * Internationalized printf.
1452 * This is essentially the same as PHP's built-in printf
1453 * with the following exceptions:
1455 * <li> It passes the format string through gettext().
1456 * <li> It supports the argument reordering extensions.
1463 * __printf("Differences between versions %s and %s of %s",
1464 * $new_link, $old_link, $page_link);
1467 * Then in locale/po/de.po, one can reorder the printf arguments:
1470 * msgid "Differences between %s and %s of %s."
1471 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1474 * (Note that while PHP tries to expand $vars within double-quotes,
1475 * the values in msgstr undergo no such expansion, so the '$'s
1478 * One shouldn't use reordered arguments in the default format string.
1479 * Backslashes in the default string would be necessary to escape the
1480 * '$'s, and they'll cause all kinds of trouble....
1482 function __printf ($fmt) {
1483 $args = func_get_args();
1485 echo __vsprintf($fmt, $args);
1489 * Internationalized sprintf.
1491 * This is essentially the same as PHP's built-in printf with the
1492 * following exceptions:
1495 * <li> It passes the format string through gettext().
1496 * <li> It supports the argument reordering extensions.
1501 function __sprintf ($fmt) {
1502 $args = func_get_args();
1504 return __vsprintf($fmt, $args);
1508 * Internationalized vsprintf.
1510 * This is essentially the same as PHP's built-in printf with the
1511 * following exceptions:
1514 * <li> It passes the format string through gettext().
1515 * <li> It supports the argument reordering extensions.
1520 function __vsprintf ($fmt, $args) {
1521 $fmt = gettext($fmt);
1522 // PHP's sprintf doesn't support variable with specifiers,
1523 // like sprintf("%*s", 10, "x"); --- so we won't either.
1525 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1526 // Format string has '%2$s' style argument reordering.
1527 // PHP doesn't support this.
1528 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1529 // literal variable name substitution only to keep locale
1530 // strings uncluttered
1531 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1532 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1534 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1537 // Reorder arguments appropriately.
1538 foreach($m[1] as $argnum) {
1539 if ($argnum < 1 || $argnum > count($args))
1540 trigger_error(sprintf(_("%s: argument index out of range"),
1541 $argnum), E_USER_WARNING);
1542 $newargs[] = $args[$argnum - 1];
1547 // Not all PHP's have vsprintf, so...
1548 array_unshift($args, $fmt);
1549 return call_user_func_array('sprintf', $args);
1552 function file_mtime ($filename) {
1553 if ($stat = @stat($filename))
1559 function sort_file_mtime ($a, $b) {
1560 $ma = file_mtime($a);
1561 $mb = file_mtime($b);
1562 if (!$ma or !$mb or $ma == $mb) return 0;
1563 return ($ma > $mb) ? -1 : 1;
1568 * Build an array in $this->_fileList of files from $dirname.
1569 * Subdirectories are not traversed.
1571 * (This was a function LoadDir in lib/loadsave.php)
1572 * See also http://www.php.net/manual/en/function.readdir.php
1574 function getFiles($exclude='', $sortby='', $limit='') {
1575 $list = $this->_fileList;
1578 require_once('lib/PageList.php');
1579 switch (Pagelist::sortby($sortby, 'db')) {
1580 case 'pagename ASC': break;
1581 case 'pagename DESC':
1582 $list = array_reverse($list);
1585 usort($list,'sort_file_mtime');
1588 usort($list,'sort_file_mtime');
1589 $list = array_reverse($list);
1594 return array_splice($list, 0, $limit);
1598 function _filenameSelector($filename) {
1599 if (! $this->_pattern )
1602 if (! $this->_pcre_pattern )
1603 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1604 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1609 function fileSet($directory, $filepattern = false) {
1610 $this->_fileList = array();
1611 $this->_pattern = $filepattern;
1613 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1615 $this->_case = !isWindows();
1616 $this->_pathsep = '/';
1618 if (empty($directory)) {
1619 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1621 return; // early return
1624 @ $dir_handle = opendir($dir=$directory);
1625 if (empty($dir_handle)) {
1626 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1627 $dir), E_USER_NOTICE);
1628 return; // early return
1631 while ($filename = readdir($dir_handle)) {
1632 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1634 if ($this->_filenameSelector($filename)) {
1635 array_push($this->_fileList, "$filename");
1636 //trigger_error(sprintf(_("found file %s"), $filename),
1637 // E_USER_NOTICE); //debugging
1640 closedir($dir_handle);
1646 // expands a list containing regex's to its matching entries
1647 class ListRegexExpand {
1648 //var $match, $list, $index, $case_sensitive;
1649 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1650 $this->match = $match;
1651 $this->list = &$list;
1652 $this->case_sensitive = $case_sensitive;
1653 //$this->index = false;
1655 function listMatchCallback ($item, $key) {
1656 $quoted = str_replace('/','\/',$item);
1657 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1659 unset($this->list[$this->index]);
1660 $this->list[] = $item;
1663 function expandRegex ($index, &$pages) {
1664 $this->index = $index;
1665 array_walk($pages, array($this, 'listMatchCallback'));
1670 // Convert fileglob to regex style:
1671 // Convert some wildcards to pcre style, escape the rest
1672 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1673 // Fixed bug #994994: "/" in $glob.
1674 function glob_to_pcre ($glob) {
1675 // check simple case: no need to escape
1676 $escape = '\[](){}=!<>|:/';
1677 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1679 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1680 $glob = strtr($glob, "\\", "\xff");
1681 $glob = str_replace("/", "\\/", $glob);
1682 // first convert some unescaped expressions to pcre style: . => \.
1684 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1685 "\\1\xff\\2", $glob);
1688 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1689 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1690 if (!preg_match('/^[\?\*]/', $glob))
1692 if (!preg_match('/[\?\*]$/', $glob))
1695 // Fixes Bug 1182997
1696 // .*? handled above, now escape the rest
1697 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1698 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1700 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1702 $re = preg_replace('/\xff/', '', $re);
1706 function glob_match ($glob, $against, $case_sensitive = true) {
1707 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1711 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1712 $list = explode(',',$input);
1713 // expand wildcards from list of $allnames
1714 if (preg_match('/[\?\*]/',$input)) {
1715 // Optimizing loop invariants:
1716 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1717 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1719 if (preg_match('/[\?\*]/',$f)) {
1721 $expand = new ListRegexExpand($list,
1722 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1723 $expand->expandRegex($i, $allnames);
1730 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1731 function explodePageList($input, $include_empty=false, $sortby='pagename',
1732 $limit='', $exclude='') {
1733 include_once("lib/PageList.php");
1734 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1737 // Class introspections
1740 * Determine whether object is of a specified type.
1741 * In PHP builtin since 4.2.0 as is_a()
1742 * is_a() deprecated in PHP 5, in favor of instanceof operator
1744 * @param $object object An object.
1745 * @param $class string Class name.
1746 * @return bool True iff $object is a $class
1747 * or a sub-type of $class.
1749 function isa ($object, $class) {
1750 //if (check_php_version(5))
1751 // return $object instanceof $class;
1752 if (check_php_version(4,2) and !check_php_version(5))
1753 return is_a($object, $class);
1755 $lclass = check_php_version(5) ? $class : strtolower($class);
1756 return is_object($object)
1757 && ( strtolower(get_class($object)) == strtolower($class)
1758 || is_subclass_of($object, $lclass) );
1761 /** Determine whether (possible) object has method.
1763 * @param $object mixed Object
1764 * @param $method string Method name
1765 * @return bool True iff $object is an object with has method $method.
1767 function can ($object, $method) {
1768 return is_object($object) && method_exists($object, strtolower($method));
1771 /** Determine whether a function is okay to use.
1773 * Some providers (e.g. Lycos) disable some of PHP functions for
1774 * "security reasons." This makes those functions, of course,
1775 * unusable, despite the fact the function_exists() says they
1778 * This function test to see if a function exists and is not
1779 * disallowed by PHP's disable_functions config setting.
1781 * @param string $function_name Function name
1782 * @return bool True iff function can be used.
1784 function function_usable($function_name) {
1786 if (!is_array($disabled)) {
1787 $disabled = array();
1788 // Use get_cfg_var since ini_get() is one of the disabled functions
1789 // (on Lycos, at least.)
1790 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1791 foreach ($split as $f)
1792 $disabled[strtolower($f)] = true;
1795 return ( function_exists($function_name)
1796 and ! isset($disabled[strtolower($function_name)])
1803 * This is used for generating ETags.
1805 function wikihash ($x) {
1806 if (is_scalar($x)) {
1809 elseif (is_array($x)) {
1811 return md5(serialize($x));
1813 elseif (is_object($x)) {
1816 trigger_error("Can't hash $x", E_USER_ERROR);
1821 * Seed the random number generator.
1823 * better_srand() ensures the randomizer is seeded only once.
1825 * How random do you want it? See:
1826 * http://www.php.net/manual/en/function.srand.php
1827 * http://www.php.net/manual/en/function.mt-srand.php
1829 function better_srand($seed = '') {
1830 static $wascalled = FALSE;
1832 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1833 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1835 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1839 function rand_ascii($length = 1) {
1842 for ($i = 1; $i <= $length; $i++) {
1843 // return only typeable 7 bit ascii, avoid quotes
1844 if (function_exists('mt_rand'))
1845 $s .= chr(mt_rand(40, 126));
1847 // the usually bad glibc srand()
1848 $s .= chr(rand(40, 126));
1853 /* by Dan Frankowski.
1855 function rand_ascii_readable ($length = 6) {
1856 // Pick a few random letters or numbers
1859 // Don't use 1lI0O, because they're hard to read
1860 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1861 $letter_len = strlen($letters);
1862 for ($i=0; $i < $length; $i++) {
1863 if (function_exists('mt_rand'))
1864 $word .= $letters[mt_rand(0, $letter_len-1)];
1866 $word .= $letters[rand(0, $letter_len-1)];
1872 * Recursively count all non-empty elements
1873 * in array of any dimension or mixed - i.e.
1874 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1875 * See http://www.php.net/manual/en/function.count.php
1877 function count_all($arg) {
1878 // skip if argument is empty
1880 //print_r($arg); //debugging
1882 // not an array, return 1 (base case)
1885 // else call recursively for all elements $arg
1886 foreach($arg as $key => $val)
1887 $count += count_all($val);
1892 function isSubPage($pagename) {
1893 return (strstr($pagename, SUBPAGE_SEPARATOR));
1896 function subPageSlice($pagename, $pos) {
1897 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1898 $pages = array_slice($pages,$pos,1);
1905 * Class for "popping up" and alert box. (Except that right now, it doesn't
1909 * This is a hackish and needs to be refactored. However it would be nice to
1910 * unify all the different methods we use for showing Alerts and Dialogs.
1911 * (E.g. "Page deleted", login form, ...)
1916 * @param object $request
1917 * @param mixed $head Header ("title") for alert box.
1918 * @param mixed $body The text in the alert box.
1919 * @param hash $buttons An array mapping button labels to URLs.
1920 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1922 function Alert($head, $body, $buttons=false) {
1923 if ($buttons === false)
1926 if (is_array($body)) {
1928 foreach ($body as $li) {
1929 $html->pushContent(HTML::li($li));
1933 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1934 $this->_buttons = $buttons;
1938 * Show the alert box.
1943 $tokens = $this->_tokens;
1944 $tokens['BUTTONS'] = $this->_getButtons();
1946 $request->discardOutput();
1947 $tmpl = new Template('dialog', $request, $tokens);
1953 function _getButtons() {
1956 $buttons = $this->_buttons;
1958 $buttons = array(_("Okay") => $request->getURLtoSelf());
1961 foreach ($buttons as $label => $url)
1962 print "$label $url\n";
1963 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1964 return new XmlContent($out);
1969 // 1.3.9-p1 => 1030.091
1970 // 1.3.10pre => 1030.099
1971 // 1.3.11pre-20041120 => 1030.1120041120
1972 // 1.3.12-rc1 => 1030.119
1973 function phpwiki_version() {
1974 static $PHPWIKI_VERSION;
1975 if (!isset($PHPWIKI_VERSION)) {
1976 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1977 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1978 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1979 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1980 $PHPWIKI_VERSION -= 0.01;
1982 return $PHPWIKI_VERSION;
1985 function phpwiki_gzhandler($ob) {
1986 if (function_exists('gzencode'))
1987 $ob = gzencode($ob);
1988 $GLOBALS['request']->_ob_get_length = strlen($ob);
1989 if (!headers_sent()) {
1990 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1995 function isWikiWord($word) {
1996 global $WikiNameRegexp;
1997 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1998 return preg_match("/^$WikiNameRegexp\$/",$word);
2001 // needed to store serialized objects-values only (perm, pref)
2002 function obj2hash ($obj, $exclude = false, $fields = false) {
2004 if (! $fields ) $fields = get_object_vars($obj);
2005 foreach ($fields as $key => $val) {
2006 if (is_array($exclude)) {
2007 if (in_array($key, $exclude)) continue;
2015 * isAsciiString($string)
2017 function isAsciiString($s) {
2018 $ptrASCII = '[\x00-\x7F]';
2019 return preg_match("/^($ptrASCII)*$/s", $s);
2023 * isUtf8String($string) - cheap utf-8 detection
2025 * segfaults for strings longer than 10kb!
2026 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
2027 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
2029 function isUtf8String( $s ) {
2030 $ptrASCII = '[\x00-\x7F]';
2031 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
2032 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
2033 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
2034 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
2035 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
2036 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2040 * Check for UTF-8 URLs; Internet Explorer produces these if you
2041 * type non-ASCII chars in the URL bar or follow unescaped links.
2042 * Requires urldecoded pagename.
2043 * Fixes sf.net bug #953949
2045 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2047 function fixTitleEncoding( $s ) {
2052 if (empty($s)) return $s;
2054 $ishigh = preg_match( '/[\x80-\xff]/', $s);
2056 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2057 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
2059 $isutf = ($ishigh ? isUtf8String($s) : true);
2060 $locharset = strtolower($charset);
2062 if( $locharset != "utf-8" and $ishigh and $isutf )
2063 $s = charset_convert('UTF-8', $locharset, $s);
2064 if ($locharset == "utf-8" and $ishigh and !$isutf )
2065 return utf8_encode( $s );
2067 // Other languages can safely leave this function, or replace
2068 // it with one to detect and convert another legacy encoding.
2073 * MySQL fulltext index doesn't grok utf-8, so we
2074 * need to fold cases and convert to hex.
2075 * src: languages/Language.php:stripForSearch() from mediawiki
2078 function stripForSearch( $string ) {
2079 global $wikiLowerChars;
2080 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2081 return preg_replace(
2082 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2083 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2089 * Workaround for allow_url_fopen, to get the content of an external URI.
2090 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2091 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2093 function url_get_contents( $uri ) {
2094 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2095 return @file_get_contents($uri);
2097 require_once("lib/HttpClient.php");
2098 $bits = parse_url($uri);
2099 $host = $bits['host'];
2100 $port = isset($bits['port']) ? $bits['port'] : 80;
2101 $path = isset($bits['path']) ? $bits['path'] : '/';
2102 if (isset($bits['query'])) {
2103 $path .= '?'.$bits['query'];
2105 $client = new HttpClient($host, $port);
2106 $client->use_gzip = false;
2107 if (!$client->get($path)) {
2110 return $client->getContent();
2116 * Generate consecutively named strings:
2117 * Name, Name2, Name3, ...
2119 function GenerateId($name) {
2120 static $ids = array();
2121 if (empty($ids[$name])) {
2126 return $name . $ids[$name];
2130 // from IncludePage. To be of general use.
2131 // content: string or array of strings
2132 function firstNWordsOfContent( $n, $content ) {
2133 if ($content and $n > 0) {
2134 if (is_array($content)) {
2135 // fixme: return a list of lines then?
2136 //$content = join("\n", $content);
2137 //$return_array = true;
2139 foreach ($content as $line) {
2140 $words = explode(' ', $line);
2141 if ($wordcount + count($words) > $n) {
2142 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2143 . sprintf(_("... (first %s words)"), $n);
2146 $wordcount += count($words);
2152 // fixme: use better whitespace/word seperators
2153 $words = explode(' ', $content);
2154 if (count($words) > $n) {
2155 return join(' ', array_slice($words, 0, $n))
2156 . sprintf(_("... (first %s words)"), $n);
2166 // moved from lib/plugin/IncludePage.php
2167 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2168 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2170 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2171 . " \\s*$\\n?" // possible blank lines
2172 . " ( (?: ^.*\\n? )*? )" // some lines
2173 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2174 implode("\n", $content),
2176 // Strip trailing blanks lines and ---- <hr>s
2177 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2179 $text = $match[1] . $section ."\n". $text;
2180 return explode("\n", $text);
2183 $mesg = $page ." ". $section;
2186 return array(sprintf(_("<%s: no such section>"), $mesg));
2189 // Extract the first $sections sections of the page
2190 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2192 $mycontent = $content;
2195 while ($sections > 0) {
2197 if (preg_match("/ ^(!{1,})\\s*(.*)\\n" // section header
2198 . " \\s*$\\n?" // possible blank lines
2199 . " ( (?: ^.*\\n? )*? )" // some lines
2200 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2201 implode("\n", $mycontent),
2203 $section = $match[2];
2204 // Strip trailing blanks lines and ---- <hr>s
2205 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2207 $text = $match[1] . $section ."\n". $text;
2210 $mycontent = explode("\n", $match[4]);
2212 if ($sections === 0) {
2213 return explode("\n", $result);
2219 // use this faster version: only load ExternalReferrer if we came from an external referrer
2220 function isExternalReferrer(&$request) {
2221 if ($referrer = $request->get('HTTP_REFERER')) {
2222 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2223 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2224 require_once("lib/ExternalReferrer.php");
2225 $se = new SearchEngines();
2226 return $se->parseSearchQuery($referrer);
2228 //if (DEBUG) return array('query' => 'wiki');
2233 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2235 function loadPhpExtension($extension) {
2236 if (!extension_loaded($extension)) {
2237 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2238 $soname = ($isWindows ? 'php_' : '')
2240 . ($isWindows ? '.dll' : '.so');
2244 return extension_loaded($extension);
2247 function charset_convert($from, $to, $data) {
2249 //$wikicharset = strtolower($CHARSET);
2250 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2251 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2252 return utf8_decode($data);
2253 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2254 return utf8_encode($data);
2256 if (loadPhpExtension("iconv")) {
2257 $tmpdata = iconv($from, $to, $data);
2259 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2263 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2268 function string_starts_with($string, $prefix) {
2269 return (substr($string, 0, strlen($prefix)) == $prefix);
2271 function string_ends_with($string, $suffix) {
2272 return (substr($string, -strlen($suffix)) == $suffix);
2274 function array_remove($arr,$value) {
2275 return array_values(array_diff($arr,array($value)));
2279 * Ensure that the script will have another $secs time left.
2280 * Works only if safe_mode is off.
2281 * For example not to timeout on waiting socket connections.
2282 * Use the socket timeout as arg.
2284 function longer_timeout($secs = 30) {
2285 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2286 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2287 if ($timeleft < $secs)
2288 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2291 function printSimpleTrace($bt) {
2293 echo "\nTraceback:\n";
2294 if (function_exists('debug_print_backtrace')) { // >= 5
2295 debug_print_backtrace();
2297 foreach ($bt as $i => $elem) {
2298 if (!array_key_exists('file', $elem)) {
2301 //echo join(" ",array_values($elem)),"\n";
2302 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2308 * Return the used process memory, in bytes.
2309 * Enable the section which will work for you. They are very slow.
2310 * Special quirks for Windows: Requires cygwin.
2312 function getMemoryUsage() {
2313 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2314 if (function_exists('memory_get_usage') and memory_get_usage()) {
2315 return memory_get_usage();
2316 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2317 $mem = $u['ru_maxrss'];
2318 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2319 // what we want is the process memory only: apache or php (if CGI)
2322 // win32_ps_stat_proc, win32_ps_stat_mem
2323 if (function_exists('win32_ps_list_procs')) {
2324 $info = win32_ps_stat_proc($pid);
2325 $memstr = $info['mem']['working_set_size'];
2327 // This works only if it's a cygwin process (apache or php).
2328 // Requires a newer cygwin
2329 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2331 // if it's native windows use something like this:
2332 // (requires pslist from sysinternals.com, grep, sed and perl)
2333 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2335 return (integer) trim($memstr);
2338 //%MEM: Percentage of total memory in use by this process
2339 //VSZ: Total virtual memory size, in 1K blocks.
2340 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2341 //CPU time used by process since it started.
2342 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2343 $memstr = exec("ps -orss -p $pid|sed 1d");
2344 return (integer) trim($memstr);
2349 * @param var $needle
2350 * @param array $haystack one-dimensional numeric array only, no hash
2352 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2353 It will return false if not found or the index where it was found.
2354 From dennis.decoene@moveit.be http://www.php.net/array_search
2356 function binary_search($needle, $haystack) {
2357 $high = count($haystack);
2360 while (($high - $low) > 1) {
2361 $probe = floor(($high + $low) / 2);
2362 if ($haystack[$probe] < $needle) {
2364 } elseif ($haystack[$probe] == $needle) {
2365 $high = $low = $probe;
2371 if ($high == count($haystack) || $haystack[$high] != $needle) {
2378 function is_localhost($url = false) {
2380 global $HTTP_SERVER_VARS;
2381 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2386 * Take a string and quote it sufficiently to be passed as a Javascript
2387 * string between ''s
2389 function javascript_quote_string($s) {
2390 return str_replace("'", "\'", $s);
2393 function isSerialized($s) {
2394 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2398 * Take a string and return an array of pairs (attribute name, attribute value)
2400 * We allow attributes with or without double quotes (")
2401 * Attribute-value pairs may be separated by space or comma
2402 * Space is normal HTML attributes, comma is for RichTable compatibility
2403 * border=1, cellpadding="5"
2404 * border=1 cellpadding="5"
2405 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2406 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2408 function parse_attributes($line) {
2412 if (empty($line)) return $options;
2413 $line = trim($line);
2414 if (empty($line)) return $options;
2415 $line = trim($line, ",");
2416 if (empty($line)) return $options;
2418 // First we have an attribute name.
2423 while (($i < strlen($line)) && ($line[$i] != '=')) {
2426 $attribute = substr($line, 0, $i);
2427 $attribute = strtolower($attribute);
2429 $line = substr($line, $i+1);
2430 $line = trim ($line);
2431 $line = trim ($line, "=");
2432 $line = trim ($line);
2434 if (empty($line)) return $options;
2436 // Then we have the attribute value.
2439 // Attribute value might be between double quotes
2440 // In that case we have to find the closing double quote
2441 if ($line[0] == '"') {
2442 $i++; // skip first '"'
2443 while (($i < strlen($line)) && ($line[$i] != '"')) {
2446 $value = substr($line, 0, $i);
2447 $value = trim ($value, '"');
2448 $value = trim ($value);
2450 // If there are no double quotes, we have to find the next space or comma
2452 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2455 $value = substr($line, 0, $i);
2456 $value = trim ($value);
2457 $value = trim ($value, ",");
2458 $value = trim ($value);
2461 $options[$attribute] = $value;
2463 $line = substr($line, $i+1);
2464 $line = trim ($line);
2465 $line = trim ($line, ",");
2466 $line = trim ($line);
2468 return $options + parse_attributes($line);
2472 * Returns true if the filename ends with an image suffix.
2473 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2475 function is_image ($filename) {
2477 if (defined('INLINE_IMAGES')) {
2478 $inline_images = INLINE_IMAGES;
2480 $inline_images = "png|jpg|jpeg|gif";
2483 foreach (explode("|", $inline_images) as $suffix) {
2484 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2492 * Returns true if the filename ends with an video suffix.
2493 * Currently only FLV
2495 function is_video ($filename) {
2497 return string_ends_with(strtolower($filename), ".flv")
2498 or string_ends_with(strtolower($filename), ".ogg");
2503 * Compute cell in spreadsheet table
2504 * $table: two-dimensional table
2505 * $i and $j: indexes of cell to compute
2506 * $imax and $jmax: table dimensions
2508 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2510 // What is implemented:
2511 // @@=SUM(R)@@ : sum of cells in current row
2512 // @@=SUM(C)@@ : sum of cells in current column
2513 // @@=AVERAGE(R)@@ : average of cells in current row
2514 // @@=AVERAGE(C)@@ : average of cells in current column
2515 // @@=MAX(R)@@ : maximum value of cells in current row
2516 // @@=MAX(C)@@ : maximum value of cells in current column
2517 // @@=MIN(R)@@ : minimum value of cells in current row
2518 // @@=MIN(C)@@ : minimum value of cells in current column
2519 // @@=COUNT(R)@@ : number of cells in current row
2520 // (numeric or not, excluding headers and current cell)
2521 // @@=COUNT(C)@@ : number of cells in current column
2522 // (numeric or not, excluding headers and current cell)
2528 if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2529 for ($index=0; $index<$imax; $index++) {
2530 if (is_numeric($table[$index][$j])) {
2531 $result += $table[$index][$j];
2534 return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2536 } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2537 for ($index=0; $index<$jmax; $index++) {
2538 if (is_numeric($table[$i][$index])) {
2539 $result += $table[$i][$index];
2542 return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2544 } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2545 for ($index=0; $index<$imax; $index++) {
2546 if (is_numeric($table[$index][$j])) {
2547 $result += $table[$index][$j];
2551 $result=$result/$counter;
2552 return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2554 } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2555 for ($index=0; $index<$jmax; $index++) {
2556 if (is_numeric($table[$i][$index])) {
2557 $result += $table[$i][$index];
2561 $result=$result/$counter;
2562 return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2564 } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2565 for ($index=0; $index<$imax; $index++) {
2566 if (is_numeric($table[$index][$j])) {
2569 $result=$table[$index][$j];
2571 $result = max($result, $table[$index][$j]);
2578 return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2580 } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2581 for ($index=0; $index<$jmax; $index++) {
2582 if (is_numeric($table[$i][$index])) {
2585 $result=$table[$i][$index];
2587 $result = max($result, $table[$i][$index]);
2594 return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2596 } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2597 for ($index=0; $index<$imax; $index++) {
2598 if (is_numeric($table[$index][$j])) {
2601 $result=$table[$index][$j];
2603 $result = min($result, $table[$index][$j]);
2610 return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2612 } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2613 for ($index=0; $index<$jmax; $index++) {
2614 if (is_numeric($table[$i][$index])) {
2617 $result=$table[$i][$index];
2619 $result = min($result, $table[$i][$index]);
2626 return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2628 } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2629 for ($index=0; $index<$imax; $index++) {
2630 if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2634 $result = $counter-1; // exclude self
2635 return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2637 } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2638 for ($index=0; $index<$jmax; $index++) {
2639 if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2643 $result = $counter-1; // exclude self
2644 return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2647 return $table[$i][$j];
2651 * Remove accents from given text.
2653 function strip_accents($text) {
2654 $res = utf8_decode($text);
2656 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2657 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2658 return utf8_encode($res);
2661 // (c-file-style: "gnu")
2665 // c-basic-offset: 4
2666 // c-hanging-comment-ender-p: nil
2667 // indent-tabs-mode: nil