Skip to content

Commit

Permalink
MDL-19418 Replaced ereg* by preg*
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolasconnault committed Jun 22, 2009
1 parent c20b684 commit 6dbcace
Show file tree
Hide file tree
Showing 36 changed files with 183 additions and 165 deletions.
10 changes: 5 additions & 5 deletions admin/mnet/MethodTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -465,15 +465,15 @@ function cleanArguments($args, $commentParams){
$word0 = strtolower($word0);
$word1 = strtolower($word1);

$wordBase0 = ereg_replace('^[&$]+','',$word0);
$wordBase1 = ereg_replace('^[&$]+','',$word1);
$startBase = strtolower(ereg_replace('^[&$]+','',$start));
$wordBase0 = preg_replace('/^[&$]+/','',$word0);
$wordBase1 = preg_replace('/^[&$]+/','',$word1);
$startBase = strtolower(preg_replace('/^[&$]+/','',$start));

if ($wordBase0 == $startBase) {
$type = str_replace(array('(',')'),'', $word1);
} elseif($wordBase1 == $startBase) {
$type = str_replace(array('(',')'),'', $word0);
} elseif( ereg('(^[&$]+)|(\()([a-z0-9]+)(\)$)', $word0, $regs) ) {
} elseif( preg_match('/(^[&$]+)|(\()([a-z0-9]+)(\)$)/', $word0, $regs) ) {
$tail = str_ireplace($word0, '', $end);
$type = $regs[3];
} else {
Expand Down Expand Up @@ -535,7 +535,7 @@ function cleanComment($comment){
$comment = str_replace("*/", "", $comment);
$comment = str_replace("*", "", $comment);
$comment = str_replace("\n", "\\n", trim($comment));
$comment = eregi_replace("[\r\t\n ]+", " ", trim($comment));
$comment = preg_replace("/[\r\t\n ]+/i", " ", trim($comment));
$comment = str_replace("\"", "\\\"", $comment);
return $comment;
}
Expand Down
16 changes: 8 additions & 8 deletions admin/uploaduser.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@
$bulknurl = $CFG->wwwroot.'/'.$CFG->admin.'/user/user_bulk.php';

// array of all valid fields for validation
$STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
'city', 'country', 'lang', 'auth', 'timezone', 'mailformat',
'maildisplay', 'maildigest', 'htmleditor', 'ajax', 'autosubscribe',
'mnethostid', 'institution', 'department', 'idnumber', 'skype',
'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
'url', 'description', 'oldusername', 'emailstop', 'deleted',
$STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
'city', 'country', 'lang', 'auth', 'timezone', 'mailformat',
'maildisplay', 'maildigest', 'htmleditor', 'ajax', 'autosubscribe',
'mnethostid', 'institution', 'department', 'idnumber', 'skype',
'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
'url', 'description', 'oldusername', 'emailstop', 'deleted',
'password');

$PRF_FIELDS = array();
Expand Down Expand Up @@ -262,7 +262,7 @@
// normalize username
$user->username = $textlib->strtolower($user->username);
if (empty($CFG->extendedusernamechars)) {
$user->username = eregi_replace('[^(-\.[:alnum:])]', '', $user->username);
$user->username = preg_replace('/[^(-\.[:alnum:])]/i', '', $user->username);
}
if (empty($user->username)) {
$upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
Expand Down Expand Up @@ -1010,4 +1010,4 @@ function uu_allowed_roles($shortname=false) {

return $choices;
}
?>
?>
2 changes: 1 addition & 1 deletion auth/shibboleth/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function user_login($username, $password) {
} else {
// Try to find out using the user's cookie
foreach ($_COOKIE as $name => $value){
if (eregi('_shibsession_', $name)){
if (preg_match('/_shibsession_/i', $name)){
$sessionkey = $value;
}
}
Expand Down
4 changes: 2 additions & 2 deletions calendar/lib.php
Original file line number Diff line number Diff line change
Expand Up @@ -770,8 +770,8 @@ function calendar_top_controls($type, $data) {
$text = get_string('strftimedaydate');
/*
// Regexp hackery to make a link out of the month/year part
$text = ereg_replace('(%B.+%Y|%Y.+%B|%Y.+%m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
$text = ereg_replace('(F.+Y|Y.+F|Y.+m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
$text = preg_replace('/(%B.+%Y|%Y.+%B|%Y.+%m[^ ]+)/', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
$text = preg_replace('/(F.+Y|Y.+F|Y.+m[^ ]+)/', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
*/
// Replace with actual values and lose any day leading zero
$text = userdate($time, $text);
Expand Down
22 changes: 11 additions & 11 deletions enrol/authorize/enrol_form.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ private function other_method_available($currentmethod)

private function validate_aba($aba)
{
if (ereg("^[0-9]{9}$", $aba)) {
if (preg_match("/^[0-9]{9}$/", $aba)) {
$n = 0;
for($i = 0; $i < 9; $i += 3) {
$n += (substr($aba, $i, 1) * 3) + (substr($aba, $i + 1, 1) * 7) + (substr($aba, $i + 2, 1));
Expand Down Expand Up @@ -272,45 +272,45 @@ private function validate_cc($Num, $Name = "n/a", $Exp = "")
$GoodCard = true;

// Get rid of any non-digits
$Num = ereg_replace("[^0-9]", "", $Num);
$Num = preg_replace("/[^0-9]~", "", $Num);

// Perform card-specific checks, if applicable
switch ($Name)
{
case "mcd" :
$GoodCard = ereg("^5[1-5].{14}$", $Num);
$GoodCard = preg_match("/^5[1-5].{14}$/", $Num);
break;

case "vis" :
$GoodCard = ereg("^4.{15}$|^4.{12}$", $Num);
$GoodCard = preg_match("/^4.{15}$|^4.{12}$/", $Num);
break;

case "amx" :
$GoodCard = ereg("^3[47].{13}$", $Num);
$GoodCard = preg_match("/^3[47].{13}$/", $Num);
break;

case "dsc" :
$GoodCard = ereg("^6011.{12}$", $Num);
$GoodCard = preg_match("/^6011.{12}$/", $Num);
break;

case "dnc" :
$GoodCard = ereg("^30[0-5].{11}$|^3[68].{12}$", $Num);
$GoodCard = preg_match("/^30[0-5].{11}$|^3[68].{12}$/", $Num);
break;

case "jcb" :
$GoodCard = ereg("^3.{15}$|^2131|1800.{11}$", $Num);
$GoodCard = preg_match("/^3.{15}$|^2131|1800.{11}$/", $Num);
break;

case "dlt" :
$GoodCard = ereg("^4.{15}$", $Num);
$GoodCard = preg_match("/^4.{15}$/", $Num);
break;

case "swi" :
$GoodCard = ereg("^[456].{15}$|^[456].{17,18}$", $Num);
$GoodCard = preg_match("/^[456].{15}$|^[456].{17,18}$/", $Num);
break;

case "enr" :
$GoodCard = ereg("^2014.{11}$|^2149.{11}$", $Num);
$GoodCard = preg_match("/^2014.{11}$|^2149.{11}$/", $Num);
break;
}

Expand Down
4 changes: 2 additions & 2 deletions install.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@
*/

if (isset($_REQUEST['lang'])) {
$lang = eregi_replace('[^A-Za-z0-9_-]', '', $_REQUEST['lang']);
$lang = preg_replace('/[^A-Za-z0-9_-]/i', '', $_REQUEST['lang']);
} else {
$lang = 'en_utf8';
}

if (isset($_REQUEST['admin'])) {
$admin = eregi_replace('[^A-Za-z0-9_-]', '', $_REQUEST['admin']);
$admin = preg_replace('/[^A-Za-z0-9_-]/i', '', $_REQUEST['admin']);
} else {
$admin = 'admin';
}
Expand Down
36 changes: 18 additions & 18 deletions lib/moodlelib.php
Original file line number Diff line number Diff line change
Expand Up @@ -448,19 +448,19 @@ function clean_param($param, $type) {
return (float)$param; // Convert to float

case PARAM_ALPHA: // Remove everything not a-z
return eregi_replace('[^a-zA-Z]', '', $param);
return preg_replace('/[^a-zA-Z]/i', '', $param);

case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
return eregi_replace('[^a-zA-Z_-]', '', $param);
return preg_replace('/[^a-zA-Z_-]/i', '', $param);

case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
return eregi_replace('[^A-Za-z0-9]', '', $param);
return preg_replace('/[^A-Za-z0-9]/i', '', $param);

case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
return eregi_replace('[^A-Za-z0-9_-]', '', $param);
return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);

case PARAM_SEQUENCE: // Remove everything not 0-9,
return eregi_replace('[^0-9,]', '', $param);
return preg_replace('/[^0-9,]/i', '', $param);

case PARAM_BOOL: // Convert to 1 or 0
$tempstr = strtolower($param);
Expand All @@ -480,25 +480,25 @@ function clean_param($param, $type) {
return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);

case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);

case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
return eregi_replace('[^a-zA-Z0-9/_-]', '', $param);
return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);

case PARAM_FILE: // Strip all suspicious characters from filename
$param = ereg_replace('[[:cntrl:]]|[&<>"`\|\':\\/]', '', $param);
$param = ereg_replace('\.\.+', '', $param);
$param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\/]~', '', $param);
$param = preg_replace('~\.\.+~', '', $param);
if ($param === '.') {
$param = '';
}
return $param;

case PARAM_PATH: // Strip all suspicious characters from file path
$param = str_replace('\\', '/', $param);
$param = ereg_replace('[[:cntrl:]]|[&<>"`\|\':]', '', $param);
$param = ereg_replace('\.\.+', '', $param);
$param = ereg_replace('//+', '/', $param);
return ereg_replace('/(\./)+', '/', $param);
$param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~', '', $param);
$param = preg_replace('~\.\.+~', '', $param);
$param = preg_replace('~//+~', '/', $param);
return preg_replace('~/(\./)+~', '/', $param);

case PARAM_HOST: // allow FQDN or IPv4 dotted quad
$param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
Expand Down Expand Up @@ -604,7 +604,7 @@ function clean_param($param, $type) {
//problem, so remove *all* backslash.
//$param = str_replace('\\', '', $param);
//remove some nasties
$param = ereg_replace('[[:cntrl:]]|[<>`]', '', $param);
$param = preg_replace('~[[:cntrl:]]|[<>`]~', '', $param);
//convert many whitespace chars into one
$param = preg_replace('/\s+/', ' ', $param);
$textlib = textlib_get_instance();
Expand Down Expand Up @@ -4540,7 +4540,7 @@ function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $a
}

if ($attachment && $attachname) {
if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
if (preg_match( "~\\.\\.~" ,$attachment )) { // Security check for ".." in dir path
$mail->AddAddress($supportuser->email, fullname($supportuser, true) );
$mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
} else {
Expand Down Expand Up @@ -5058,7 +5058,7 @@ function make_mod_upload_directory($courseid) {
function make_user_directory($userid, $test=false) {
global $CFG;

if (is_bool($userid) || $userid < 0 || !ereg('^[0-9]{1,10}$', $userid) || $userid > 2147483647) {
if (is_bool($userid) || $userid < 0 || !preg_match('/^[0-9]{1,10}$/', $userid) || $userid > 2147483647) {
if (!$test) {
notify("Given userid was not a valid integer! (" . gettype($userid) . " $userid)");
}
Expand Down Expand Up @@ -7550,7 +7550,7 @@ function count_letters($string) {
$textlib = textlib_get_instance();

$string = strip_tags($string); // Tags are out now
$string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
$string = preg_replace('/[[:space:]]*/','',$string); //Whitespace are out now

return $textlib->strlen($string);
}
Expand Down Expand Up @@ -9172,4 +9172,4 @@ function check_consecutive_identical_characters($password, $maxchars) {
return true;
}

?>
?>
6 changes: 6 additions & 0 deletions lib/simpletest/testweblib.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ function test_format_string() {

function test_s() {
$this->assertEqual(s("This Breaks \" Strict"), "This Breaks &quot; Strict");
$this->assertEqual(s("This Breaks <a>\" Strict</a>"), "This Breaks &lt;a&gt;&quot; Strict&lt;/a&gt;");
}

function test_format_text_email() {
Expand Down Expand Up @@ -66,5 +67,10 @@ function test_highlight() {
$this->assertEqual(highlight('+good', 'This is goodness'), 'This is goodness');
$this->assertEqual(highlight('good', 'This is goodness'), 'This is <span class="highlight">good</span>ness');
}

function test_replace_ampersands() {
$this->assertEqual(replace_ampersands_not_followed_by_entity("This & that &nbsp;"), "This &amp; that &nbsp;");
$this->assertEqual(replace_ampersands_not_followed_by_entity("This &nbsp that &nbsp;"), "This &amp;nbsp that &nbsp;");
}
}
?>
33 changes: 23 additions & 10 deletions lib/weblib.php
Original file line number Diff line number Diff line change
Expand Up @@ -1639,7 +1639,8 @@ function format_string($string, $striplinks=true, $courseid=NULL ) {
}

// First replace all ampersands not followed by html entity code
$string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
// Regular expression moved to its own method for easier unit testing
$string = replace_ampersands_not_followed_by_entity($string);

if (!empty($CFG->filterall) && $CFG->version >= 2009040600) { // Avoid errors during the upgrade to the new system.
$context = $PAGE->context;
Expand All @@ -1664,6 +1665,18 @@ function format_string($string, $striplinks=true, $courseid=NULL ) {
return $string;
}

/**
* Given a string, performs a negative lookahead looking for any ampersand character
* that is not followed by a proper HTML entity. If any is found, it is replaced
* by &amp;. The string is then returned.
*
* @param string $string
* @return string
*/
function replace_ampersands_not_followed_by_entity($string) {
return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
}

/**
* Given text in a variety of format codings, this function returns
* the text as plain text suitable for plain email.
Expand All @@ -1690,7 +1703,7 @@ function format_text_email($text, $format) {
$text = wiki_to_html($text);
/// This expression turns links into something nice in a text format. (Russell Jungwirth)
/// From: http://php.net/manual/en/function.eregi-replace.php and simplified
$text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
$text = preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $text);
return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;

Expand All @@ -1701,7 +1714,7 @@ function format_text_email($text, $format) {
case FORMAT_MOODLE:
case FORMAT_MARKDOWN:
default:
$text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
$text = preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $text);
return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;
}
Expand Down Expand Up @@ -1861,8 +1874,8 @@ function clean_text($text, $format=FORMAT_MOODLE) {
}

/// Remove potential script events - some extra protection for undiscovered bugs in our code
$text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
$text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
$text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "$1Xlanguage=", $text);
$text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "$1Xon$2=", $text);

return $text;
}
Expand Down Expand Up @@ -2105,11 +2118,11 @@ function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
global $CFG;

/// Remove any whitespace that may be between HTML tags
$text = eregi_replace(">([[:space:]]+)<", "><", $text);
$text = preg_replace("~>([[:space:]]+)<~i", "><", $text);

/// Remove any returns that precede or follow HTML tags
$text = eregi_replace("([\n\r])<", " <", $text);
$text = eregi_replace(">([\n\r])", "> ", $text);
$text = preg_replace("~([\n\r])<~i", " <", $text);
$text = preg_replace("~>([\n\r])~i", "> ", $text);

convert_urls_into_links($text);

Expand Down Expand Up @@ -2172,11 +2185,11 @@ function html_to_text($html) {
*/
function convert_urls_into_links(&$text) {
/// Make lone URLs into links. eg http://moodle.com/
$text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
$text = preg_replace("~([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])~i",
"\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);

/// eg www.moodle.com
$text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
$text = preg_replace("~([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])~i",
"\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
}

Expand Down
2 changes: 1 addition & 1 deletion login/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
$frm->username = trim(moodle_strtolower($frm->username));

if (is_enabled_auth('none') && empty($CFG->extendedusernamechars)) {
$string = eregi_replace("[^(-\.[:alnum:])]", "", $frm->username);
$string = preg_replace("~[^(-\.[:alnum:])]~i", "", $frm->username);
if (strcmp($frm->username, $string)) {
$errormsg = get_string('username').': '.get_string("alphanumerical");
$errorcode = 2;
Expand Down
4 changes: 2 additions & 2 deletions login/signup_form.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function definition() {

if (signup_captcha_enabled()) {
$mform->addElement('recaptcha', 'recaptcha_element', get_string('recaptcha', 'auth'), array('https' => $CFG->loginhttps));
$mform->setHelpButton('recaptcha_element', array('recaptcha', get_string('recaptcha', 'auth')));
$mform->setHelpButton('recaptcha_element', array('recaptcha', get_string('recaptcha', 'auth')));
}

profile_signup_fields($mform);
Expand Down Expand Up @@ -99,7 +99,7 @@ function validation($data, $files) {
$errors['username'] = get_string('usernameexists');
} else {
if (empty($CFG->extendedusernamechars)) {
$string = eregi_replace("[^(-\.[:alnum:])]", '', $data['username']);
$string = preg_replace("~[^(-\.[:alnum:])]~i", '', $data['username']);
if (strcmp($data['username'], $string)) {
$errors['username'] = get_string('alphanumerical');
}
Expand Down
Loading

0 comments on commit 6dbcace

Please sign in to comment.