$/u', $match)) {
break 2;
} else {
$open = true;
}
}
if ($open) {
break;
}
return $param;
}
} while (false);
// Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
return strip_tags($param);
case self::PARAM_COMPONENT:
// We do not want any guessing here, either the name is correct or not
// please note only normalised component names are accepted.
if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
return '';
}
if (strpos($param, '__') !== false) {
return '';
}
if (strpos($param, 'mod_') === 0) {
// Module names must not contain underscores because we need to differentiate them from invalid plugin types.
if (substr_count($param, '_') != 1) {
return '';
}
}
return $param;
case self::PARAM_SAFEDIR:
// Remove everything not a-zA-Z0-9_- .
return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
case self::PARAM_SAFEPATH:
// Remove everything not a-zA-Z0-9/_- .
return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
case self::PARAM_FILE:
// Strip all suspicious characters from filename.
$param = fix_utf8($param);
$param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
if ($param === '.' || $param === '..') {
$param = '';
}
return $param;
case self::PARAM_PATH:
// Strip all suspicious characters from file path.
$param = fix_utf8($param);
$param = str_replace('\\', '/', $param);
// Explode the path and clean each element using the PARAM_FILE rules.
$breadcrumb = explode('/', $param);
foreach ($breadcrumb as $key => $crumb) {
if ($crumb === '.' && $key === 0) {
// Special condition to allow for relative current path such as ./currentdirfile.txt.
} else {
$crumb = clean_param($crumb, PARAM_FILE);
}
$breadcrumb[$key] = $crumb;
}
$param = implode('/', $breadcrumb);
// Remove multiple current path (./././) and multiple slashes (///).
$param = preg_replace('~//+~', '/', $param);
$param = preg_replace('~/(\./)+~', '/', $param);
return $param;
case self::PARAM_HOST:
// Allow FQDN or IPv4 dotted quad.
$param = preg_replace('/[^\.\d\w-]/', '', $param );
// Match ipv4 dotted quad.
if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
// Confirm values are ok.
if ( $match[0] > 255
|| $match[1] > 255
|| $match[3] > 255
|| $match[4] > 255 ) {
// Hmmm, what kind of dotted quad is this?
$param = '';
}
} else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
&& !preg_match('/^[\.-]/',$param) // No leading dots/hyphens.
&& !preg_match('/[\.-]$/',$param) // No trailing dots/hyphens.
) {
// All is ok - $param is respected.
} else {
// All is not ok...
$param='';
}
return $param;
case self::PARAM_URL: // Allow safe ftp, http, mailto urls.
$param = fix_utf8($param);
if (!empty($param) && self::validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
// All is ok, param is respected.
} else {
// Not really ok.
$param ='';
}
return $param;
case self::PARAM_PEM:
$param = trim($param);
// PEM formatted strings may contain letters/numbers and the symbols:
// forward slash: /
// plus sign: +
// equal sign: =
// , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
list($wholething, $body) = $matches;
unset($wholething, $matches);
$b64 = clean_param($body, PARAM_BASE64);
if (!empty($b64)) {
return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
} else {
return '';
}
}
return '';
case self::PARAM_BASE64:
if (!empty($param)) {
// PEM formatted strings may contain letters/numbers and the symbols
// forward slash: /
// plus sign: +
// equal sign: =.
if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
return '';
}
$lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
// Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
// than (or equal to) 64 characters long.
for ($i=0, $j=count($lines); $i < $j; $i++) {
if ($i + 1 == $j) {
if (64 < strlen($lines[$i])) {
return '';
}
continue;
}
if (64 != strlen($lines[$i])) {
return '';
}
}
return implode("\n", $lines);
} else {
return '';
}
case self::PARAM_TAGLIST:
$param = fix_utf8($param);
$tags = explode(',', $param);
$result = array();
foreach ($tags as $tag) {
$res = clean_param($tag, PARAM_TAG);
if ($res !== '') {
$result[] = $res;
}
}
if ($result) {
return implode(',', $result);
} else {
return '';
}
case self::PARAM_USERNAME:
$param = fix_utf8($param);
$param = trim($param);
// Convert uppercase to lowercase MDL-16919.
$param = core_text::strtolower($param);
if (empty($CFG->extendedusernamechars)) {
$param = str_replace(" " , "", $param);
// Regular expression, eliminate all chars EXCEPT:
// alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
$param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
}
return $param;
case self::PARAM_EMAIL:
$param = fix_utf8($param);
if (validate_email($param)) {
return $param;
} else {
return '';
}
case self::PARAM_STRINGID:
if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
return $param;
} else {
return '';
}
case self::PARAM_TIMEZONE:
// Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
$param = fix_utf8($param);
$timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
if (preg_match($timezonepattern, $param)) {
return $param;
} else {
return '';
}
default:
// Doh! throw error, switched parameters in optional_param or another serious problem.
print_error("unknownparamtype", '', '', $type);
}
}
function fix_utf8($value) {
if (is_null($value) or $value === '') {
return $value;
} else if (is_string($value)) {
if ((string)(int)$value === $value) {
// Shortcut.
return $value;
}
// No null bytes expected in our data, so let's remove it.
$value = str_replace("\0", '', $value);
// Note: this duplicates min_fix_utf8() intentionally.
static $buggyiconv = null;
if ($buggyiconv === null) {
$buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
}
if ($buggyiconv) {
if (function_exists('mb_convert_encoding')) {
$subst = mb_substitute_character();
mb_substitute_character('');
$result = mb_convert_encoding($value, 'utf-8', 'utf-8');
mb_substitute_character($subst);
} else {
// Warn admins on admin/index.php page.
$result = $value;
}
} else {
$result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
}
return $result;
} else if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = fix_utf8($v);
}
return $value;
} else if (is_object($value)) {
// Do not modify original.
$value = clone($value);
foreach ($value as $k => $v) {
$value->$k = fix_utf8($v);
}
return $value;
} else {
// This is some other type, no utf-8 here.
return $value;
}
}
function validateUrlSyntax( $urladdr, $options="" ){
// Force Options parameter to be lower case
// DISABLED PERMAMENTLY - OK to remove from code
// $options = strtolower($options);
// Check Options Parameter
if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
{
trigger_error("Options attribute malformed", E_USER_ERROR);
}
// Set Options Array, set defaults if options are not specified
// Scheme
if (strpos( $options, 's') === false) $aOptions['s'] = '?';
else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
// http://
if (strpos( $options, 'H') === false) $aOptions['H'] = '?';
else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
// https:// (SSL)
if (strpos( $options, 'S') === false) $aOptions['S'] = '?';
else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
// mailto: (email)
if (strpos( $options, 'E') === false) $aOptions['E'] = '-';
else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
// ftp://
if (strpos( $options, 'F') === false) $aOptions['F'] = '-';
else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
// User section
if (strpos( $options, 'u') === false) $aOptions['u'] = '?';
else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
// Password in user section
if (strpos( $options, 'P') === false) $aOptions['P'] = '?';
else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
// Address Section
if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
// IP Address in address section
if (strpos( $options, 'I') === false) $aOptions['I'] = '?';
else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
// Port number
if (strpos( $options, 'p') === false) $aOptions['p'] = '?';
else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
// File Path
if (strpos( $options, 'f') === false) $aOptions['f'] = '?';
else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
// Query Section
if (strpos( $options, 'q') === false) $aOptions['q'] = '?';
else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
// Fragment (Anchor)
if (strpos( $options, 'r') === false) $aOptions['r'] = '?';
else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
// Loop through options array, to search for and replace "-" to "{0}" and "+" to ""
foreach($aOptions as $key => $value)
{
if ($value == '-')
{
$aOptions[$key] = '{0}';
}
if ($value == '+')
{
$aOptions[$key] = '';
}
}
// DEBUGGING - Unescape following line to display to screen current option values
// echo ''; print_r($aOptions); echo '
';
// Preset Allowed Characters
$alphanum = '[a-zA-Z0-9]'; // Alpha Numeric
$unreserved = '[a-zA-Z0-9_.!~*' . '\'' . '()-]';
$escaped = '(%[0-9a-fA-F]{2})'; // Escape sequence - In Hex - %6d would be a 'm'
$reserved = '[;/?:@&=+$,]'; // Special characters in the URI
// Beginning Regular Expression
// Scheme - Allows for 'http://', 'https://', 'mailto:', or 'ftp://'
$scheme = '(';
if ($aOptions['H'] === '') { $scheme .= 'http://'; }
elseif ($aOptions['S'] === '') { $scheme .= 'https://'; }
elseif ($aOptions['E'] === '') { $scheme .= 'mailto:'; }
elseif ($aOptions['F'] === '') { $scheme .= 'ftp://'; }
else
{
if ($aOptions['H'] === '?') { $scheme .= '|(http://)'; }
if ($aOptions['S'] === '?') { $scheme .= '|(https://)'; }
if ($aOptions['E'] === '?') { $scheme .= '|(mailto:)'; }
if ($aOptions['F'] === '?') { $scheme .= '|(ftp://)'; }
$scheme = str_replace('(|', '(', $scheme); // fix first pipe
}
$scheme .= ')' . $aOptions['s'];
// End setting scheme
// User Info - Allows for 'username@' or 'username:password@'. Note: contrary to rfc, I removed ':' from username section, allowing it only in password.
// /---------------- Username -----------------------\ /-------------------------------- Password ------------------------------\
$userinfo = '((' . $unreserved . '|' . $escaped . '|[;&=+$,]' . ')+(:(' . $unreserved . '|' . $escaped . '|[;:&=+$,]' . ')+)' . $aOptions['P'] . '@)' . $aOptions['u'];
// IP ADDRESS - Allows 0.0.0.0 to 255.255.255.255
$ipaddress = '((((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9]))\.){3}((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9])))';
// Tertiary Domain(s) - Optional - Multi - Although some sites may use other characters, the RFC says tertiary domains have the same naming restrictions as second level domains
$domain_tertiary = '(' . $alphanum . '(([a-zA-Z0-9-]{0,62})' . $alphanum . ')?\.)*';
/* MDL-9295 - take out domain_secondary here and below, so that URLs like http://localhost/ and lan addresses like http://host/ are accepted.
// Second Level Domain - Required - First and last characters must be Alpha-numeric. Hyphens are allowed inside.
$domain_secondary = '(' . $alphanum . '(([a-zA-Z0-9-]{0,62})' . $alphanum . ')?\.)';
*/
// we want more relaxed URLs in Moodle: MDL-11462
// Top Level Domain - First character must be Alpha. Last character must be AlphaNumeric. Hyphens are allowed inside.
$domain_toplevel = '([a-zA-Z](([a-zA-Z0-9-]*)[a-zA-Z0-9])?)';
/* // Top Level Domain - Required - Domain List Current As Of December 2004. Use above escaped line to be forgiving of possible future TLD's
$domain_toplevel = '(aero|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|post|pro|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ax|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)';
*/
// Address can be IP address or Domain
if ($aOptions['I'] === '{0}') { // IP Address Not Allowed
$address = '(' . $domain_tertiary . /* MDL-9295 $domain_secondary . */ $domain_toplevel . ')';
} elseif ($aOptions['I'] === '') { // IP Address Required
$address = '(' . $ipaddress . ')';
} else { // IP Address Optional
$address = '((' . $ipaddress . ')|(' . $domain_tertiary . /* MDL-9295 $domain_secondary . */ $domain_toplevel . '))';
}
$address = $address . $aOptions['a'];
// Port Number - :80 or :8080 or :65534 Allows range of :0 to :65535
// (0-59999) |(60000-64999) |(65000-65499) |(65500-65529) |(65530-65535)
$port_number = '(:(([0-5]?[0-9]{1,4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5])))' . $aOptions['p'];
// Path - Can be as simple as '/' or have multiple folders and filenames
$path = '(/((;)?(' . $unreserved . '|' . $escaped . '|' . '[:@&=+$,]' . ')+(/)?)*)' . $aOptions['f'];
// Query Section - Accepts ?var1=value1&var2=value2 or ?2393,1221 and much more
$querystring = '(\?(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['q'];
// Fragment Section - Accepts anchors such as #top
$fragment = '(\#(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['r'];
// Building Regular Expression
$regexp = '#^' . $scheme . $userinfo . $address . $port_number . $path . $querystring . $fragment . '$#i';
// DEBUGGING - Uncomment Line Below To Display The Regular Expression Built
// echo '' . htmlentities(wordwrap($regexp,70,"\n",1)) . '
';
// Running the regular expression
if (preg_match( $regexp, $urladdr ))
{
return true; // The domain passed
}
else
{
return false; // The domain didn't pass the expression
}
}
function validateEmailSyntax( $emailaddr, $options="" ){
// Check Options Parameter
if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
{
trigger_error("Options attribute malformed", E_USER_ERROR);
}
// Set Options Array, set defaults if options are not specified
// Scheme
if (strpos( $options, 's') === false) $aOptions['s'] = '-';
else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
// http://
if (strpos( $options, 'H') === false) $aOptions['H'] = '-';
else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
// https:// (SSL)
if (strpos( $options, 'S') === false) $aOptions['S'] = '-';
else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
// mailto: (email)
if (strpos( $options, 'E') === false) $aOptions['E'] = '?';
else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
// ftp://
if (strpos( $options, 'F') === false) $aOptions['F'] = '-';
else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
// User section
if (strpos( $options, 'u') === false) $aOptions['u'] = '+';
else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
// Password in user section
if (strpos( $options, 'P') === false) $aOptions['P'] = '-';
else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
// Address Section
if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
// IP Address in address section
if (strpos( $options, 'I') === false) $aOptions['I'] = '-';
else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
// Port number
if (strpos( $options, 'p') === false) $aOptions['p'] = '-';
else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
// File Path
if (strpos( $options, 'f') === false) $aOptions['f'] = '-';
else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
// Query Section
if (strpos( $options, 'q') === false) $aOptions['q'] = '-';
else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
// Fragment (Anchor)
if (strpos( $options, 'r') === false) $aOptions['r'] = '-';
else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
// Generate options
$newoptions = '';
foreach($aOptions as $key => $value)
{
$newoptions .= $key . $value;
}
// DEBUGGING - Uncomment line below to display generated options
// echo '' . $newoptions . '
';
// Send to validateUrlSyntax() and return result
return validateUrlSyntax( $emailaddr, $newoptions);
}
function validateFtpSyntax( $ftpaddr, $options="" ){
// Check Options Parameter
if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
{
trigger_error("Options attribute malformed", E_USER_ERROR);
}
// Set Options Array, set defaults if options are not specified
// Scheme
if (strpos( $options, 's') === false) $aOptions['s'] = '?';
else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
// http://
if (strpos( $options, 'H') === false) $aOptions['H'] = '-';
else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
// https:// (SSL)
if (strpos( $options, 'S') === false) $aOptions['S'] = '-';
else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
// mailto: (email)
if (strpos( $options, 'E') === false) $aOptions['E'] = '-';
else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
// ftp://
if (strpos( $options, 'F') === false) $aOptions['F'] = '+';
else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
// User section
if (strpos( $options, 'u') === false) $aOptions['u'] = '?';
else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
// Password in user section
if (strpos( $options, 'P') === false) $aOptions['P'] = '?';
else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
// Address Section
if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
// IP Address in address section
if (strpos( $options, 'I') === false) $aOptions['I'] = '?';
else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
// Port number
if (strpos( $options, 'p') === false) $aOptions['p'] = '?';
else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
// File Path
if (strpos( $options, 'f') === false) $aOptions['f'] = '?';
else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
// Query Section
if (strpos( $options, 'q') === false) $aOptions['q'] = '-';
else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
// Fragment (Anchor)
if (strpos( $options, 'r') === false) $aOptions['r'] = '-';
else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
// Generate options
$newoptions = '';
foreach($aOptions as $key => $value)
{
$newoptions .= $key . $value;
}
// DEBUGGING - Uncomment line below to display generated options
// echo '' . $newoptions . '
';
// Send to validateUrlSyntax() and return result
return validateUrlSyntax( $ftpaddr, $newoptions);
}
}