/gforge/plugins/wiki/www/lib/stdlib.php
PHP | 2469 lines | 1275 code | 160 blank | 1034 comment | 259 complexity | 957181b75e6a602c7a6739ed0367d3d8 MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception
Large files files are truncated, but you can click here to view the full file
- <?php //rcs_id('$Id: stdlib.php,v 1.251 2006/03/19 15:01:00 rurban Exp $');
- /*
- Copyright 1999,2000,2001,2002,2004,2005 $ThePhpWikiProgrammingTeam
- This file is part of PhpWiki.
- PhpWiki is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- PhpWiki is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with PhpWiki; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
- /*
- Standard functions for Wiki functionality
- WikiURL ($pagename, $args, $get_abs_url)
- AbsoluteURL ($url)
- IconForLink ($protocol_or_url)
- PossiblyGlueIconToText($proto_or_url, $text)
- IsSafeURL($url)
- LinkURL ($url, $linktext)
- LinkImage ($url, $alt)
- SplitQueryArgs ($query_args)
- LinkPhpwikiURL ($url, $text, $basepage)
- ConvertOldMarkup ($content, $markup_type = "block")
- MangleXmlIdentifier($str)
- UnMangleXmlIdentifier($str)
-
- class Stack { push($item), pop(), cnt(), top() }
- class Alert { show() }
- class WikiPageName {getParent(),isValid(),getWarnings() }
- expand_tabs($str, $tab_width = 8)
- SplitPagename ($page)
- NoSuchRevision ($request, $page, $version)
- TimezoneOffset ($time, $no_colon)
- Iso8601DateTime ($time)
- Rfc2822DateTime ($time)
- ParseRfc1123DateTime ($timestr)
- CTime ($time)
- ByteFormatter ($bytes = 0, $longformat = false)
- __printf ($fmt)
- __sprintf ($fmt)
- __vsprintf ($fmt, $args)
- file_mtime ($filename)
- sort_file_mtime ($a, $b)
- class fileSet {fileSet($directory, $filepattern = false),
- getFiles($exclude=false, $sortby=false, $limit=false) }
- class ListRegexExpand { listMatchCallback($item, $key),
- expandRegex ($index, &$pages) }
- glob_to_pcre ($glob)
- glob_match ($glob, $against, $case_sensitive = true)
- explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
- explodePageList ($input, $perm = false)
- isa ($object, $class)
- can ($object, $method)
- function_usable ($function_name)
- wikihash ($x)
- better_srand ($seed = '')
- count_all ($arg)
- isSubPage ($pagename)
- subPageSlice ($pagename, $pos)
- phpwiki_version ()
- isWikiWord ($word)
- obj2hash ($obj, $exclude = false, $fields = false)
- isUtf8String ($s)
- fixTitleEncoding ($s)
- url_get_contents ($uri)
- GenerateId ($name)
- firstNWordsOfContent ($n, $content)
- extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
- isExternalReferrer()
- function: LinkInterWikiLink($link, $linktext)
- moved to: lib/interwiki.php
- function: linkExistingWikiWord($wikiword, $linktext, $version)
- moved to: lib/Theme.php
- function: LinkUnknownWikiWord($wikiword, $linktext)
- moved to: lib/Theme.php
- function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
- gone see: lib/plugin/RecentChanges.php
- */
- if (defined('_PHPWIKI_STDLIB_LOADED')) return;
- else define('_PHPWIKI_STDLIB_LOADED', true);
- define('MAX_PAGENAME_LENGTH', 100);
-
- /**
- * Convert string to a valid XML identifier.
- *
- * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
- *
- * We would like to have, e.g. named anchors within wiki pages
- * names like "Table of Contents" --- clearly not a valid XML
- * fragment identifier.
- *
- * This function implements a one-to-one map from {any string}
- * to {valid XML identifiers}.
- *
- * It does this by
- * converting all bytes not in [A-Za-z0-9:_-],
- * and any leading byte not in [A-Za-z] to 'xbb.',
- * where 'bb' is the hexadecimal representation of the
- * character.
- *
- * As a special case, the empty string is converted to 'empty.'
- *
- * @param string $str
- * @return string
- */
- function MangleXmlIdentifier($str) {
- if (!$str)
- return 'empty.';
-
- return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
- "'x' . sprintf('%02x', ord('\\0')) . '.'",
- $str);
- }
- function UnMangleXmlIdentifier($str) {
- if ($str == 'empty.')
- return '';
- return preg_replace('/x(\w\w)\./e',
- "sprintf('%c', hex('\\0'))",
- $str);
- }
- /**
- * Returns a name for the WIKI_ID cookie that should be unique on the host.
- * But for it to be unique you must have set a unique WIKI_NAME in your
- * configuration file.
- * @return string The name of the WIKI_ID cookie to use for this wiki.
- */
- function GetCookieName() {
- return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
- }
- /**
- * Generates a valid URL for a given Wiki pagename.
- * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
- * If a WikiDB_Page object function will extract the name to link to.
- * If a WikiDB_PageRevision object function will extract the name to link to.
- * @param array $args
- * @param boolean $get_abs_url Default value is false.
- * @return string The absolute URL to the page passed as $pagename.
- */
- function WikiURL($pagename, $args = '', $get_abs_url = false) {
- $anchor = false;
-
- if (is_object($pagename)) {
- if (isa($pagename, 'WikiDB_Page')) {
- $pagename = $pagename->getName();
- }
- elseif (isa($pagename, 'WikiDB_PageRevision')) {
- $page = $pagename->getPage();
- $args['version'] = $pagename->getVersion();
- $pagename = $page->getName();
- }
- elseif (isa($pagename, 'WikiPageName')) {
- $anchor = $pagename->anchor;
- $pagename = $pagename->name;
- } else { // php5
- $anchor = $pagename->anchor;
- $pagename = $pagename->name;
- }
- }
- if (!$get_abs_url and DEBUG and $GLOBALS['request']->getArg('start_debug')) {
- if (!$args)
- $args = 'start_debug=' . $GLOBALS['request']->getArg('start_debug');
- elseif (is_array($args))
- $args['start_debug'] = $GLOBALS['request']->getArg('start_debug');
- else
- $args .= '&start_debug=' . $GLOBALS['request']->getArg('start_debug');
- }
- if (is_array($args)) {
- $enc_args = array();
- foreach ($args as $key => $val) {
- // avoid default args
- if (USE_PATH_INFO and $key == 'pagename')
- ;
- elseif ($key == 'action' and $val == 'browse')
- ;
- elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
- $enc_args[] = urlencode($key) . '=' . urlencode($val);
- }
- $args = join('&', $enc_args);
- }
- if (USE_PATH_INFO or !empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX)) {
- $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
- $url = $url . preg_replace('/%2f/i', '/', rawurlencode($pagename));
- if (!empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX))
- $url .= $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
- if ($args)
- $url .= "?$args";
- }
- else {
- $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
- $url .= "?pagename=" . rawurlencode($pagename);
- if ($args)
- $url .= "&$args";
- }
- if ($anchor)
- $url .= "#" . MangleXmlIdentifier($anchor);
- return $url;
- }
- /** Convert relative URL to absolute URL.
- *
- * This converts a relative URL to one of PhpWiki's support files
- * to an absolute one.
- *
- * @param string $url
- * @return string Absolute URL
- */
- function AbsoluteURL ($url) {
- if (preg_match('/^https?:/', $url))
- return $url;
- if ($url[0] != '/') {
- $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
- while ($base != '/' and substr($url, 0, 3) == "../") {
- $url = substr($url, 3);
- $base = dirname($base);
- }
- if ($base != '/')
- $base .= '/';
- $url = $base . $url;
- }
- return SERVER_URL . $url;
- }
- function DataURL ($url) {
- if (preg_match('/^https?:/', $url))
- return $url;
- $url = NormalizeWebFileName($url);
- if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
- $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
- return AbsoluteURL($url);
- }
- /**
- * Generates icon in front of links.
- *
- * @param string $protocol_or_url URL or protocol to determine which icon to use.
- *
- * @return HtmlElement HtmlElement object that contains data to create img link to
- * icon for use with url or protocol passed to the function. False if no img to be
- * displayed.
- */
- function IconForLink($protocol_or_url) {
- global $WikiTheme;
- if (0 and $filename_suffix == false) {
- // display apache style icon for file type instead of protocol icon
- // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
- // - document: html, htm, text, txt, rtf, pdf, doc
- // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
- // - audio: mp3,mp2,aiff,aif,au
- // - multimedia: mpeg,mpg,mov,qt
- } else {
- list ($proto) = explode(':', $protocol_or_url, 2);
- $src = $WikiTheme->getLinkIconURL($proto);
- if ($src)
- return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
- else
- return false;
- }
- }
- /**
- * Glue icon in front of or after text.
- * Pref: 'noLinkIcons' - ignore icon if set
- * Theme: 'LinkIcons' - 'yes' at front
- * - 'no' display no icon
- * - 'front' display at left
- * - 'after' display at right
- *
- * @param string $protocol_or_url Protocol or URL. Used to determine the
- * proper icon.
- * @param string $text The text.
- * @return XmlContent.
- */
- function PossiblyGlueIconToText($proto_or_url, $text) {
- global $request, $WikiTheme;
- if ($request->getPref('noLinkIcons'))
- return $text;
- $icon = IconForLink($proto_or_url);
- if (!$icon)
- return $text;
- if ($where = $WikiTheme->getLinkIconAttr()) {
- if ($where == 'no') return $text;
- if ($where != 'after') $where = 'front';
- } else {
- $where = 'front';
- }
- if ($where == 'after') {
- // span the icon only to the last word (tie them together),
- // to let the previous words wrap on line breaks.
- if (!is_object($text)) {
- preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
- list (, $prefix, $last_word) = $m;
- }
- else {
- $last_word = $text;
- $prefix = false;
- }
- $text = HTML::span(array('style' => 'white-space: nowrap'),
- $last_word, HTML::Raw(' '), $icon);
- if ($prefix)
- $text = HTML($prefix, $text);
- return $text;
- }
- // span the icon only to the first word (tie them together),
- // to let the next words wrap on line breaks
- if (!is_object($text)) {
- preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
- list (, $first_word, $tail) = $m;
- }
- else {
- $first_word = $text;
- $tail = false;
- }
- $text = HTML::span(array('style' => 'white-space: nowrap'),
- $icon, $first_word);
- if ($tail)
- $text = HTML($text, $tail);
- return $text;
- }
- /**
- * Determines if the url passed to function is safe, by detecting if the characters
- * '<', '>', or '"' are present.
- * Check against their urlencoded values also.
- *
- * @param string $url URL to check for unsafe characters.
- * @return boolean True if same, false else.
- */
- function IsSafeURL($url) {
- return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
- }
- /**
- * Generates an HtmlElement object to store data for a link.
- *
- * @param string $url URL that the link will point to.
- * @param string $linktext Text to be displayed as link.
- * @return HtmlElement HtmlElement object that contains data to construct an html link.
- */
- function LinkURL($url, $linktext = '') {
- // FIXME: Is this needed (or sufficient?)
- if(! IsSafeURL($url)) {
- $link = HTML::strong(HTML::u(array('class' => 'baduri'),
- _("BAD URL -- remove all of <, >, \"")));
- }
- else {
- if (!$linktext)
- $linktext = preg_replace("/mailto:/A", "", $url);
- $args = array('href' => $url);
- if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
- $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
- $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
- }
- $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
- return $link;
- }
- /**
- * Inline Images
- *
- * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
- * Disallows sizes which are too small.
- * Spammers may use such (typically invisible) image attributes to higher their GoogleRank.
- *
- * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
- */
- function LinkImage($url, $alt = false) {
- $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
- // Disallow tags in img src urls. Typical CSS attacks.
- // FIXME: Is this needed (or sufficient?)
- if(! IsSafeURL($url)) {
- $link = HTML::strong(HTML::u(array('class' => 'baduri'),
- _("BAD URL -- remove all of <, >, \"")));
- } else {
- // support new syntax: [image.jpg size=50% border=n]
- if (!preg_match("/\.(".$force_img.")/i", $url))
- $ori_url = $url;
- $arr = split(' ',$url);
- if (count($arr) > 1) {
- $url = $arr[0];
- }
- if (empty($alt)) $alt = basename($url);
- $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
- if (count($arr) > 1) {
- array_shift($arr);
- foreach ($arr as $attr) {
- if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
- $link->setAttr('width',$m[1]);
- $link->setAttr('height',$m[1]);
- }
- if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
- $link->setAttr('width',$m[1]);
- $link->setAttr('height',$m[2]);
- }
- if (preg_match('/^border=(\d+)$/',$attr,$m))
- $link->setAttr('border',$m[1]);
- if (preg_match('/^align=(\w+)$/',$attr,$m))
- $link->setAttr('align',$m[1]);
- if (preg_match('/^hspace=(\d+)$/',$attr,$m))
- $link->setAttr('hspace',$m[1]);
- if (preg_match('/^vspace=(\d+)$/',$attr,$m))
- $link->setAttr('vspace',$m[1]);
- }
- }
- // Check width and height as spam countermeasure
- if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
- //$width = (int) $width; // px or % or other suffix
- //$height = (int) $height;
- if (($width < 3 and $height < 10) or
- ($height < 3 and $width < 20) or
- ($height < 7 and $width < 7))
- {
- trigger_error(_("Invalid image size"), E_USER_WARNING);
- return '';
- }
- } else {
- // Older php versions crash here with certain png's:
- // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
- // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
- // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
- if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
- ; // it's safe to assume that this will fail.
- elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
- $width = $size[0];
- $height = $size[1];
- if (($width < 3 and $height < 10)
- or ($height < 3 and $width < 20)
- or ($height < 7 and $width < 7))
- {
- trigger_error(_("Invalid image size"), E_USER_WARNING);
- return '';
- }
- }
- }
- }
- $link->setAttr('class', 'inlineimage');
- /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
- * png|jpg|gif|jpeg|bmp|pl|cgi
- * Note: Allow cgi's (pl,cgi) returning images.
- */
- if (!preg_match("/\.(".$force_img.")/i", $url)) {
- //HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
- // => HTML::object(array('src' => $url)) ...;
- return ImgObject($link, $ori_url);
- }
- return $link;
- }
- /**
- * <object> / <embed> tags instead of <img> for all non-image extensions allowed via INLINE_IMAGES
- * Called by LinkImage(), not directly.
- * Syntax: [image.svg size=50% border=n align= hspace= vspace= width= height=]
- * $alt may be an alternate img
- * TODO: Need to unify with WikiPluginCached::embedObject()
- *
- * Note that Safari 1.0 will crash with <object>, so use only <embed>
- * http://www.alleged.org.uk/pdc/2002/svg-object.html
- */
- function ImgObject($img, $url) {
- // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
- $args = split(' ', $url);
- if (count($args) >= 1) {
- $url = array_shift($args);
- foreach ($args as $attr) {
- if (preg_match('/^type=(\S+)$/',$attr,$m))
- $img->setAttr('type', $m[1]);
- if (preg_match('/^data=(\S+)$/',$attr,$m))
- $img->setAttr('data', $m[1]);
- }
- }
- $type = $img->getAttr('type');
- if (!$type) {
- // TODO: map extension to mime-types if type is not given and php < 4.3
- if (function_exists('mime_content_type'))
- $type = mime_content_type($url);
- }
- $link = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)));
- $link->setAttr('class', 'inlineobject');
- if (isBrowserSafari()) {
- return HTML::embed($link->_attr);
- }
- $link->pushContent(HTML::embed($link->_attr));
- return $link;
- }
- class Stack {
- // var in php5 deprecated
- function Stack() {
- $this->items = array();
- $this->size = 0;
- }
- function push($item) {
- $this->items[$this->size] = $item;
- $this->size++;
- return true;
- }
-
- function pop() {
- if ($this->size == 0) {
- return false; // stack is empty
- }
- $this->size--;
- return $this->items[$this->size];
- }
-
- function cnt() {
- return $this->size;
- }
-
- function top() {
- if($this->size)
- return $this->items[$this->size - 1];
- else
- return '';
- }
-
- }
- // end class definition
- function SplitQueryArgs ($query_args = '')
- {
- // FIXME: use the arg-seperator which might not be &
- $split_args = split('&', $query_args);
- $args = array();
- while (list($key, $val) = each($split_args))
- if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
- $args[$m[1]] = $m[2];
- return $args;
- }
- function LinkPhpwikiURL($url, $text = '', $basepage = false) {
- $args = array();
-
- if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
- return HTML::strong(array('class' => 'rawurl'),
- HTML::u(array('class' => 'baduri'),
- _("BAD phpwiki: URL")));
- }
- if ($m[1])
- $pagename = urldecode($m[1]);
- $qargs = $m[2];
-
- if (empty($pagename) &&
- preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
- // Convert old style links (to not break diff links in
- // RecentChanges).
- $pagename = urldecode($m[2]);
- $args = array("action" => $m[1]);
- }
- else {
- $args = SplitQueryArgs($qargs);
- }
- if (empty($pagename))
- $pagename = $GLOBALS['request']->getArg('pagename');
- if (isset($args['action']) && $args['action'] == 'browse')
- unset($args['action']);
-
- /*FIXME:
- if (empty($args['action']))
- $class = 'wikilink';
- else if (is_safe_action($args['action']))
- $class = 'wikiaction';
- */
- if (empty($args['action']) || is_safe_action($args['action']))
- $class = 'wikiaction';
- else {
- // Don't allow administrative links on unlocked pages.
- $dbi = $GLOBALS['request']->getDbh();
- $page = $dbi->getPage($basepage ? $basepage : $pagename);
- if (!$page->get('locked'))
- return HTML::span(array('class' => 'wikiunsafe'),
- HTML::u(_("Lock page to enable link")));
- $class = 'wikiadmin';
- }
-
- if (!$text)
- $text = HTML::span(array('class' => 'rawurl'), $url);
- $wikipage = new WikiPageName($pagename);
- if (!$wikipage->isValid()) {
- global $WikiTheme;
- return $WikiTheme->linkBadWikiWord($wikipage, $url);
- }
-
- return HTML::a(array('href' => WikiURL($pagename, $args),
- 'class' => $class),
- $text);
- }
- /**
- * A class to assist in parsing wiki pagenames.
- *
- * Now with subpages and anchors, parsing and passing around
- * pagenames is more complicated. This should help.
- */
- class WikiPageName
- {
- /** Short name for page.
- *
- * This is the value of $name passed to the constructor.
- * (For use, e.g. as a default label for links to the page.)
- */
- //var $shortName;
- /** The full page name.
- *
- * This is the full name of the page (without anchor).
- */
- //var $name;
-
- /** The anchor.
- *
- * This is the referenced anchor within the page, or the empty string.
- */
- //var $anchor;
-
- /** Constructor
- *
- * @param mixed $name Page name.
- * WikiDB_Page, WikiDB_PageRevision, or string.
- * This can be a relative subpage name (like '/SubPage'),
- * or can be the empty string to refer to the $basename.
- *
- * @param string $anchor For links to anchors in page.
- *
- * @param mixed $basename Page name from which to interpret
- * relative or other non-fully-specified page names.
- */
- function WikiPageName($name, $basename=false, $anchor=false) {
- if (is_string($name)) {
- $this->shortName = $name;
- if (strstr($name, ':')) {
- list($moniker, $this->shortName) = split (":", $name, 2);
- $map = getInterwikiMap(); // allow overrides to custom maps
- if (isset($map->_map[$moniker])) {
- $url = $map->_map[$moniker];
- if (strstr($url, '%s'))
- $url = sprintf($url, $this->shortName);
- else
- $url .= $this->shortName;
- // expand Talk or User, but not to absolute urls!
- if (strstr($url, '//')) {
- if ($moniker == 'Talk')
- $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
- elseif ($moniker == 'User')
- $name = $name;
- } else {
- $name = $url;
- }
- if (strstr($name, '?'))
- list($name, $dummy) = split("?", $name, 2);
- }
- }
- // FIXME: We should really fix the cause for "/PageName" in the WikiDB
- if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
- if ($basename)
- $name = $this->_pagename($basename) . $name;
- else {
- $name = $this->_normalize_bad_pagename($name);
- $this->shortName = $name;
- }
- }
- }
- else {
- $name = $this->_pagename($name);
- $this->shortName = $name;
- }
- $this->name = $this->_check($name);
- $this->anchor = (string)$anchor;
- }
- function getName() {
- return $this->name;
- }
-
- function getParent() {
- $name = $this->name;
- if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
- return false;
- return substr($name, 0, -strlen($tail));
- }
- function isValid($strict = false) {
- if ($strict)
- return !isset($this->_errors);
- return (is_string($this->name) and $this->name != '');
- }
- function getWarnings() {
- $warnings = array();
- if (isset($this->_warnings))
- $warnings = array_merge($warnings, $this->_warnings);
- if (isset($this->_errors))
- $warnings = array_merge($warnings, $this->_errors);
- if (!$warnings)
- return false;
-
- return sprintf(_("'%s': Bad page name: %s"),
- $this->shortName, join(', ', $warnings));
- }
-
- function _pagename($page) {
- if (isa($page, 'WikiDB_Page'))
- return $page->getName();
- elseif (isa($page, 'WikiDB_PageRevision'))
- return $page->getPageName();
- elseif (isa($page, 'WikiPageName'))
- return $page->name;
- // '0' or e.g. '1984' should be allowed though
- if (!is_string($page) and !is_integer($page)) {
- trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
- $page, gettype($page), get_class($page)),
- E_USER_NOTICE);
- }
- //assert(is_string($page));
- return $page;
- }
- function _normalize_bad_pagename($name) {
- trigger_error("Bad pagename: " . $name, E_USER_WARNING);
- // Punt... You really shouldn't get here.
- if (empty($name)) {
- global $request;
- return $request->getArg('pagename');
- }
- assert($name[0] == SUBPAGE_SEPARATOR);
- $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
- return substr($name, 1);
- }
- function _check($pagename) {
- // Compress internal white-space to single space character.
- $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
- if ($pagename != $orig)
- $this->_warnings[] = _("White space converted to single space");
-
- // Delete any control characters.
- if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file') {
- $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
- if ($pagename != $orig)
- $this->_errors[] = _("Control characters not allowed");
- }
- // Strip leading and trailing white-space.
- $pagename = trim($pagename);
- $orig = $pagename;
- while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
- $pagename = substr($pagename, 1);
- if ($pagename != $orig)
- $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
- // ";" is urlencoded, so safe from php arg-delim problems
- /*if (strstr($pagename, ';')) {
- $this->_warnings[] = _("';' is deprecated");
- $pagename = str_replace(';', '', $pagename);
- }*/
-
- // not only for SQL, also to restrict url length
- if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
- $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
- $this->_errors[] = _("too long");
- }
- // disallow some chars only on file and cvs
- if ((DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file')
- and preg_match('/(:|\.\.)/', $pagename, $m)) {
- $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
- $pagename = str_replace('..', '', $pagename);
- $pagename = str_replace(':', '', $pagename);
- }
-
- return $pagename;
- }
- }
- /**
- * Convert old page markup to new-style markup.
- *
- * @param string $text Old-style wiki markup.
- *
- * @param string $markup_type
- * One of: <dl>
- * <dt><code>"block"</code> <dd>Convert all markup.
- * <dt><code>"inline"</code> <dd>Convert only inline markup.
- * <dt><code>"links"</code> <dd>Convert only link markup.
- * </dl>
- *
- * @return string New-style wiki markup.
- *
- * @bugs Footnotes don't work quite as before (esp if there are
- * multiple references to the same footnote. But close enough,
- * probably for now....
- * @bugs Apache2 and IIS crash with OldTextFormattingRules or
- * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
- * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
- * also known to crash, even with Apache1.
- */
- function ConvertOldMarkup ($text, $markup_type = "block") {
- static $subs;
- static $block_re;
-
- // FIXME:
- // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
- // AnciennesR%E8glesDeFormatage crashes.
- // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
- // also known to crash, even with Apache1.
- $debug_skip = false;
- // I suspect this only to crash with Apache2 and IIS.
- if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
- and preg_match("/plugin CreateToc/", $text))
- {
- trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
- ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
- ._("Skipped."), E_USER_WARNING);
- $debug_skip = true;
- //if (!DEBUG) return $text;
- return $text;
- }
- if (empty($subs)) {
- /*****************************************************************
- * Conversions for inline markup:
- */
- // escape tilde's
- $orig[] = '/~/';
- $repl[] = '~~';
- // escape escaped brackets
- $orig[] = '/\[\[/';
- $repl[] = '~[';
- // change ! escapes to ~'s.
- global $WikiNameRegexp, $request;
- $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
- // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
- if (check_php_version(4,3,9)) {
- $map = getInterwikiMap();
- if ($map_regex = $map->getRegexp())
- $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
- }
- $bang_esc[] = $WikiNameRegexp;
- $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
- $repl[] = '~\\1';
- $subs["links"] = array($orig, $repl);
- // Temporarily URL-encode pairs of underscores in links to hide
- // them from the re for bold markup.
- $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
- $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
- // Escape '<'s
- //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
- //$repl[] = '~<';
-
- // Convert footnote references.
- $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
- $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
- // Convert old style emphases to HTML style emphasis.
- $orig[] = '/__(.*?)__/';
- $repl[] = '<strong>\\1</strong>';
- $orig[] = "/''(.*?)''/";
- $repl[] = '<em>\\1</em>';
- // Escape nestled markup.
- $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
- $repl[] = '~\\0';
-
- // in old markup headings only allowed at beginning of line
- $orig[] = '/!/';
- $repl[] = '~!';
- // Convert URL-encoded pairs of underscores in links back to
- // real underscores after bold markup has been converted.
- $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
- $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
- $subs["inline"] = array($orig, $repl);
- /*****************************************************************
- * Patterns which match block markup constructs which take
- * special handling...
- */
- // Indented blocks
- $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
- // Tables
- $blockpats[] = '\|(?:.*\n\|)*';
- // List items
- $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
- // Footnote definitions
- $blockpats[] = '\[\s*(\d+)\s*\]';
- if (!$debug_skip) {
- // Plugins
- $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
- }
- // Section Title
- $blockpats[] = '!{1,3}[^!]';
- /*
- removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
- this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
- */
- $block_re = ( '/\A((?:.|\n)*?)(^(?:'
- . join("|", $blockpats)
- . ').*$)\n?/m' );
-
- }
-
- if ($markup_type != "block") {
- list ($orig, $repl) = $subs[$markup_type];
- return preg_replace($orig, $repl, $text);
- }
- else {
- list ($orig, $repl) = $subs['inline'];
- $out = '';
- //FIXME:
- // php crashes here in the 2nd paragraph of OldTextFormattingRules,
- // AnciennesR%E8glesDeFormatage and more
- // See http://www.pcre.org/pcre.txt LIMITATIONS
- while (preg_match($block_re, $text, $m)) {
- $text = substr($text, strlen($m[0]));
- list (,$leading_text, $block) = $m;
- $suffix = "\n";
-
- if (strchr(" \t", $block[0])) {
- // Indented block
- $prefix = "<pre>\n";
- $suffix = "\n</pre>\n";
- }
- elseif ($block[0] == '|') {
- // Old-style table
- $prefix = "<?plugin OldStyleTable\n";
- $suffix = "\n?>\n";
- }
- elseif (strchr("#*;", $block[0])) {
- // Old-style list item
- preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
- list (,$ind,$bullet) = $m;
- $block = substr($block, strlen($m[0]));
-
- $indent = str_repeat(' ', strlen($ind));
- if ($bullet[0] == ';') {
- //$term = ltrim(substr($bullet, 1));
- //return $indent . $term . "\n" . $indent . ' ';
- $prefix = $ind . $bullet;
- }
- else
- $prefix = $indent . $bullet . ' ';
- }
- elseif ($block[0] == '[') {
- // Footnote definition
- preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
- $footnum = $m[1];
- $block = substr($block, strlen($m[0]));
- $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
- }
- elseif ($block[0] == '<') {
- // Plugin.
- // HACK: no inline markup...
- $prefix = $block;
- $block = '';
- }
- elseif ($block[0] == '!') {
- // Section heading
- preg_match('/^!{1,3}/', $block, $m);
- $prefix = $m[0];
- $block = substr($block, strlen($m[0]));
- }
- else {
- // AAck!
- assert(0);
- }
- if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
- if ($block) $block = preg_replace($orig, $repl, $block);
- $out .= $leading_text;
- $out .= $prefix;
- $out .= $block;
- $out .= $suffix;
- }
- return $out . preg_replace($orig, $repl, $text);
- }
- }
- /**
- * Expand tabs in string.
- *
- * Converts all tabs to (the appropriate number of) spaces.
- *
- * @param string $str
- * @param integer $tab_width
- * @return string
- */
- function expand_tabs($str, $tab_width = 8) {
- $split = split("\t", $str);
- $tail = array_pop($split);
- $expanded = "\n";
- foreach ($split as $hunk) {
- $expanded .= $hunk;
- $pos = strlen(strrchr($expanded, "\n")) - 1;
- $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
- }
- return substr($expanded, 1) . $tail;
- }
- /**
- * Split WikiWords in page names.
- *
- * It has been deemed useful to split WikiWords (into "Wiki Words") in
- * places like page titles. This is rumored to help search engines
- * quite a bit.
- *
- * @param $page string The page name.
- *
- * @return string The split name.
- */
- function SplitPagename ($page) {
-
- if (preg_match("/\s/", $page))
- return $page; // Already split --- don't split any more.
-
- // This algorithm is specialized for several languages.
- // (Thanks to Pierrick MEIGNEN)
- // Improvements for other languages welcome.
- static $RE;
- if (!isset($RE)) {
- // This mess splits between a lower-case letter followed by
- // either an upper-case or a numeral; except that it wont
- // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
- switch ($GLOBALS['LANG']) {
- case 'en':
- case 'it':
- case 'es':
- case 'de':
- $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
- break;
- case 'fr':
- $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
- break;
- }
- $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
- // This the single-letter words 'I' and 'A' from any following
- // capitalized words.
- switch ($GLOBALS['LANG']) {
- case 'en':
- $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
- break;
- case 'fr':
- $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
- break;
- }
- // Split numerals from following letters.
- $RE[] = '/(\d)([[:alpha:]])/';
- // Split at subpage seperators. TBD in Theme.php
- $RE[] = "/([^${sep}]+)(${sep})/";
-
- foreach ($RE as $key)
- $RE[$key] = pcre_fix_posix_classes($key);
- }
- foreach ($RE as $regexp) {
- $page = preg_replace($regexp, '\\1 \\2', $page);
- }
- return $page;
- }
- function NoSuchRevision (&$request, $page, $version) {
- $html = HTML(HTML::h2(_("Revision Not Found")),
- HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
- $version, WikiLink($page, 'auto'))));
- include_once('lib/Template.php');
- GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
- $request->finish();
- }
- /**
- * Get time offset for local time zone.
- *
- * @param $time time_t Get offset for this time. Default: now.
- * @param $no_colon boolean Don't put colon between hours and minutes.
- * @return string Offset as a string in the format +HH:MM.
- */
- function TimezoneOffset ($time = false, $no_colon = false) {
- if ($time === false)
- $time = time();
- $secs = date('Z', $time);
- if ($secs < 0) {
- $sign = '-';
- $secs = -$secs;
- }
- else {
- $sign = '+';
- }
- $colon = $no_colon ? '' : ':';
- $mins = intval(($secs + 30) / 60);
- return sprintf("%s%02d%s%02d",
- $sign, $mins / 60, $colon, $mins % 60);
- }
- /**
- * Format time in ISO-8601 format.
- *
- * @param $time time_t Time. Default: now.
- * @return string Date and time in ISO-8601 format.
- */
- function Iso8601DateTime ($time = false) {
- if ($time === false)
- $time = time();
- $tzoff = TimezoneOffset($time);
- $date = date('Y-m-d', $time);
- $time = date('H:i:s', $time);
- return $date . 'T' . $time . $tzoff;
- }
- /**
- * Format time in RFC-2822 format.
- *
- * @param $time time_t Time. Default: now.
- * @return string Date and time in RFC-2822 format.
- */
- function Rfc2822DateTime ($time = false) {
- if ($time === false)
- $time = time();
- return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
- }
- /**
- * Format time in RFC-1123 format.
- *
- * @param $time time_t Time. Default: now.
- * @return string Date and time in RFC-1123 format.
- */
- function Rfc1123DateTime ($time = false) {
- if ($time === false)
- $time = time();
- return gmdate('D, d M Y H:i:s \G\M\T', $time);
- }
- /** Parse date in RFC-1123 format.
- *
- * According to RFC 1123 we must accept dates in the following
- * formats:
- *
- * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
- * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
- * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
- *
- * (Though we're only allowed to generate dates in the first format.)
- */
- function ParseRfc1123DateTime ($timestr) {
- $timestr = trim($timestr);
- if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
- .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
- $timestr, $m)) {
- list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
- }
- elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
- .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
- $timestr, $m)) {
- list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
- if ($year < 70) $year += 2000;
- elseif ($year < 100) $year += 1900;
- }
- elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
- .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
- $timestr, $m)) {
- list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
- }
- else {
- // Parse failed.
- return false;
- }
- $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
- if ($time == -1)
- return false; // failed
- return $time;
- }
- /**
- * Format time to standard 'ctime' format.
- *
- * @param $time time_t Time. Default: now.
- * @return string Date and time.
- */
- function CTime ($time = false)
- {
- if ($time === false)
- $time = time();
- return date("D M j H:i:s Y", $time);
- }
- /**
- * Format number as kilobytes or bytes.
- * Short format is used for PageList
- * Long format is used in PageInfo
- *
- * @param $bytes int. Default: 0.
- * @param $longformat bool. Default: false.
- * @return class FormattedText (XmlElement.php).
- */
- function ByteFormatter ($bytes = 0, $longformat = false) {
- if ($bytes < 0)
- return fmt("-???");
- if ($bytes < 1024) {
- if (! $longformat)
- $size = fmt("%s b", $bytes);
- else
- $size = fmt("%s bytes", $bytes);
- }
- else {
- $kb = round($bytes / 1024, 1);
- if (! $longformat)
- $size = fmt("%s k", $kb);
- else
- $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
- }
- return $size;
- }
- /**
- * Internationalized printf.
- *
- * This is essentially the same as PHP's built-in printf
- * with the following exceptions:
- * <ol>
- * <li> It passes the format string through gettext().
- * <li> It supports the argument reordering extensions.
- * </ol>
- *
- * Example:
- *
- * In php code, use:
- * <pre>
- * __printf("Differences between versions %s and %s of %s",
- * $new_link, $old_link, $page_link);
- * </pre>
- *
- * Then in locale/po/de.po, one can reorder the printf arguments:
- *
- * <pre>
- * msgid "Differences between %s and %s of %s."
- * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
- * </pre>
- *
- * (Note that while PHP tries to expand $vars within double-quotes,
- * the values in msgstr undergo no such expansion, so the '$'s
- * okay...)
- *
- * One shouldn't use reordered arguments in the default format string.
- * Backslashes in the default string would be necessary to escape the
- * '$'s, and they'll cause all kinds of trouble....
- */
- function __printf ($fmt) {
- $args = func_get_args();
- array_shift($args);
- echo __vsprintf($fmt, $args);
- }
- /**
- * Internationalized sprintf.
- *
- * This is essentially the same as PHP's built-in printf with the
- * following exceptions:
- *
- * <ol>
- * <li> It passes the format string through gettext().
- * <li> It supports the argument reordering extensions.
- * </ol>
- *
- * @see __printf
- */
- function __sprintf ($fmt) {
- $args = func_get_args();
- array_shift($args);
- return __vsprintf($fmt, $args);
- }
- /**
- * Internationalized vsprintf.
- *
- * This is essentially the same as PHP's built-in printf with the
- * following exceptions:
- *
- * <ol>
- * <li> It passes the format string through gettext().
- * <li> It supports the argument reordering extensions.
- * </ol>
- *
- * @see __printf
- */
- function __vsprintf ($fmt, $args) {
- $fmt = gettext($fmt);
- // PHP's sprintf doesn't support variable with specifiers,
- // like sprintf("%*s", 10, "x"); --- so we won't either.
-
- if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
- // Format string has '%2$s' style argument reordering.
- // PHP doesn't support this.
- if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
- // literal variable name substitution only to keep locale
- // strings uncluttered
- trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
- '%1\$s','%s'), E_USER_WARNING); //php+locale error
-
- $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
- $newargs = array();
-
- // Reorder arguments appropriately.
- foreach($m[1] as $argnum) {
- if ($argnum < 1 || $argnum > count($args))
- trigger_error(sprintf(_("%s: argument index out of range"),
- $argnum), E_USER_WARNING);
- $newargs[] = $args[$argnum - 1];
- }
- $args = $newargs;
- }
-
- // Not all PHP's have vsprintf, so...
- array_unshift($args, $fmt);
- return call_user_func_array('sprintf', $args);
- }
- function file_mtime ($filename) {
- if ($stat = @stat($filename))
- return $stat[9];
- else
- return false;
- }
- function sort_file_mtime ($a, $b) {
- $ma = file_mtime($a);
- $mb = file_mtime($b);
- if (!$ma or !$mb or $ma == $mb) return 0;
- return ($ma > $mb) ? -1 : 1;
- }
- class fileSet {
- /**
- * Build an array in $this->_fileList of files from $dirname.
- * Subdirectories are not traversed.
- *
- * (This was a function LoadDir in lib/loadsave.php)
- * See also http://www.php.net/manual/en/function.readdir.php
- */
- function getFiles($exclude=false, $sortby=false, $limit=false) {
- $list = $this->_fileList;
- if ($sortby) {
- require_once('lib/PageList.php');
- switch (Pagelist::sortby($sortby, 'db')) {
- case 'pagename ASC': break;
- case 'pagename DESC':
- $list = array_reverse($list);
- break;
- case 'mtime ASC':
- usort($list,'sort_file_mtime');
- break;
- case 'mtime DESC':
- usort($list,'sort_file_mtime');
- $list = array_reverse($list);
- break;
- }
- }
- if ($limit)
- return array_splice($list, 0, $limit);
- return $list;
- }
- function _filenameSelector($filename) {
- if (! $this->_pattern )
- return true;
- else {
- if (! $this->_pcre_pattern )
- $this->_pcre_pattern = glob_to_pcre($this->_pattern);
- return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
- $filename);
- }
- }
- function fileSet($directory, $filepattern = false) {
- $this->_fileList = array();
- $this->_pattern = $filepattern;
- if ($filepattern)
- $this->_pcre_pattern = glob_to_pcre($this->_pattern);
- $this->_case = !isWindows();
- $this->_pathsep = '/';
- if (empty($directory)) {
- trigger_error(sprintf(_("%s is empty."), 'directoryname'),
- E_USER_NOTICE);
- return; // early return
- }
- @ $dir_handle = opendir($dir=$directory);
- if (empty($dir_handle)) {
- trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
- $dir), E_USER_NOTICE);
- return; // early return
- }
- while ($filename = readdir($dir_handle)) {
- if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
- continue;
- if ($this->_filenameSelector($filename)) {
- array_push($this->_fileList, "$filename");
- //trigger_error(sprintf(_("found file %s"), $filename),
- // E_USER_NOTICE); //debugging
- }
- }
- closedir($dir_handle);
- }
- };
- // File globbing
- // expands a list containing regex's to its matching entries
- class ListRegexExpand {
- //var $match, $list, $index, $case_sensitive;
- function ListRegexExpand (&$list, $match, $case_sensitive = true) {
- $this->match = $match;
- $this->list = &$list;
- $this->case_sensitive = $case_sensitive;
- //$this->index = false;
- }
- function listMatchCallback ($item, $key) {
- $quoted = str_replace('/','\/',$item);
- if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
- $quoted)) {
- unset($this->list[$this->index]);
- $this->list[] = $item;
- }
- }
- function expandRegex ($index, &$pages) {
- $this->index = $index;
- array_walk($pages, array($this, 'listMatchCallback'));
- return $this->list;
- }
- }
- // Convert fileglob to regex style:
- // Convert some wildcards to pcre style, escape the rest
- // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
- // Fixed bug #994994: "/" in $glob.
- function glob_to_pcre ($glob) {
- // check simple case: no need to escape
- $escape = '\[](){}=!<>|:/';
- if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
- r…
Large files files are truncated, but you can click here to view the full file