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 along
19 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 Standard functions for Wiki functionality
25 WikiURL ($pagename, $args, $get_abs_url)
27 IconForLink ($protocol_or_url)
28 PossiblyGlueIconToText($proto_or_url, $text)
30 LinkURL ($url, $linktext)
31 LinkImage ($url, $alt)
32 ImgObject ($img, $url)
34 SplitQueryArgs ($query_args)
35 LinkPhpwikiURL ($url, $text, $basepage)
36 ConvertOldMarkup ($content, $markup_type = "block")
37 MangleXmlIdentifier($str)
38 UnMangleXmlIdentifier($str)
40 class Stack { push($item), pop(), cnt(), top() }
41 class Alert { show() }
42 class WikiPageName {getParent(),isValid(),getWarnings() }
44 expand_tabs($str, $tab_width = 8)
46 NoSuchRevision ($request, $page, $version)
47 TimezoneOffset ($time, $no_colon)
48 Iso8601DateTime ($time)
49 Rfc2822DateTime ($time)
50 ParseRfc1123DateTime ($timestr)
52 ByteFormatter ($bytes = 0, $longformat = false)
55 __vsprintf ($fmt, $args)
57 file_mtime ($filename)
58 sort_file_mtime ($a, $b)
59 class fileSet {fileSet($directory, $filepattern = false),
60 getFiles($exclude='', $sortby='', $limit='') }
61 class ListRegexExpand { listMatchCallback($item, $key),
62 expandRegex ($index, &$pages) }
65 glob_match ($glob, $against, $case_sensitive = true)
66 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
67 explodePageList ($input, $perm = false)
69 can ($object, $method)
70 function_usable ($function_name)
72 better_srand ($seed = '')
75 subPageSlice ($pagename, $pos)
76 isActionPage ($filename)
80 obj2hash ($obj, $exclude = false, $fields = false)
83 url_get_contents ($uri)
85 firstNWordsOfContent ($n, $content)
86 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
89 charset_convert($from, $to, $data)
90 string_starts_with($string, $prefix)
91 string_ends_with($string, $suffix)
92 array_remove($arr,$value)
93 longer_timeout($secs=30)
96 binary_search($needle, $haystack)
98 javascript_quote_string($s)
100 is_whole_number($var)
101 parse_attributes($line)
105 function: linkExistingWikiWord($wikiword, $linktext, $version)
106 moved to: lib/WikiTheme.php
108 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
109 else define('_PHPWIKI_STDLIB_LOADED', true);
111 if (!defined('MAX_PAGENAME_LENGTH')) {
112 define('MAX_PAGENAME_LENGTH', 100);
116 * Convert string to a valid XML identifier.
118 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
120 * We would like to have, e.g. named anchors within wiki pages
121 * names like "Table of Contents" --- clearly not a valid XML
122 * fragment identifier.
124 * This function implements a one-to-one map from {any string}
125 * to {valid XML identifiers}.
128 * converting all bytes not in [A-Za-z0-9:_-],
129 * and any leading byte not in [A-Za-z] to 'xbb.',
130 * where 'bb' is the hexadecimal representation of the
133 * As a special case, the empty string is converted to 'empty.'
138 function MangleXmlIdentifier($str) {
142 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
143 "'x' . sprintf('%02x', ord('\\0')) . '.'",
147 function UnMangleXmlIdentifier($str) {
148 if ($str == 'empty.')
150 return preg_replace('/x(\w\w)\./e',
151 "sprintf('%c', hex('\\0'))",
156 * Returns a name for the WIKI_ID cookie that should be unique on the host.
157 * But for it to be unique you must have set a unique WIKI_NAME in your
158 * configuration file.
159 * @return string The name of the WIKI_ID cookie to use for this wiki.
161 function getCookieName() {
162 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
166 * Generates a valid URL for a given Wiki pagename.
167 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
168 * If a WikiDB_Page object function will extract the name to link to.
169 * If a WikiDB_PageRevision object function will extract the name to link to.
171 * @param boolean $get_abs_url Default value is false.
172 * @return string The absolute URL to the page passed as $pagename.
174 function WikiURL($pagename, $args = '', $get_abs_url = false) {
175 global $request, $WikiTheme;
178 if (is_object($pagename)) {
179 if (isa($pagename, 'WikiDB_Page')) {
180 $pagename = $pagename->getName();
182 elseif (isa($pagename, 'WikiDB_PageRevision')) {
183 $page = $pagename->getPage();
184 $args['version'] = $pagename->getVersion();
185 $pagename = $page->getName();
187 elseif (isa($pagename, 'WikiPageName')) {
188 $anchor = $pagename->anchor;
189 $pagename = $pagename->name;
191 $anchor = $pagename->anchor;
192 $pagename = $pagename->name;
195 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
197 $args = 'start_debug=' . $request->getArg('start_debug');
198 elseif (is_array($args))
199 $args['start_debug'] = $request->getArg('start_debug');
201 $args .= '&start_debug=' . $request->getArg('start_debug');
203 if (is_array($args)) {
205 foreach ($args as $key => $val) {
206 // avoid default args
207 if (USE_PATH_INFO and $key == 'pagename')
209 elseif ($key == 'action' and $val == 'browse')
211 elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
212 $enc_args[] = urlencode($key) . '=' . urlencode($val);
214 $args = join('&', $enc_args);
217 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
218 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
219 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
221 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
222 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
223 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
226 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
228 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
238 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
239 $url .= "?pagename=" . rawurlencode($pagename);
244 $url .= "#" . MangleXmlIdentifier($anchor);
248 /** Convert relative URL to absolute URL.
250 * This converts a relative URL to one of PhpWiki's support files
251 * to an absolute one.
254 * @return string Absolute URL
256 function AbsoluteURL ($url) {
257 if (preg_match('/^https?:/', $url))
259 if ($url[0] != '/') {
260 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
261 while ($base != '/' and substr($url, 0, 3) == "../") {
262 $url = substr($url, 3);
263 $base = dirname($base);
269 return SERVER_URL . $url;
272 function DataURL ($url) {
273 if (preg_match('/^https?:/', $url))
275 $url = NormalizeWebFileName($url);
276 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
277 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
278 return AbsoluteURL($url);
282 * Generates icon in front of links.
284 * @param string $protocol_or_url URL or protocol to determine which icon to use.
286 * @return HtmlElement HtmlElement object that contains data to create img link to
287 * icon for use with url or protocol passed to the function. False if no img to be
290 function IconForLink($protocol_or_url) {
292 if (0 and $filename_suffix == false) {
293 // display apache style icon for file type instead of protocol icon
294 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
295 // - document: html, htm, text, txt, rtf, pdf, doc
296 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
297 // - audio: mp3,mp2,aiff,aif,au
298 // - multimedia: mpeg,mpg,mov,qt
300 list ($proto) = explode(':', $protocol_or_url, 2);
301 $src = $WikiTheme->getLinkIconURL($proto);
303 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon'));
310 * Glue icon in front of or after text.
311 * Pref: 'noLinkIcons' - ignore icon if set
312 * WikiTheme: 'LinkIcons' - 'yes' at front
313 * - 'no' display no icon
314 * - 'front' display at left
315 * - 'after' display at right
317 * @param string $protocol_or_url Protocol or URL. Used to determine the
319 * @param string $text The text.
320 * @return XmlContent.
322 function PossiblyGlueIconToText($proto_or_url, $text) {
323 global $request, $WikiTheme;
324 if ($request->getPref('noLinkIcons'))
326 $icon = IconForLink($proto_or_url);
329 if ($where = $WikiTheme->getLinkIconAttr()) {
330 if ($where == 'no') return $text;
331 if ($where != 'after') $where = 'front';
335 if ($where == 'after') {
336 // span the icon only to the last word (tie them together),
337 // to let the previous words wrap on line breaks.
338 if (!is_object($text)) {
339 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
340 list (, $prefix, $last_word) = $m;
346 $text = HTML::span(array('style' => 'white-space: nowrap'),
347 $last_word, HTML::Raw(' '), $icon);
349 $text = HTML($prefix, $text);
352 // span the icon only to the first word (tie them together),
353 // to let the next words wrap on line breaks
354 if (!is_object($text)) {
355 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
356 list (, $first_word, $tail) = $m;
362 $text = HTML::span(array('style' => 'white-space: nowrap'),
365 $text = HTML($text, $tail);
370 * Determines if the url passed to function is safe, by detecting if the characters
371 * '<', '>', or '"' are present.
372 * Check against their urlencoded values also.
374 * @param string $url URL to check for unsafe characters.
375 * @return boolean True if same, false else.
377 function IsSafeURL($url) {
378 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
382 * Generates an HtmlElement object to store data for a link.
384 * @param string $url URL that the link will point to.
385 * @param string $linktext Text to be displayed as link.
386 * @return HtmlElement HtmlElement object that contains data to construct an html link.
388 function LinkURL($url, $linktext = '') {
389 // FIXME: Is this needed (or sufficient?)
390 if(! IsSafeURL($url)) {
391 $link = HTML::span(array('class' => 'error'), _('Bad URL -- remove all of <, >, "'));
396 $linktext = preg_replace("/mailto:/A", "", $url);
397 $args = array('href' => $url);
398 if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
399 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
400 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
402 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
409 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
410 * Disallows sizes which are too small.
411 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
413 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
415 function LinkImage($url, $alt = "") {
416 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
417 // Disallow tags in img src urls. Typical CSS attacks.
418 // FIXME: Is this needed (or sufficient?)
419 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
421 // support new syntax: [prefix/image.jpg size=50% border=n]
422 if (empty($alt)) $alt = "";
424 if (! IsSafeURL($url)) {
425 $link = HTML::span(array('class' => 'error'), _('Bad URL for image -- remove all of <, >, "'));
428 // spaces in inline images must be %20 encoded!
429 $link = HTML::img(array('src' => $url));
431 // Extract attributes and shorten url
432 $arr = parse_attributes(strstr($url, " "));
433 foreach ($arr as $attr => $value) {
434 // strip attr=... url suffix
435 $link->setAttr('src', $url);
436 $i = strpos($url, $attr);
437 $url = substr($url, 0, $i-1);
438 // These attributes take strings: lang, id, title, alt
439 if (($attr == "lang")
441 || ($attr == "title")
442 || ($attr == "alt")) {
443 $link->setAttr($attr, $value);
445 // align = bottom|middle|top|left|right
446 // we allow "center" as synonym for "middle"
447 elseif (($attr == "align")
448 && (($value == "bottom")
449 || ($value == "middle")
450 || ($value == "center")
452 || ($value == "left")
453 || ($value == "right"))) {
454 if ($value == "center") {
457 $link->setAttr($attr, $value);
459 // These attributes take a number (pixels): border, hspace, vspace
460 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
461 && (is_numeric($value))) {
462 $link->setAttr($attr, (int)$value);
464 // These attributes take a number (pixels) or a percentage: height, width
465 elseif ((($attr == "height") || ($attr == "width"))
466 && (preg_match('/\d+[%p]?x?/', $value))) {
467 $link->setAttr($attr, $value);
469 // We allow size=50% and size=20x30
470 // We replace this with "width" and "height" HTML attributes
471 elseif ($attr == "size") {
472 if (preg_match('/(\d+%)/', $value, $m)) {
473 $link->setAttr('width',$m[1]);
474 $link->setAttr('height',$m[1]);
475 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
476 $link->setAttr('width',$m[1]);
477 $link->setAttr('height',$m[2]);
480 $url = substr(strrchr($ori_url, "/"), 1);
481 $link = HTML::span(array('class' => 'error'),
482 sprintf(_("Invalid attribute %s=%s for image %s"),
483 $attr, $value, $url));
487 // Correct silently the most common error
488 if (strstr($ori_url, " ") and !preg_match("/^http/",$url)) {
489 // space belongs to the path
490 $file = NormalizeLocalFileName($ori_url);
491 if (file_exists($file)) {
492 $link = HTML::img(array('src' => $ori_url));
494 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
495 $url, $ori_url), E_USER_WARNING);
496 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
497 $file = substr($file, strlen(getUploadDataPath()));
498 $path = getUploadFilePath().$file;
499 if (file_exists($path)) {
500 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
501 $url, $ori_url), E_USER_WARNING);
502 $link->setAttr('src', getUploadDataPath() . $file);
507 if (!$link->getAttr('alt')) {
508 $link->setAttr('alt', $alt);
510 // Check width and height as spam countermeasure
511 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
512 //$width = (int) $width; // px or % or other suffix
513 //$height = (int) $height;
514 if (($width < 3 and $height < 10) or
515 ($height < 3 and $width < 20) or
516 ($height < 7 and $width < 7))
518 $link = HTML::span(array('class' => 'error'),
519 _("Invalid image size"));
524 // Prepare for getimagesize($url)
525 // $url only valid for external urls, otherwise local path
526 if (DISABLE_GETIMAGESIZE)
528 elseif (! preg_match("/\.$force_img$/i", $url))
529 ; // only valid image extensions or scripts assumed to generate images
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
545 $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
551 if (($width < 3 and $height < 10)
552 or ($height < 3 and $width < 20)
553 or ($height < 7 and $width < 7))
555 $link = HTML::span(array('class' => 'error'),
556 _("Invalid image size"));
561 $link->setAttr('class', 'inlineimage');
563 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
564 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
565 * Note: Allow cgi's (pl,cgi) returning images.
567 if (!preg_match("/\.(".$force_img.")/i", $ori_url)) {
568 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
569 // => HTML::object(array('src' => $url)) ...;
570 return ImgObject($link, $ori_url);
576 * <object> / <embed> tags instead of <img> for all non-image extensions
578 * Called by LinkImage(), not directly.
579 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
580 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
581 * $alt may be an alternate img
582 * TODO: Need to unify with WikiPluginCached::embedObject()
584 * Note that Safari 1.0 will crash with <object>, so use only <embed>
585 * http://www.alleged.org.uk/pdc/2002/svg-object.html
587 * Allowed object tags:
589 * DATA=URI (object data)
590 * CLASSID=URI (location of implementation)
591 * ARCHIVE=CDATA (archive files)
592 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
593 * WIDTH=Length (object width)
594 * HEIGHT=Length (object height)
595 * NAME=CDATA (name for form submission)
596 * USEMAP=URI (client-side image map)
597 * TYPE=ContentType (content-type of object)
598 * CODETYPE=ContentType (content-type of code)
599 * STANDBY=Text (message to show while loading)
600 * TABINDEX=NUMBER (position in tabbing order)
601 * DECLARE (do not instantiate object)
602 * The rest is added as <param name="" value="" /> tags
604 function ImgObject($img, $url) {
605 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
606 $params = explode(",","id,width,height,data,classid,archive,codebase,name,usemap,type,".
607 "codetype,standby,tabindex,declare");
608 if (is_array($url)) {
611 foreach ($args as $attr => $value) {
612 foreach ($params as $param) {
613 if ($param == $attr) {
614 $img->setAttr($param, $value);
615 if (isset($found[$param])) $found[$param]++;
616 else $found[$param] = 1;
621 // now all remaining args are added as <param> to the object
623 foreach ($args as $attr => $value) {
624 if (!isset($found[$attr])) {
625 $params[] = HTML::param(array('name' => $attr,
629 $url = $img->getAttr('src');
630 $force_img = "png|jpg|gif|jpeg|bmp";
631 if (!preg_match("/\.(".$force_img.")/i", $url)) {
632 $img->setAttr('src', false);
635 $args = explode(' ', $url);
636 if (count($args) >= 1) {
637 $url = array_shift($args);
639 foreach ($args as $attr) {
640 foreach ($params as $param) {
641 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
642 $img->setAttr($param, $m[1]);
643 if (isset($found[$param])) $found[$param]++;
644 else $found[$param] = 1;
649 // now all remaining args are added as <param> to the object
651 foreach ($args as $attr) {
652 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
653 $params[] = HTML::param(array('name' => $m[1],
659 $type = $img->getAttr('type');
661 if (function_exists('mime_content_type') && file_exists($url)) {
662 $type = mime_content_type($url);
665 $object = HTML::object(array_merge($img->_attr,
666 array('type' => $type)), //'src' => $url
668 $object->setAttr('class', 'inlineobject');
670 foreach ($params as $param) $object->pushContent($param);
672 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
673 return HTML::embed($object->_attr, $object->_content);
675 $object->pushContent(HTML::embed($object->_attr));
681 // var in php5 deprecated
683 $this->items = array();
686 function push($item) {
687 $this->items[$this->size] = $item;
693 if ($this->size == 0) {
694 return false; // stack is empty
697 return $this->items[$this->size];
706 return $this->items[$this->size - 1];
712 // end class definition
714 function SplitQueryArgs ($query_args = '')
716 // FIXME: use the arg-seperator which might not be &
717 $split_args = explode('&', $query_args);
719 while (list($key, $val) = each($split_args))
720 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
721 $args[$m[1]] = $m[2];
725 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
728 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
729 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
733 $pagename = urldecode($m[1]);
736 if (empty($pagename) &&
737 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
738 // Convert old style links (to not break diff links in
740 $pagename = urldecode($m[2]);
741 $args = array("action" => $m[1]);
744 $args = SplitQueryArgs($qargs);
747 if (empty($pagename))
748 $pagename = $GLOBALS['request']->getArg('pagename');
750 if (isset($args['action']) && $args['action'] == 'browse')
751 unset($args['action']);
754 if (empty($args['action']))
756 else if (is_safe_action($args['action']))
757 $class = 'wikiaction';
759 if (empty($args['action']) || is_safe_action($args['action']))
760 $class = 'wikiaction';
762 // Don't allow administrative links on unlocked pages.
763 $dbi = $GLOBALS['request']->getDbh();
764 $page = $dbi->getPage($basepage ? $basepage : $pagename);
765 if (!$page->get('locked'))
766 return HTML::span(array('class' => 'wikiunsafe'),
767 HTML::u(_("Lock page to enable link")));
768 $class = 'wikiadmin';
772 $text = HTML::span(array('class' => 'rawurl'), $url);
774 $wikipage = new WikiPageName($pagename);
775 if (!$wikipage->isValid()) {
777 return $WikiTheme->linkBadWikiWord($wikipage, $url);
780 return HTML::a(array('href' => WikiURL($pagename, $args),
786 * A class to assist in parsing wiki pagenames.
788 * Now with subpages and anchors, parsing and passing around
789 * pagenames is more complicated. This should help.
793 /** Short name for page.
795 * This is the value of $name passed to the constructor.
796 * (For use, e.g. as a default label for links to the page.)
800 /** The full page name.
802 * This is the full name of the page (without anchor).
808 * This is the referenced anchor within the page, or the empty string.
814 * @param mixed $name Page name.
815 * WikiDB_Page, WikiDB_PageRevision, or string.
816 * This can be a relative subpage name (like '/SubPage'),
817 * or can be the empty string to refer to the $basename.
819 * @param string $anchor For links to anchors in page.
821 * @param mixed $basename Page name from which to interpret
822 * relative or other non-fully-specified page names.
824 function WikiPageName($name, $basename=false, $anchor=false) {
825 if (is_string($name)) {
826 $this->shortName = $name;
827 if (strstr($name, ':')) {
828 list($moniker, $shortName) = explode (":", $name, 2);
829 $map = getInterwikiMap(); // allow overrides to custom maps
830 if (isset($map->_map[$moniker])) {
831 $url = $map->_map[$moniker];
832 if (strstr($url, '%s'))
833 $url = sprintf($url, $shortName);
837 // expand Talk or User, but not to absolute urls!
838 if (strstr($url, '//')) {
839 if ($moniker == 'Talk')
840 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
841 elseif ($moniker == 'User')
846 if (strstr($shortName, '?')) {
847 list($shortName, $dummy) = explode("\?", $shortName, 2);
849 $this->shortName = $shortName;
852 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
853 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
855 $name = $this->_pagename($basename) . $name;
857 $name = $this->_normalize_bad_pagename($name);
858 $this->shortName = $name;
863 $name = $this->_pagename($name);
864 $this->shortName = $name;
867 $this->name = $this->_check($name);
868 $this->anchor = (string)$anchor;
875 function getParent() {
877 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
879 return substr($name, 0, -strlen($tail));
882 function isValid($strict = false) {
884 return !isset($this->_errors);
885 return (is_string($this->name) and $this->name != '');
888 function getWarnings() {
890 if (isset($this->_warnings))
891 $warnings = array_merge($warnings, $this->_warnings);
892 if (isset($this->_errors))
893 $warnings = array_merge($warnings, $this->_errors);
897 return sprintf(_("'%s': Bad page name: %s"),
898 $this->shortName, join(', ', $warnings));
901 function _pagename($page) {
902 if (isa($page, 'WikiDB_Page'))
903 return $page->getName();
904 elseif (isa($page, 'WikiDB_PageRevision'))
905 return $page->getPageName();
906 elseif (isa($page, 'WikiPageName'))
908 // '0' or e.g. '1984' should be allowed though
909 if (!is_string($page) and !is_integer($page)) {
910 trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
911 $page, gettype($page), get_class($page)),
914 //assert(is_string($page));
918 function _normalize_bad_pagename($name) {
919 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
921 // Punt... You really shouldn't get here.
924 return $request->getArg('pagename');
926 assert($name[0] == SUBPAGE_SEPARATOR);
927 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
928 return substr($name, 1);
932 * Compress internal white-space to single space character.
934 * This leads to problems with loading a foreign charset pagename,
935 * which cannot be deleted anymore, because unknown chars are compressed.
936 * So BEFORE importing a file _check must be done !!!
938 function _check($pagename) {
939 // Compress internal white-space to single space character.
940 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
941 if ($pagename != $orig)
942 $this->_warnings[] = _("White space converted to single space");
944 // Delete any control characters.
945 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
946 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
947 if ($pagename != $orig)
948 $this->_errors[] = _("Control characters not allowed");
951 // Strip leading and trailing white-space.
952 $pagename = trim($pagename);
955 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
956 $pagename = substr($pagename, 1);
957 if ($pagename != $orig)
958 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
960 // ";" is urlencoded, so safe from php arg-delim problems
961 /*if (strstr($pagename, ';')) {
962 $this->_warnings[] = _("';' is deprecated");
963 $pagename = str_replace(';', '', $pagename);
966 // not only for SQL, also to restrict url length
967 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
968 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
969 $this->_errors[] = _("Page name too long");
972 // disallow some chars only on file and cvs
973 if ((DATABASE_TYPE == 'cvs'
974 or DATABASE_TYPE == 'file'
975 or DATABASE_TYPE == 'flatfile')
976 and preg_match('/(:|\.\.)/', $pagename, $m))
978 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
979 $pagename = str_replace('..', '', $pagename);
980 $pagename = str_replace(':', '', $pagename);
988 * Convert old page markup to new-style markup.
990 * @param string $text Old-style wiki markup.
992 * @param string $markup_type
994 * <dt><code>"block"</code> <dd>Convert all markup.
995 * <dt><code>"inline"</code> <dd>Convert only inline markup.
996 * <dt><code>"links"</code> <dd>Convert only link markup.
999 * @return string New-style wiki markup.
1001 * @bugs Footnotes don't work quite as before (esp if there are
1002 * multiple references to the same footnote. But close enough,
1003 * probably for now....
1004 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
1005 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
1006 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1007 * also known to crash, even with Apache1.
1009 function ConvertOldMarkup ($text, $markup_type = "block") {
1015 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
1016 // AnciennesR%E8glesDeFormatage crashes.
1017 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1018 // also known to crash, even with Apache1.
1019 $debug_skip = false;
1020 // I suspect this only to crash with Apache2 and IIS.
1021 if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
1022 and preg_match("/plugin CreateToc/", $text))
1024 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
1025 ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
1026 ._("Skipped."), E_USER_WARNING);
1028 //if (!DEBUG) return $text;
1033 /*****************************************************************
1034 * Conversions for inline markup:
1041 // escape escaped brackets
1045 // change ! escapes to ~'s.
1046 global $WikiNameRegexp, $request;
1047 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1048 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1049 $map = getInterwikiMap();
1050 if ($map_regex = $map->getRegexp())
1051 $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 = explode("\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)
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());
1297 * Get time offset for local time zone.
1299 * @param $time time_t Get offset for this time. Default: now.
1300 * @param $no_colon boolean Don't put colon between hours and minutes.
1301 * @return string Offset as a string in the format +HH:MM.
1303 function TimezoneOffset ($time = false, $no_colon = false) {
1304 if ($time === false)
1306 $secs = date('Z', $time);
1315 $colon = $no_colon ? '' : ':';
1316 $mins = intval(($secs + 30) / 60);
1317 return sprintf("%s%02d%s%02d",
1318 $sign, $mins / 60, $colon, $mins % 60);
1323 * Format time in ISO-8601 format.
1325 * @param $time time_t Time. Default: now.
1326 * @return string Date and time in ISO-8601 format.
1328 function Iso8601DateTime ($time = false) {
1329 if ($time === false)
1331 $tzoff = TimezoneOffset($time);
1332 $date = date('Y-m-d', $time);
1333 $time = date('H:i:s', $time);
1334 return $date . 'T' . $time . $tzoff;
1338 * Format time in RFC-2822 format.
1340 * @param $time time_t Time. Default: now.
1341 * @return string Date and time in RFC-2822 format.
1343 function Rfc2822DateTime ($time = false) {
1344 if ($time === false)
1346 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1350 * Format time in RFC-1123 format.
1352 * @param $time time_t Time. Default: now.
1353 * @return string Date and time in RFC-1123 format.
1355 function Rfc1123DateTime ($time = false) {
1356 if ($time === false)
1358 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1361 /** Parse date in RFC-1123 format.
1363 * According to RFC 1123 we must accept dates in the following
1366 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1367 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1368 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1370 * (Though we're only allowed to generate dates in the first format.)
1372 function ParseRfc1123DateTime ($timestr) {
1373 $timestr = trim($timestr);
1374 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1375 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1377 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1379 elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1380 .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1382 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1383 if ($year < 70) $year += 2000;
1384 elseif ($year < 100) $year += 1900;
1386 elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1387 .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1389 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1396 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1398 return false; // failed
1403 * Format time to standard 'ctime' format.
1405 * @param $time time_t Time. Default: now.
1406 * @return string Date and time.
1408 function CTime ($time = false)
1410 if ($time === false)
1412 return date("D M j H:i:s Y", $time);
1417 * Format number as kibibytes or bytes.
1418 * Short format is used for PageList
1419 * Long format is used in PageInfo
1421 * @param $bytes int. Default: 0.
1422 * @param $longformat bool. Default: false.
1423 * @return class FormattedText (XmlElement.php).
1425 function ByteFormatter ($bytes = 0, $longformat = false) {
1428 if ($bytes < 1024) {
1430 $size = fmt("%s B", $bytes);
1432 $size = fmt("%s bytes", $bytes);
1435 $kb = round($bytes / 1024, 1);
1437 $size = fmt("%s KiB", $kb);
1439 $size = fmt("%s KiB (%s bytes)", $kb, $bytes);
1445 * Internationalized printf.
1447 * This is essentially the same as PHP's built-in printf
1448 * with the following exceptions:
1450 * <li> It passes the format string through gettext().
1451 * <li> It supports the argument reordering extensions.
1458 * __printf("Differences between versions %s and %s of %s",
1459 * $new_link, $old_link, $page_link);
1462 * Then in locale/po/de.po, one can reorder the printf arguments:
1465 * msgid "Differences between %s and %s of %s."
1466 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1469 * (Note that while PHP tries to expand $vars within double-quotes,
1470 * the values in msgstr undergo no such expansion, so the '$'s
1473 * One shouldn't use reordered arguments in the default format string.
1474 * Backslashes in the default string would be necessary to escape the
1475 * '$'s, and they'll cause all kinds of trouble....
1477 function __printf ($fmt) {
1478 $args = func_get_args();
1480 echo __vsprintf($fmt, $args);
1484 * Internationalized sprintf.
1486 * This is essentially the same as PHP's built-in printf with the
1487 * following exceptions:
1490 * <li> It passes the format string through gettext().
1491 * <li> It supports the argument reordering extensions.
1496 function __sprintf ($fmt) {
1497 $args = func_get_args();
1499 return __vsprintf($fmt, $args);
1503 * Internationalized vsprintf.
1505 * This is essentially the same as PHP's built-in printf with the
1506 * following exceptions:
1509 * <li> It passes the format string through gettext().
1510 * <li> It supports the argument reordering extensions.
1515 function __vsprintf ($fmt, $args) {
1516 $fmt = gettext($fmt);
1517 // PHP's sprintf doesn't support variable with specifiers,
1518 // like sprintf("%*s", 10, "x"); --- so we won't either.
1520 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1521 // Format string has '%2$s' style argument reordering.
1522 // PHP doesn't support this.
1523 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1524 // literal variable name substitution only to keep locale
1525 // strings uncluttered
1526 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1527 '%1\$s','%s'), E_USER_WARNING); //php+locale error
1529 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1532 // Reorder arguments appropriately.
1533 foreach($m[1] as $argnum) {
1534 if ($argnum < 1 || $argnum > count($args))
1535 trigger_error(sprintf(_("%s: argument index out of range"),
1536 $argnum), E_USER_WARNING);
1537 $newargs[] = $args[$argnum - 1];
1542 // Not all PHP's have vsprintf, so...
1543 array_unshift($args, $fmt);
1544 return call_user_func_array('sprintf', $args);
1547 function file_mtime ($filename) {
1548 if ($stat = @stat($filename))
1554 function sort_file_mtime ($a, $b) {
1555 $ma = file_mtime($a);
1556 $mb = file_mtime($b);
1557 if (!$ma or !$mb or $ma == $mb) return 0;
1558 return ($ma > $mb) ? -1 : 1;
1563 * Build an array in $this->_fileList of files from $dirname.
1564 * Subdirectories are not traversed.
1566 * (This was a function LoadDir in lib/loadsave.php)
1567 * See also http://www.php.net/manual/en/function.readdir.php
1569 function getFiles($exclude='', $sortby='', $limit='') {
1570 $list = $this->_fileList;
1573 require_once 'lib/PageList.php';
1574 switch (Pagelist::sortby($sortby, 'db')) {
1575 case 'pagename ASC': break;
1576 case 'pagename DESC':
1577 $list = array_reverse($list);
1580 usort($list,'sort_file_mtime');
1583 usort($list,'sort_file_mtime');
1584 $list = array_reverse($list);
1589 return array_splice($list, 0, $limit);
1593 function _filenameSelector($filename) {
1594 if (! $this->_pattern )
1597 if (! $this->_pcre_pattern )
1598 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1599 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1604 function fileSet($directory, $filepattern = false) {
1605 $this->_fileList = array();
1606 $this->_pattern = $filepattern;
1608 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1610 $this->_case = !isWindows();
1611 $this->_pathsep = '/';
1613 if (empty($directory)) {
1614 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1616 return; // early return
1619 @ $dir_handle = opendir($dir=$directory);
1620 if (empty($dir_handle)) {
1621 trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1622 $dir), E_USER_NOTICE);
1623 return; // early return
1626 while ($filename = readdir($dir_handle)) {
1627 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1629 if ($this->_filenameSelector($filename)) {
1630 array_push($this->_fileList, "$filename");
1631 //trigger_error(sprintf(_("found file %s"), $filename),
1632 // E_USER_NOTICE); //debugging
1635 closedir($dir_handle);
1641 // expands a list containing regex's to its matching entries
1642 class ListRegexExpand {
1643 //var $match, $list, $index, $case_sensitive;
1644 function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1645 $this->match = $match;
1646 $this->list = &$list;
1647 $this->case_sensitive = $case_sensitive;
1648 //$this->index = false;
1650 function listMatchCallback ($item, $key) {
1651 $quoted = str_replace('/','\/',$item);
1652 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1654 unset($this->list[$this->index]);
1655 $this->list[] = $item;
1658 function expandRegex ($index, &$pages) {
1659 $this->index = $index;
1660 array_walk($pages, array($this, 'listMatchCallback'));
1665 // Convert fileglob to regex style:
1666 // Convert some wildcards to pcre style, escape the rest
1667 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1668 // Fixed bug #994994: "/" in $glob.
1669 function glob_to_pcre ($glob) {
1670 // check simple case: no need to escape
1671 $escape = '\[](){}=!<>|:/';
1672 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1674 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1675 $glob = strtr($glob, "\\", "\xff");
1676 $glob = str_replace("/", "\\/", $glob);
1677 // first convert some unescaped expressions to pcre style: . => \.
1679 $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/',
1680 "\\1\xff\\2", $glob);
1683 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1684 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1685 if (!preg_match('/^[\?\*]/', $glob))
1687 if (!preg_match('/[\?\*]$/', $glob))
1690 // Fixes Bug 1182997
1691 // .*? handled above, now escape the rest
1692 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1693 $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/',
1695 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1697 $re = preg_replace('/\xff/', '', $re);
1701 function glob_match ($glob, $against, $case_sensitive = true) {
1702 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1706 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1707 $list = explode(',',$input);
1708 // expand wildcards from list of $allnames
1709 if (preg_match('/[\?\*]/',$input)) {
1710 // Optimizing loop invariants:
1711 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1712 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1714 if (preg_match('/[\?\*]/',$f)) {
1716 $expand = new ListRegexExpand($list,
1717 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1718 $expand->expandRegex($i, $allnames);
1725 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1726 function explodePageList($input, $include_empty=false, $sortby='pagename',
1727 $limit='', $exclude='') {
1728 include_once 'lib/PageList.php';
1729 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1732 // Class introspections
1735 * Determine whether object is of a specified type.
1736 * In PHP builtin since 4.2.0 as is_a()
1737 * is_a() deprecated in PHP 5, in favor of instanceof operator
1739 * @param $object object An object.
1740 * @param $class string Class name.
1741 * @return bool True iff $object is a $class
1742 * or a sub-type of $class.
1744 function isa ($object, $class) {
1745 //if (check_php_version(5))
1746 // return $object instanceof $class;
1747 if (!check_php_version(5))
1748 return is_a($object, $class);
1750 $lclass = check_php_version(5) ? $class : strtolower($class);
1751 return is_object($object)
1752 && ( strtolower(get_class($object)) == strtolower($class)
1753 || is_subclass_of($object, $lclass) );
1756 /** Determine whether a function is okay to use.
1758 * Some providers (e.g. Lycos) disable some of PHP functions for
1759 * "security reasons." This makes those functions, of course,
1760 * unusable, despite the fact the function_exists() says they
1763 * This function test to see if a function exists and is not
1764 * disallowed by PHP's disable_functions config setting.
1766 * @param string $function_name Function name
1767 * @return bool True iff function can be used.
1769 function function_usable($function_name) {
1771 if (!is_array($disabled)) {
1772 $disabled = array();
1773 // Use get_cfg_var since ini_get() is one of the disabled functions
1774 // (on Lycos, at least.)
1775 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1776 foreach ($split as $f)
1777 $disabled[strtolower($f)] = true;
1780 return ( function_exists($function_name)
1781 and ! isset($disabled[strtolower($function_name)])
1788 * This is used for generating ETags.
1790 function wikihash ($x) {
1791 if (is_scalar($x)) {
1794 elseif (is_array($x)) {
1796 return md5(serialize($x));
1798 elseif (is_object($x)) {
1801 trigger_error("Can't hash $x", E_USER_ERROR);
1806 * Seed the random number generator.
1808 * better_srand() ensures the randomizer is seeded only once.
1810 * How random do you want it? See:
1811 * http://www.php.net/manual/en/function.srand.php
1812 * http://www.php.net/manual/en/function.mt-srand.php
1814 function better_srand($seed = '') {
1815 static $wascalled = FALSE;
1817 $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1818 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1820 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1824 function rand_ascii($length = 1) {
1827 for ($i = 1; $i <= $length; $i++) {
1828 // return only typeable 7 bit ascii, avoid quotes
1829 if (function_exists('mt_rand'))
1830 $s .= chr(mt_rand(40, 126));
1832 // the usually bad glibc srand()
1833 $s .= chr(rand(40, 126));
1838 /* by Dan Frankowski.
1840 function rand_ascii_readable ($length = 6) {
1841 // Pick a few random letters or numbers
1844 // Don't use 1lI0O, because they're hard to read
1845 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1846 $letter_len = strlen($letters);
1847 for ($i=0; $i < $length; $i++) {
1848 if (function_exists('mt_rand'))
1849 $word .= $letters[mt_rand(0, $letter_len-1)];
1851 $word .= $letters[rand(0, $letter_len-1)];
1857 * Recursively count all non-empty elements
1858 * in array of any dimension or mixed - i.e.
1859 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1860 * See http://www.php.net/manual/en/function.count.php
1862 function count_all($arg) {
1863 // skip if argument is empty
1865 //print_r($arg); //debugging
1867 // not an array, return 1 (base case)
1870 // else call recursively for all elements $arg
1871 foreach($arg as $key => $val)
1872 $count += count_all($val);
1877 function isSubPage($pagename) {
1878 return (strstr($pagename, SUBPAGE_SEPARATOR));
1881 function subPageSlice($pagename, $pos) {
1882 $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1883 $pages = array_slice($pages,$pos,1);
1887 function isActionPage($filename) {
1889 global $AllActionPages;
1891 $localizedAllActionPages = array_map("gettext", $AllActionPages);
1893 return (in_array($filename, $localizedAllActionPages));
1899 * Class for "popping up" and alert box. (Except that right now, it doesn't
1903 * This is a hackish and needs to be refactored. However it would be nice to
1904 * unify all the different methods we use for showing Alerts and Dialogs.
1905 * (E.g. "Page deleted", login form, ...)
1910 * @param object $request
1911 * @param mixed $head Header ("title") for alert box.
1912 * @param mixed $body The text in the alert box.
1913 * @param hash $buttons An array mapping button labels to URLs.
1914 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1916 function Alert($head, $body, $buttons=false) {
1917 if ($buttons === false)
1920 if (is_array($body)) {
1922 foreach ($body as $li) {
1923 $html->pushContent(HTML::li($li));
1927 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1928 $this->_buttons = $buttons;
1932 * Show the alert box.
1937 $tokens = $this->_tokens;
1938 $tokens['BUTTONS'] = $this->_getButtons();
1940 $request->discardOutput();
1941 $tmpl = new Template('dialog', $request, $tokens);
1947 function _getButtons() {
1950 $buttons = $this->_buttons;
1952 $buttons = array(_("OK") => $request->getURLtoSelf());
1955 foreach ($buttons as $label => $url)
1956 print "$label $url\n";
1957 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1958 return new XmlContent($out);
1963 // 1.3.9-p1 => 1030.091
1964 // 1.3.10pre => 1030.099
1965 // 1.3.11pre-20041120 => 1030.1120041120
1966 // 1.3.12-rc1 => 1030.119
1967 function phpwiki_version() {
1968 static $PHPWIKI_VERSION;
1969 if (!isset($PHPWIKI_VERSION)) {
1970 $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1971 $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1972 $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1973 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1974 $PHPWIKI_VERSION -= 0.01;
1976 return $PHPWIKI_VERSION;
1979 function phpwiki_gzhandler($ob) {
1980 if (function_exists('gzencode'))
1981 $ob = gzencode($ob);
1982 $GLOBALS['request']->_ob_get_length = strlen($ob);
1983 if (!headers_sent()) {
1984 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1989 function isWikiWord($word) {
1990 global $WikiNameRegexp;
1991 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1992 return preg_match("/^$WikiNameRegexp\$/",$word);
1995 // needed to store serialized objects-values only (perm, pref)
1996 function obj2hash ($obj, $exclude = false, $fields = false) {
1998 if (! $fields ) $fields = get_object_vars($obj);
1999 foreach ($fields as $key => $val) {
2000 if (is_array($exclude)) {
2001 if (in_array($key, $exclude)) continue;
2009 * isAsciiString($string)
2011 function isAsciiString($s) {
2012 $ptrASCII = '[\x00-\x7F]';
2013 return preg_match("/^($ptrASCII)*$/s", $s);
2017 * isUtf8String($string) - cheap utf-8 detection
2019 * segfaults for strings longer than 10kb!
2020 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
2021 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
2023 function isUtf8String( $s ) {
2024 $ptrASCII = '[\x00-\x7F]';
2025 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
2026 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
2027 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
2028 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
2029 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
2030 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2034 * Check for UTF-8 URLs; Internet Explorer produces these if you
2035 * type non-ASCII chars in the URL bar or follow unescaped links.
2036 * Requires urldecoded pagename.
2037 * Fixes sf.net bug #953949
2039 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2041 function fixTitleEncoding( $s ) {
2046 if (empty($s)) return $s;
2048 $ishigh = preg_match( '/[\x80-\xff]/', $s);
2050 $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2051 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
2053 $isutf = ($ishigh ? isUtf8String($s) : true);
2054 $locharset = strtolower($charset);
2056 if( $locharset != "utf-8" and $ishigh and $isutf )
2057 $s = charset_convert('UTF-8', $locharset, $s);
2058 if ($locharset == "utf-8" and $ishigh and !$isutf )
2059 return utf8_encode( $s );
2061 // Other languages can safely leave this function, or replace
2062 // it with one to detect and convert another legacy encoding.
2067 * MySQL fulltext index doesn't grok utf-8, so we
2068 * need to fold cases and convert to hex.
2069 * src: languages/Language.php:stripForSearch() from mediawiki
2072 function stripForSearch( $string ) {
2073 global $wikiLowerChars;
2074 // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2075 return preg_replace(
2076 "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2077 "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2083 * Workaround for allow_url_fopen, to get the content of an external URI.
2084 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2085 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2087 function url_get_contents( $uri ) {
2088 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2089 return @file_get_contents($uri);
2091 require_once 'lib/HttpClient.php';
2092 $bits = parse_url($uri);
2093 $host = $bits['host'];
2094 $port = isset($bits['port']) ? $bits['port'] : 80;
2095 $path = isset($bits['path']) ? $bits['path'] : '/';
2096 if (isset($bits['query'])) {
2097 $path .= '?'.$bits['query'];
2099 $client = new HttpClient($host, $port);
2100 $client->use_gzip = false;
2101 if (!$client->get($path)) {
2104 return $client->getContent();
2110 * Generate consecutively named strings:
2111 * Name, Name2, Name3, ...
2113 function GenerateId($name) {
2114 static $ids = array();
2115 if (empty($ids[$name])) {
2120 return $name . $ids[$name];
2124 // from IncludePage. To be of general use.
2125 // content: string or array of strings
2126 function firstNWordsOfContent( $n, $content ) {
2127 if ($content and $n > 0) {
2128 if (is_array($content)) {
2129 // fixme: return a list of lines then?
2130 //$content = join("\n", $content);
2131 //$return_array = true;
2133 foreach ($content as $line) {
2134 $words = explode(' ', $line);
2135 if ($wordcount + count($words) > $n) {
2136 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2137 . sprintf(_("... (first %s words)"), $n);
2140 $wordcount += count($words);
2146 // fixme: use better whitespace/word seperators
2147 $words = explode(' ', $content);
2148 if (count($words) > $n) {
2149 return join(' ', array_slice($words, 0, $n))
2150 . sprintf(_("... (first %s words)"), $n);
2160 // moved from lib/plugin/IncludePage.php
2161 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2162 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2164 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
2165 . " \\s*$\\n?" // possible blank lines
2166 . " ( (?: ^.*\\n? )*? )" // some lines
2167 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2168 implode("\n", $content),
2170 // Strip trailing blanks lines and ---- <hr>s
2171 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2173 $text = $match[1] . $section ."\n". $text;
2174 return explode("\n", $text);
2177 $mesg = $page ." ". $section;
2180 return array(sprintf(_("<%s: no such section>"), $mesg));
2183 // Extract the first $sections sections of the page
2184 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2186 $mycontent = $content;
2189 while ($sections > 0) {
2191 if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
2192 . " \\s*$\\n?" // possible blank lines
2193 . " ( (?: ^.*\\n? )*? )" // some lines
2194 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2195 implode("\n", $mycontent),
2197 $section = $match[2];
2198 // Strip trailing blanks lines and ---- <hr>s
2199 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2201 $text = $match[1] . $section ."\n". $text;
2204 $mycontent = explode("\n", $match[4]);
2206 if ($sections === 0) {
2207 return explode("\n", $result);
2213 // use this faster version: only load ExternalReferrer if we came from an external referrer
2214 function isExternalReferrer(&$request) {
2215 if ($referrer = $request->get('HTTP_REFERER')) {
2216 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2217 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2218 require_once 'lib/ExternalReferrer.php';
2219 $se = new SearchEngines();
2220 return $se->parseSearchQuery($referrer);
2222 //if (DEBUG) return array('query' => 'wiki');
2227 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2229 function loadPhpExtension($extension) {
2230 if (!extension_loaded($extension)) {
2231 $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2232 $soname = ($isWindows ? 'php_' : '')
2234 . ($isWindows ? '.dll' : '.so');
2238 return extension_loaded($extension);
2241 function charset_convert($from, $to, $data) {
2243 //$wikicharset = strtolower($CHARSET);
2244 //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2245 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2246 return utf8_decode($data);
2247 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2248 return utf8_encode($data);
2250 if (loadPhpExtension("iconv")) {
2251 $tmpdata = iconv($from, $to, $data);
2253 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2257 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2262 function string_starts_with($string, $prefix) {
2263 return (substr($string, 0, strlen($prefix)) == $prefix);
2265 function string_ends_with($string, $suffix) {
2266 return (substr($string, -strlen($suffix)) == $suffix);
2268 function array_remove($arr,$value) {
2269 return array_values(array_diff($arr,array($value)));
2273 * Ensure that the script will have another $secs time left.
2274 * Works only if safe_mode is off.
2275 * For example not to timeout on waiting socket connections.
2276 * Use the socket timeout as arg.
2278 function longer_timeout($secs = 30) {
2279 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2280 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2281 if ($timeleft < $secs)
2282 @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2285 function printSimpleTrace($bt) {
2287 echo "\nTraceback:\n";
2288 if (function_exists('debug_print_backtrace')) { // >= 5
2289 debug_print_backtrace();
2291 foreach ($bt as $i => $elem) {
2292 if (!array_key_exists('file', $elem)) {
2295 //echo join(" ",array_values($elem)),"\n";
2296 echo " ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2302 * Return the used process memory, in bytes.
2303 * Enable the section which will work for you. They are very slow.
2304 * Special quirks for Windows: Requires cygwin.
2306 function getMemoryUsage() {
2307 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2308 if (function_exists('memory_get_usage') and memory_get_usage()) {
2309 return memory_get_usage();
2310 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2311 $mem = $u['ru_maxrss'];
2312 } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2313 // what we want is the process memory only: apache or php (if CGI)
2316 // win32_ps_stat_proc, win32_ps_stat_mem
2317 if (function_exists('win32_ps_list_procs')) {
2318 $info = win32_ps_stat_proc($pid);
2319 $memstr = $info['mem']['working_set_size'];
2321 // This works only if it's a cygwin process (apache or php).
2322 // Requires a newer cygwin
2323 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2325 // if it's native windows use something like this:
2326 // (requires pslist from sysinternals.com, grep, sed and perl)
2327 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2329 return (integer) trim($memstr);
2332 //%MEM: Percentage of total memory in use by this process
2333 //VSZ: Total virtual memory size, in 1K blocks.
2334 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2335 //CPU time used by process since it started.
2336 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2337 $memstr = exec("ps -orss -p $pid|sed 1d");
2338 return (integer) trim($memstr);
2343 * @param var $needle
2344 * @param array $haystack one-dimensional numeric array only, no hash
2346 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2347 It will return false if not found or the index where it was found.
2348 From dennis.decoene@moveit.be http://www.php.net/array_search
2350 function binary_search($needle, $haystack) {
2351 $high = count($haystack);
2354 while (($high - $low) > 1) {
2355 $probe = floor(($high + $low) / 2);
2356 if ($haystack[$probe] < $needle) {
2358 } elseif ($haystack[$probe] == $needle) {
2359 $high = $low = $probe;
2365 if ($high == count($haystack) || $haystack[$high] != $needle) {
2372 function is_localhost($url = false) {
2374 global $HTTP_SERVER_VARS;
2375 return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2380 * Take a string and quote it sufficiently to be passed as a Javascript
2381 * string between ''s
2383 function javascript_quote_string($s) {
2384 return str_replace("'", "\'", $s);
2387 function isSerialized($s) {
2388 return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2392 * Determine if a variable represents a whole number
2395 function is_whole_number($var) {
2396 return (is_numeric($var) && (intval($var)==floatval($var)));
2400 * Take a string and return an array of pairs (attribute name, attribute value)
2402 * We allow attributes with or without double quotes (")
2403 * Attribute-value pairs may be separated by space or comma
2404 * Space is normal HTML attributes, comma is for RichTable compatibility
2405 * border=1, cellpadding="5"
2406 * border=1 cellpadding="5"
2407 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2408 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2410 function parse_attributes($line) {
2414 if (empty($line)) return $options;
2415 $line = trim($line);
2416 if (empty($line)) return $options;
2417 $line = trim($line, ",");
2418 if (empty($line)) return $options;
2420 // First we have an attribute name.
2425 while (($i < strlen($line)) && ($line[$i] != '=')) {
2428 $attribute = substr($line, 0, $i);
2429 $attribute = strtolower($attribute);
2431 $line = substr($line, $i+1);
2432 $line = trim ($line);
2433 $line = trim ($line, "=");
2434 $line = trim ($line);
2436 if (empty($line)) return $options;
2438 // Then we have the attribute value.
2441 // Attribute value might be between double quotes
2442 // In that case we have to find the closing double quote
2443 if ($line[0] == '"') {
2444 $i++; // skip first '"'
2445 while (($i < strlen($line)) && ($line[$i] != '"')) {
2448 $value = substr($line, 0, $i);
2449 $value = trim ($value, '"');
2450 $value = trim ($value);
2452 // If there are no double quotes, we have to find the next space or comma
2454 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2457 $value = substr($line, 0, $i);
2458 $value = trim ($value);
2459 $value = trim ($value, ",");
2460 $value = trim ($value);
2463 $options[$attribute] = $value;
2465 $line = substr($line, $i+1);
2466 $line = trim ($line);
2467 $line = trim ($line, ",");
2468 $line = trim ($line);
2470 return $options + parse_attributes($line);
2474 * Returns true if the filename ends with an image suffix.
2475 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2477 function is_image ($filename) {
2479 if (defined('INLINE_IMAGES')) {
2480 $inline_images = INLINE_IMAGES;
2482 $inline_images = "png|jpg|jpeg|gif";
2485 foreach (explode("|", $inline_images) as $suffix) {
2486 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2494 * Returns true if the filename ends with an video suffix.
2495 * Currently only FLV and OGG
2497 function is_video ($filename) {
2499 return string_ends_with(strtolower($filename), ".flv")
2500 or string_ends_with(strtolower($filename), ".ogg");
2504 * Remove accents from given text.
2506 function strip_accents($text) {
2507 $res = utf8_decode($text);
2509 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2510 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2511 return utf8_encode($res);
2517 // c-basic-offset: 4
2518 // c-hanging-comment-ender-p: nil
2519 // indent-tabs-mode: nil