File: D:/HostingSpaces/PvdBoogaard/indoorski.nl/backup/oude-site/cms/api/class.validation.php
<?php
/**
* This file contains the iwp_validation class.
*/
/**
* This is the iwp_validation class which is used to filter or validate content or values.
* The iwp_base class makes this available through overloading. Most IWP classes can access this class using $this->valid
*
* Two types of functions within this class:
* - Functions starting with "Filter" return the filtered value [mixed]
* - Functions starting with "Is" or "Has" returns true/false based on the value [boolean]
**/
class iwp_validation
{
/**
* This is an overload function which can be used to call a dynamic function.
*
* e.g. FilterLimit250 will use the 250 in the name to cut the string to 250 characters
*
* @param string $func The name of the function to call
* @param string $args The arguments to pass to the function
* @return mixed Can be an Is/Has function or can be a filter, so the return is based on that
*/
public function __call($func, $args){
if(iwp_iStartsWith($func, "filterlimit")){
$func = str_ireplace("filterlimit", "", $func);
$func = (int)$func;
if($func > 0){
return substr($args[0], 0, $func);
}
}
return '';
}
/**
* This function takes in a variable as a reference and casts it to an integer to check if it is a valid ID number
* This saves doing it on the other side because this will be done anyway
*
* @param integer $id This *should* be an integer, if its not, its cast anyway
*
* @return boolean If the variable passed in is a valid ID number or not
*/
public function IsId(&$id){
$id = (int)$id;
if($id > 0){
return true;
}
return false;
}
/**
* Removes any characters that aren't English letters or numbers. (Even strips spaces)
*
* @param string $str The string to filter on
* @return string A string of only alphanumeric characters
*/
public function FilterAlphaNumeric($str){
return preg_replace('/[^a-zA-Z0-9]/','',$str);
}
/**
* Similar to the FilterAlphaNumeric() function but allows spaces, dashes and underscores as well.
*
* @param string $str The string to be filtered
* @return string The filtered string
*/
public function FilterAlphaNumericExtended($str, $charsToAllow=null){
if(is_null($charsToAllow)){
$charsToAllow = preg_quote(' \-_', '/');
}
return preg_replace('/[^a-zA-Z0-9'.$charsToAllow.']/','',$str);
}
/**
* Similar to the FilterAlphaNumeric() function but allows other characters that can be in a URL.
*
* @param string $str The string to be filtered
* @return string The filtered string
*/
public function FilterAlphaNumericURL($str){
return preg_replace('/[^a-zA-Z0-9 \-_\/\{\}\.\:;,]/','',$str);
}
/**
* Filters out any characters that aren't in the English alphabet (including numbers)
*
* @param string $str The string to be filtered
* @return string The filtered string
*/
public function FilterAlpha($str){
return preg_replace('/[^a-zA-Z]/','',$str);
}
/**
* Filters out any characters that shouldn't be in a filename.
*
* @param string $str The string to be filtered
* @return string The filtered string
*/
public function FilterFilename($str){
return preg_replace('/[^a-zA-Z0-9\._\-]/i','',$str);
}
/**
* Filters out any spaces that are more than 2 characters long to just one space.
* This can help in preventing special SQL attacks.
*
* @param string $str The string to have extra spaces removed
* @return string The cleaned string
*/
public function FilterDoubleWhiteSpace($str){
return trim(preg_replace('/\s{2,}/', ' ', $str));
}
/**
* This takes an array and removes any empty elements and returns the 'cleaned' array
*
* @param array $arr The array to remove empty elements from
* @return array An array with no empty elements
*/
public function FilterCleanArray($arr){
$new = array();
foreach($arr as $key=>$val){
if($val != ''){
$new[$key] = $val;
}
}
return $new;
}
/**
* This takes a string and returns another string which is safe for outputting to javascript.
*
* Escaped characters are:
* \ literal backslash
* \n newline
* \r carriage return
* " double quote
* ' single quote
* &
* <
* >
*
* Basic usage example:
*
* <script type="text/javascript">
* var string = <?php echo FilterJavascriptString('foo'); ? >;
* </script>
*
* @param string $string Input string to filter
* @param boolean $quoted Optional, default is true. If set to true the returned string will include quotes, e.g. "string".
* @return string Returns the input string with all appropriate control characters escaped for javascript usage
*/
public function FilterJavascriptString ($string, $quoted = true)
{
$string = strtr($string, self::$FilterJavascriptStringTable);
if ($quoted) {
$string = '"' . $string . '"';
}
return $string;
}
/**
* The translation table to use for FilterJavascriptString
*
* @var array
*/
public static $FilterJavascriptStringTable = array(
"\\" => "\\\\",
"\n" => "\\n",
"\r" => "\\r",
"'" => "\\'",
"\"" => "\\\"",
"&" => "\\x26",
"<" => "\\x3C",
">" => "\\x3E",
);
/**
* Takes in a file name and returns false if the extension appers in a blacklist of file extensions.
* This prevents users uploading .php file or anything else that could be harmful.
*
* @param string $fileName The filename to check
* @return boolean True if the filename is OK, false if its a bad filename
*/
public function IsNotBadFileExtension($fileName){
$badFiles = array('.php','.cgi','.pl','.py', '.php3','.php4','.php5','.asp','.aspx','.c','.phtml','.sh');
foreach($badFiles as $_key=>$value) {
$length = strlen($value);
// check the extension
if(strlen($fileName) > 0){
$extStart = strlen($fileName)-$length;
if($extStart >= 0){
if(substr($fileName,$extStart) == $value) {
// must be a bad file!
return false;
}
}
}
}
return true;
}
/**
* Takes a filename (string) and makes sure that the extension is a valid image extension
*
* @param string $filename The filename to check the extension for
*
* @return boolean True if it is a valid image extension, false otherwise
*/
public function IsImageFileExtension($fileName) {
$imgFiles = array('.jpg','.jpeg','.gif','.png', '.bmp','.tiff');
foreach($imgFiles as $_key=>$value) {
$length = strlen($value);
// check the extension
if(strlen($fileName) > 0){
$extStart = strlen($fileName)-$length;
if($extStart >= 0){
if(substr(iwp_strtolower($fileName),$extStart) == iwp_strtolower($value)) {
// Is a good extension
return true;
}
}
}
}
return false;
}
/**
* Takes a filename (string) and makes sure that the extension is a valid image extension
*
* @param string $filename The filename to check the extension for
*
* @return boolean True if it is a valid image extension, false otherwise
*/
public function IsImageFileJpgPng($fileName) {
$imgFiles = array('.jpg','.png');
foreach($imgFiles as $_key=>$value) {
$length = strlen($value);
// check the extension
if(strlen($fileName) > 0){
$extStart = strlen($fileName)-$length;
if($extStart >= 0){
if(substr($fileName,$extStart) == $value) {
// must be a bad file!
return true;
}
}
}
}
return false;
}
/**
* Takes a path to a file and returns true if it is a known, valid image file.
*
* @param string $path The path to the file to be checked
* @param array $imageTypes An array of valid image types made up of the IMAGETYPE_XXX constants from http://php.net/manual/en/image.constants.php - the default set is GIF, JPEG, PNG, BMP and TIFF2
* @return boolean
*/
public function IsImageFile ($path, $imageTypes = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_TIFF_II)) {
$imageDimensions = @getimagesize($path);
if ($imageDimensions === false || !is_array($imageDimensions) || !in_array($imageDimensions[2], $imageTypes, true)) {
return false;
}
return true;
}
/**
* Takes a filename (string) and makes sure that the extension is a valid flash movie extension
*
* @param string $filename The filename to check the extension for
*
* @return boolean True if it is a valid flash movie extension, false otherwise
*/
public function IsFlashFileExtension($fileName) {
$imgFiles = array('.swf','.flv','.f4v','.f4p','.f4a','.f4b');
foreach($imgFiles as $_key=>$value) {
$length = strlen($value);
// check the extension
if(strlen($fileName) > 0){
$extStart = strlen($fileName)-$length;
if($extStart >= 0){
if(substr($fileName,$extStart) == $value) {
// must be a bad file!
return true;
}
}
}
}
return false;
}
/**
* Takes a string and tests to see if its "blank", that include blank, null or zero
*
* @param string $str The string to check if its blank
* @param boolean $trim If true, the $str value will have the trim() function run before it is evaluated as strings that are just spaces are not counted as blank)
* @return boolean True if the string is blank, false if its not.
*/
public function IsBlank($str,$trim=true){
if($trim) { $str = trim($str); }
if(strlen($str) === 0 || $str === null || iwp_strtolower($str) == "null" || $str === "0" || $str === 0){
return true;
}else{
return false;
}
}
/**
* Similar to the 'IsBlank' function but it does it for html, so and <br /> are considered 'blank'. Devedit often returns these and not an empty string.
*
* @param string $str The string with HTML to check if its blank
* @param boolean $trim If true, the $str value will have the trim() function run before it is evaluated as strings that are just spaces are not counted as blank)
* @return boolean True if the string is blank, false if its not.
*/
public function IsHtmlBlank($str, $trim=true){
if($trim === true){
$str = trim($str);
}
if(empty($str)){
return true;
}
$str = preg_replace("#<br[ ]*/>#ism", "", $str);
$str = str_replace(" ", "", $str);
$str = str_replace("<br/>", "", $str);
$str = str_replace("\r\n", "", $str);
$str = str_replace("\r", "", $str);
$str = str_replace("\n", "", $str);
if(empty($str)){
return true;
}
$str = trim(strip_tags($str, '<img>'));
if($str == ""){
return true;
}
return false;
}
/**
* The opposite of the IsBlank() function.
*
* @param string $str The string to check if it is not blank
* @param boolean $trim If true, the $str value will have the trim() function run before it is evaluated as strings that are just spaces are not counted as blank)
* @return boolean True if the string is not blank, false if it is.
*
* @see IsBlank()
*/
public function IsNumberOnly($value){
return ((float)$value == $value);
}
/**
* Validates that the given string is a selectable timezone in the current PHP installation.
*
* Will temporarily set the default timezone and then return it to the value of date_default_timezone_get()
*
* @param string $identifier The string to check
* @return boolean True if the string is a selectable timezone, otherwise false.
*/
public function IsValidTimezone ($identifier) {
$current = @date_default_timezone_get();
$result = @date_default_timezone_set($identifier);
if ($current !== $identifier) {
@date_default_timezone_set($current);
}
return $result;
}
/**
* The opposite of the IsBlank() function.
*
* @param string $str The string to check if it is not blank
* @param boolean $trim If true, the $str value will have the trim() function run before it is evaluated as strings that are just spaces are not counted as blank)
* @return boolean True if the string is not blank, false if it is.
*
* @see IsBlank()
*/
public function IsNotBlank($str, $trim=false){
if($this->IsBlank($str, $trim)){
return false;
}else{
return $str;
}
}
/**
* Returns a type-cast value of the input.
*
* @param mixed $val The value to have converted to an integer
* @return integer
*/
public function FilterInt($val) {
return (int)$val;
}
/**
* Returns a type-cast value of the input.
*
* @param mixed $val The value to have converted to an integer
* @return integer
*/
public function IsInt($val) {
if($val == (int)$val) {
return true;
} else if(is_int($val)) {
return true;
}
return false;
}
/**
* Takes in a value, casts it to an integer and then checks to make sure it is zero or greater.
*
* @param mixed $val The value to have checked
* @return boolean Whether or not it is zero or above when cast to an integer
*
* @see FilterInt
*/
public function IsPositiveInt($val) {
$val = $this->FilterInt($val);
if($val >= 0){
return true;
}else{
return false;
}
}
public function ValidateUserPictureWidth ($val) {
return iwp_validation::ValidateUserPictureWidthHeight($val);
}
public function ValidateUserPictureHeight ($val) {
return iwp_validation::ValidateUserPictureWidthHeight($val);
}
private function ValidateUserPictureWidthHeight ($val) {
$restrict = (@$_POST['RestrictUserPictureSize'] == 'checked');
if (!$restrict) {
return true;
}
$result = iwp_validation::IsNotBlank($val);
if ($result) {
$result = iwp_validation::IsIntGreaterThanZero($val);
}
return $result;
}
/**
* Ensures the string passed in does not have a trailing slash
*
* @param string $str The string to confirm or remove the trailing slash from
*
* @return string The string without a trailing slash
*/
public function FilterNoEndSlash($str){
if(substr($str, -1, 1) == '/'){
return substr($str, 0, -1);
}
return $str;
}
/**
* Ensures the string passed in does not have a beginning slash
*
* @param string $str The string to confirm or remove the beginning slash from
*
* @return string The string without a trailing slash
*/
public function FilterNoStartSlash($str){
if(substr($str, 0, 1) == '/'){
return substr($str, 1);
}
return $str;
}
/**
* Takes in a value and returns true if it equals 'checked'
*
* @param mixed $val The value to have checked
* @return boolean Whether or not the value is equal to 'checked'. True if it is.
*/
public function IsChecked($val){
if(iwp_strtolower($val) == "checked"){
return true;
}
return false;
}
/**
* Takes in a value and returns true if it equals 'selected'
*
* @param mixed $val The value to have selected
* @return boolean Whether or not the value is equal to 'selected'. True if it is.
*/
public function IsSelected($val){
if(iwp_strtolower($val) == "selected"){
return true;
}
return false;
}
/**
* Takes in a value, casts it to an integer and then checks to make sure it is greater than zero.
* It is similar to the IsPositiveInt() function, but returns false on zero as well.
*
* @param mixed $val The value to have checked
* @return boolean Whether or not it is an integer above zero
*
* @see FilterInt()
* @see IsPositiveInt()
*/
public function IsIntGreaterThanZero($val){
$val = $this->FilterInt($val);
if($val > 0){
return true;
}else{
return false;
}
}
/**
* Takes in a value, casts it to an integer and then returns zero or above only.
*
* @param mixed $val The value to have cast and minimized to zero
* @return integer The returned number
*
* @see FilterInt()
*/
public function FilterIntGreaterThanZero($val){
$val = $this->FilterInt($val);
if($val > 0){
return $val;
}else{
return 0;
}
}
/**
* This function takes a string and makes sure the result is a filename and has no path information at all.
*
* @param string $filename The value to have filtered
* @return string The returned string without any path information
*
*/
public function FilterFilenameOnly($filename){
if(in_string('/', $filename)){
$filename = explode('/', $filename);
$pos = sizeof($filename)-1;
$filename = $filename[$pos];
}
while(in_string('..', $filename)){
$filename = str_replace('..', '.', $filename);
}
return $filename;
}
/**
* This takes in a string of csv (comma separted values), changes it to an array and removes any null, zero or blank entries.
* If the idNumberOnly flag is set it will not allow anything other than integer numbers greater than zero.
*
* @param string $csv The csv string to be cleaned
* @param boolean $idNumbersOnly Whether or not to only allow positive integers
* @return string A cleaned CSV with only valid values
*/
public function FilterCSV($csv,$idNumbersOnly=true){
$explode = explode(',', $csv);
if(is_array($explode)){
if($idNumbersOnly){
foreach($explode as $key=>$val){
$val = (int)$val;
if($val == 0){
$val = '';
}
$explode[$key] = $val;
}
}
$explode = CleanArray($explode);
}
if(sizeof($explode) < 1){
return '';
}else{
return implode(',',$explode);
}
}
/**
* An alias for the FilterCSV function but forces the idNumbersOnly to be off.
*
* @param string $csv The CSV string to be cleaned
* @return string The cleaned CSV string
*
* @see FilterCSV()
*/
public function FilterCSVText($csv,$idNumbersOnly=true){
return $this->FilterCSV($csv, false);
}
/**
* This takes a CSV string, cleans it and then returns it as an array, where FilterCSV() will return a string.
*
* @param string $csv The csv string to be cleaned
* @param boolean $idNumbersOnly Whether or not to only allow positive integers
* @return unknown
*/
public function FilterCsvToArray($csv,$idNumbersOnly=true){
$explode = explode(',', $csv);
if(is_array($explode)){
if($idNumbersOnly){
foreach($explode as $key=>$val){
$val = (int)$val;
if($val == 0){
$val = '';
}
$explode[$key] = $val;
}
}
$return = CleanArray($explode);
}else{
$return = array();
}
return $return;
}
/**
* This takes a array and converts it to a CSV string
*
* @param string $origArray The array string to be cleaned and converted to csv
* @param boolean $idNumbersOnly Whether or not to only allow positive integers
* @return unknown
*/
public function FilterArrayToCsv($origArray,$idNumbersOnly=true){
if(!is_array($origArray)){
$return = '';
}else{
if($idNumbersOnly){
foreach($origArray as $key=>$val){
$val = (int)$val;
if($val < 1){
$val = '';
}
$explode[$key] = $val;
}
}
$return = CleanArray($explode);
$return = implode(',', $return);
}
return $return;
}
/**
* Takes a value and options and checks to see if options has at least one of the values in the value list
*
* @param mixed $val Can be a string or array. Checks to see if any of them are in the $options
* @param array $options The values to check against
* @return boolean True if there is a match, false if there is not
*/
public function HasOneSelected($val, $options) {
if(is_array($val) && is_array($options)) {
foreach($val as $posted) {
if(!in_array($posted, $options) && !array_key_exists($posted, $options)) {
return false;
}
}
return true;
} else if(!is_array($options)) {
return false;
} else if(strlen($val) > 0 && (in_array($val, $options) || array_key_exists($val, $options))) {
return true;
}
return false;
}
/**
* Checks for duplicate category name, but this requires the work to be done beforehand within the category object itself, hence the very simply implementation within this function
*
* @param integer $total Returns false if the total is more than zero
* @return Boolean
**/
public function IsNotDuplicateCategory($total) {
if($total != 0) {
return false;
}
return true;
}
/**
* Wrapper function for htmlspecialchars() using the charset of this installation
*
* @param string $str The string to have converted to HTML entities
*
* @return string A string with html entities
*/
public function HTMLChars($str){
return htmlspecialchars($str, ENT_QUOTES, iwp_config::Get('charset'));
}
/**
* Will check WYSIWYG for content, will always return true in this PHP mode.
* Its used in javascript, but the validation methods run the functions both in javascript and PHP so we just need a dumby function.
*
* @param The content of the editor
* @return Boolean True
**/
public function GetWYSIWYGContent() {
return true;
}
/**
* This function checks to make sure the string passed in appears to be a valid time which can be (combined with a date) turned into a unix timestamp.
*
* The expected time format is that of the type that a jquery datepicker would produce in the admin, such as:
* 01:59 PM
*
* That is, a 12 hour clock, optional zero padding on the hour and a trailing AM/PM indicator
*
* @param stirng $string The string to be checked
* @param array $parts Provide an array which will be populated by this function with hour and minute values.
* @return boolean True if it appears to be a valid date, false otherwise.
*/
public function ParseTimeString ($string, &$parts) {
$string = trim($string);
$parts = null;
if (strlen($string) == 0) {
return true;
}
// time pattern check
if (preg_match('#^(\d{1,2}):(\d{2})\s*([AaPp][Mm])$#', $string, $matches) == 0) {
// no matches, not a valid time string
return false;
}
$hour = (int)$matches[1];
$minute = (int)$matches[2];
$pm = iwp_strtolower($matches[3]) == 'pm';
if ($hour < 1 || $hour > 12 || $minute < 0 || $minute > 59) {
// outside of valid time ranges
return false;
}
if (!$pm && $hour == 12) {
$hour = 0;
} else if ($pm && $hour < 12) {
$hour += 12;
}
$parts = array(
'hour' => $hour,
'minute' => $minute,
);
return true;
}
/**
* This function checks to make sure the string passed in appears to be a valid date which can be turned into a unix timestamp. d/m/y and m/d/y is supported, but is determined by the current short date format setting.
*
* @param string $string The string to be checked
* @param array $parts Provide an array which will be populated by this function with day, month and year values
* @return boolean True if it appears to be a valid date, false otherwise
*/
public function ParseDateString ($string, &$parts) {
$string = trim($string);
$parts = null;
if (strlen($string) == 0) {
return true;
}
// date pattern check
if (preg_match('#^(\d{1,2})[\/\-\.](\d{1,2})[\/\-\.](\d{2,4})$#', $string, $matches) == 0) {
// no matches, not a valid date string
return false;
}
$american = iwp_settings::IsAmericanDateFormat(iwp_getShortDateFormat());
if ($american) {
$day = (int)$matches[2];
$month = (int)$matches[1];
} else {
$day = (int)$matches[1];
$month = (int)$matches[2];
}
$year = (int)$matches[3];
if ($year <= 38) {
// 2 digit year, bump it up
$year += 2000;
} else if ($year < 100) {
// as above, but assume 1900's
$year += 1900;
}
$parts = array(
'day' => $day,
'month' => $month,
'year' => $year,
);
// internal PHP function that checks for valid dates
if (!checkdate($month, $day, $year)) {
return false;
}
// pass it into mktime to make sure it's within valid timestamp range
if (mktime(0, 0, 0, $month, $day, $year) === false) {
return false;
}
return true;
}
/**
* This function checks to make sure the string passed in appears to be a valid date which can be turned into a unix timestamp. d/m/y and m/d/y is supported, but is determined by the current short date format setting.
*
* @param string $string The string to be checked
* @return boolean True if it appears to be a valid date, false otherwise.
*/
public function ValidateDateString ($string) {
return $this->ParseDateString($string, $parts);
}
/**
* This function checks to make sure the string passed in is a valid email address
*
* @param string $email The string to check
*
* @return boolean True if its a valid email, false otherwise
*/
public function ValidEmail($email){
$validator = new Interspire_Validator_Email;
$validator->value = $email;
return $validator->isValid();
}
}
/**
* Shortcut function for use in templates.
*
* @see iwp_validation::FilterJavascriptString
*
* @param string $string Input string to filter
* @param boolean $quoted Optional, default is true. If set to true the returned string will include quotes, e.g. "string".
* @return string Returns the input string with all appropriate control characters escaped for javascript usage
* */
function iwp_FilterJavascriptString ($string, $quoted = true) {
return iwp_validation::FilterJavascriptString($string, $quoted);
}
/**
* Simple JS string escaping. Only escapes the things that break a string that is to be placed in single quotes. It removes new lines and escapes single quotes.
*
* @param string $string Input string to filter
* @return string Returns the input string with new lines gone and single quotes escaped. This does not return the surrounding quotes.
*
*/
function iwp_js ($string) {
$string = str_replace(array("\r", "\n"), "", $string);
$string = str_replace("'", "\'", $string);
return $string;
}