<?php
/**
 *
 * Klasa validatora
 *
 */
class Validator extends UserValidator {
	/**
 * lista bledow
 *
 * @var array
 */
	private $errors = array();
	/**
     * lista validatorow
     *
     * @var array
     */
	private $validators = array();
	/**
     * validowane dane
     *
     * @var array
     */
	private $values = array();

	/**
     * konstruktor klasy
     * oczekuje danych w postaci array('nazwa_zmiennej'=>$wartosc, ...)
     *
     * @param array $data
     */
	public function __construct($data) {
		$this->ResetErrorList();

		$data = $this->Remover($data);

		$this->values = $data;
	}

	public function Remover($data) {

		if (!is_array($data)) {
			$data = rawurldecode($data);
			//            $data = Utils::url2pl($data);
		} else {
			$output = array();
			foreach($data as $key=>$val) {
				$output[$key]=self::Remover($val);
			}
			$data = $output;
		}

		return $data;
	}

	/**
     * Dodaje parametry dla validatora
     *
     * @param string $field
     * @param string $match
     * @param string $msg
     * @param array $data
     */
	public function AddValidator($field, $match, $msg, $data = null) {

		$this->validators[] = array('field'=>$field, 'match'=>$match, 'msg'=>$msg, 'data'=>$data);

	}

	/**
     * Resetuje liste bledow
     *
     */
	public function ResetErrorList() {
		$this->errors = array();
	}

	/**
     * dodaje dowolny blad do dowolnego pola
     *
     * @param string $field
     * @param string $msg
     */


	public function AddError($field,$msg,$value = '') {
		$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
	}

	/**
     * Zwraca zadana wartosc
     *
     * @param string|array $field
     * @return string
     */
	private function GetValue($field) {
		if(is_array($field)) {
			if(isset($this -> values[$field['name']][$field['key']])) {
				return $this -> values[$field['name']][$field['key']];
			}
		} else {
			if(isset($this->values[$field])) {
				return $this->values[$field];
			}
		}
	}

	public function IsBadLanguage($field,$msg,$alterField = null) {
		$value = $this->GetValue($field);
		if (RestrictedKeywordDAL::CheckBadLanguage($value)) {
			$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
			return false;
		}
		else {
			return true;
		}
	}

	/**
     * sprawdza czy niepusty
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsEmpty($field, $msg, $alternativeField = null) {
		$value = trim($this->GetValue($field));
		if (empty($value)) {
			$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
			if($field == 'city') {
				SessionProxy::SetValue('_city_limit_','');
			}
			return false;
		}
		else {
			if($field == 'city') {
				SessionProxy::SetValue('_city_limit_',html_entity_decode( $this->GetValue($field),ENT_NOQUOTES, 'UTF-8'));
			}
			return true;
		}
	}

	/**
     * musi byc pusty
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function OnlyEmpty($field, $msg, $alternativeField = null) {
		$value = $this->GetValue($field);
		if (trim($value) == "") {
			if($field == 'city') {
				SessionProxy::SetValue('_city_limit_',html_entity_decode( $this->GetValue($field),ENT_NOQUOTES, 'UTF-8'));
			}
			return false;
		}
		else {
			$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
			if($field == 'city') {
				SessionProxy::SetValue('_city_limit_','');
			}
			return true;
		}
	}

	/**
     * Sprawdzenie czy wartosc istnieje w bazie
     *
     * @param <type> $field
     * @param <type> $msg
     */
	public function IsInDatabase($field, $msg, $classDAL, $db_field_name) {
		$value = $this->GetValue($field);
		eval('$result = ' . $classDAL . 'DAL::GetResult(array($db_field_name => "'.$value.'"), array(), null, null, true);');
		if($result > 0) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		} else {
			return true;
		}

	}

	/**
     * Sprawdzenie czy wartosc istnieje w bazie
     *
     * @param <type> $field
     * @param <type> $msg
     */
	public function NotInDatabase($field, $msg, $classDAL, $db_field_name) {
		$value = $this->GetValue($field);
		eval('$result = ' . $classDAL . 'DAL::GetResult(array($db_field_name => \'"'.$value.'"\'), array(), null, null, true);');
		if($result == 0) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return true;
		} else {
			return false;
		}

	}

	/**
     * Metoda sprawdza czy dla danego wpisu isnieją powiązania zadanego typu w tabeli MfLink
     *
     * @param string $field - pole formularza
     * @param string $alternativeField - alternatywne pole
     * @param integer $srcId - id wpisu (artykuł, rapoty itp.)
     * @param string $srcType
     * @param string $destinationType
     * @param string $msg
     * @param string $classDAL
     * @return bool
     */
	public function IsInMfLink($field, $alternativeField = null, $srcId, $srcType, $destinationType, $msg) {

		$value = $this->GetValue($field);
		//$fields = array(
		//  'mf_link.id_source' => $srcId,
		// 'mf_link.source_type' => '"'.$srcType.'"',
		//  'mf_link.destination_type' => '"'.$destinationType.'"'
		//);
		//$result = MfLinkDAL::GetResult($fields, array(), null, null, true);

		//if($srcId == -1 && is_array($value)) $result = 1;
		if(isset($value) && is_array($value)) {
			$result = 1;
		} else {
			$result = 0;
		}

		if($result == 0) {
			if(is_null($alternativeField)) {
				$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			} else {
				$this->errors[] = array("field" => $alternativeField, "value" => $value, "msg" => $msg);
			}
			return false;
		} else {
			return true;
		}
	}

	/**
     * Sprawdzenie czy wartosci w bazie nie ma
     *
     * @param <type> $field
     * @param <type> $msg
     */
	public function IsntInDatabase($field, $msg, $classDAL, $db_field_name) {
		$value = $this->GetValue($field);
		eval('$result = ' . $classDAL . 'DAL::GetResult(array($db_field_name => $value), array(), null, null, true);');
		if($result > 0) {
			return true;
		} else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}

	}

	/**
     * Sprawdzenie czy numer PWZ jest w bazie
     *
     * @param <type> $field
     * @param <type> $msg
     */
	public function IsNotInDatabase($field, $msg, $db_field_name, $profileId = 0) {
		$value = $this->GetValue($field);
		$result = PhysicianDAL::GetResult(array($db_field_name=> addslashes($value), 'id_nm_physician' => array('condition' => '!=', 'value' => $profileId)), array(), null, null, true);
		if($result == 0) {
			return true;
		} else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
		}

	}

	/**
     * sprawdza czy zaznaczony
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsChecked($field, $msg, $fieldId) {
		$value = $this->GetValue($field);
		if (trim($value) != "on") {
			if(is_null($fieldId)) {
				$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			}else {
				$this->errors[] = array("field" => $fieldId, "value" => $value, "msg" => $msg);
			}

			return false;
		}
		else {
			return true;
		}
	}


	/**
     * Sprawdza czy string
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsString($field, $msg) {
		$value = $this->GetValue($field);
		if(!is_string($value)) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
		else {
			return true;
		}
	}

	/**
     * Sprawdza czy liczba
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsNumber($field, $msg) {
		$value = $this->GetValue($field);
		if(!is_numeric($value)) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
		else {
			return true;
		}
	}


	/**
     * Sprawdza czy calkowite
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsInteger($field, $msg) {
		$value = $this->GetValue($field);
		if(!is_integer($value)) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
		else {
			return true;
		}
	}


	/**
     * Sprawdza czy zmiennoprzecinkowa
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsFloat($field, $msg) {
		$value = $this->GetValue($field);
		if(!is_float($value)) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
		else {
			return true;
		}
	}


	/**
     * Sprawdza czy literowe
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsAlpha($field, $msg) {
		$value = $this->GetValue($field);
		$pattern = "/^[a-zA-Z]+$/";
		if(preg_match($pattern, $value)) {
			return true;
		}
		else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
	}

	public function isDate($field,$msg, $alternativeField=null) {
		$value = $this->GetValue($field);
		$pattern = "/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/";
		if (preg_match($pattern,$value))
		return true;
		else {
			$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
			return false;
		}
	}

	public function isHour($field,$msg,$alternativeField=null) {
		$value = $this->GetValue($field);
		$pattern = "/([0-9]|[0-1][0-9]|[2][0-4]):([0-5][0-9])/";
		if (preg_match($pattern,$value))
		return true;
		else {
			$this->errors[] = array("field" => (isset($alternativeField)?$alternativeField:$field), "value" => $value, "msg" => $msg);
			return false;
		}
	}

	public function IsPrevDate($field, $msg) {
		$value = $this->GetValue($field);

		$date_prev = strtotime($value);

		if($date_prev > time()) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
		else
		return true;
	}

	public function isGoodLogin($field,$msg) {
		$value = $this->GetValue($field);
		//		echo mb_detect_encoding($value);
		//		if( mb_detect_encoding($value) == "UTF-8")
		//$value = iconv("utf-8", "iso-8859-2", $value);

		$len = "{" . strlen($value) . "}";

		$pattern = "^[a-zA-Z0-9_��������桦���Ư�� \+\-]$len$";
		//!@\$%\*\(\)\^\-
		if(strlen($value)>=3  && strlen($value)<=15 && ereg($pattern,$value,$matches)) {
			//var_dump($matches);
			return true;
		}
		else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
	}

	public function isGoodPassword($field,$msg) {
		$value = $this->GetValue($field);
		if(strlen($value) >= 6)
		return true;
		else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
	}
	/**
     * Sprawdza czy w przedziale
     *
     * @param string $field
     * @param string $msg
     * @param integer $min
     * @param integer $max
     * @return boolean
     */
	public function IsWithinRange($field, $msg, $min, $max) {
		$value = $this->GetValue($field);
		if(!is_numeric($value) || $value < $min || $value > $max) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
		else {
			return true;
		}
	}

	/**
     * Sprawdza czy email
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsEmailAddress($field, $msg) {
		$value = $this->GetValue($field);
		$pattern = "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/";
		if(preg_match($pattern, $value)) {
			return true;
		}
		else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
	}

	/**
     * Sprawdza czy oba pola sa takie sam
     *
     * @param string $field1
     * @param string $field2
     * @param string $msg
     * @return boolean
     */
	public function IsNotEqual($field1,$field2, $msg) {
		$value1 = $this->GetValue($field1);
		$value2 = $this->GetValue($field2);

		if($value1 == $value2) {
			return true;
		}
		else {
			$this->errors[] = array("field" => $field2, "value" => "", "msg" => $msg);
			return false;
		}
	}

	/**
     * Sprawdza czy oba pola sa takie sam
     *
     * @param string $field1
     * @param string $field2
     * @param string $msg
     * @return boolean
     */
	public function IsEqual($field1,$field2, $msg) {
		$value1 = $this->GetValue($field1);
		$value2 = $this->GetValue($field2);

		if($value1 != $value2) {
			return true;
		}
		else {
			$this->errors[] = array("field" => $field2, "value" => "", "msg" => $msg);
			return false;
		}
	}

	public function IsEqualValue($field, $value, $msg) {
		$value1 = $this->GetValue($field);

		if($value1 != $value) {
			return true;
		}
		else {
			$this->errors[] = array("field" => $field, "value" => "", "msg" => $msg);
			return false;
		}
	}

	public function IsNotEqualValue($field, $value, $msg) {
		$value1 = $this->GetValue($field);
//Utils::ArrayDisplay($value1.' == '. $value);
		if($value1 == $value) {
			return true;
		}
		else {
			$this->errors[] = array("field" => $field, "value" => "", "msg" => $msg);
			return false;
		}
	}



	/**
     * Zwraca liste bledow
     *
     * @return array
     */
	public function GetErrorList() {
		return $this->errors;
	}

	/**
     * Zwraca liczbe bledow
     *
     * @return integer
     */
	public function IsError() {
		if (sizeof($this->errors) > 0) {
			return sizeof($this->errors);
		}
		else {
			return false;
		}
	}



	public function CheckCaptcha($field,$msg) {
		$value1 = $this->GetValue($field);
		
		$value2 = Request::GetCookie(CAPTCHA_COOKIE_NAME, false);
		//$value2 = $_SESSION[CAPTCHA_COOKIE_NAME];

		//Utils::ArrayDisplay($value1);
		//Utils::ArrayDisplay($value2);
		if(md5(strtolower($value1) . CAPTCHA_SEED) == $value2)
		return true;
		else {
			$this->errors[] = array("field" => 'captcha', "value" => $value1, "msg" => $msg);
			return false;
		}


	}


	public function IsFile($field,$msg) {
		$value = $this->GetValue($field);
		if(is_file($value)) {
			return true;

		}
		else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
	}

	public function IsGoodImageFormat($field,$msg) {
		$value = $this->GetValue($field);
		switch ($value) {
			default:
				$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
				return false;
				break;
			case 'image/pjpeg':
				break;
			case 'image/gif':
				break;
			case 'image/jpeg':
				break;
			case 'image/png':
				break;
			case 'image/x-png':
				break;
		}
	}

	public function IsValidFeed($field, $msg) {
		$value = $this->GetValue($field);
		$value = str_replace('&lt;x&gt;','',$value);
		if(empty($value)){
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);

		}else{

			$feed = new FeedReader($value);
			$feed->init();
			$feed->handle_content_type();

			if ($feed->error()){
				$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);

			} else {
				return true;
			}
		}

	}

	/**
     * Sprawdzenie czy numer specjalizacja jest w bazie
     *
     * @param <type> $field
     * @param <type> $msg
     */
	public function IsInDatabaseSpecialty($field, $msg, $db_field_name) {

		$value = $this->GetValue($field);
		if(is_array($value))foreach($value AS $k => $val) {

			if(strlen($val) == 0) {

				//            			$this->errors[] = array("field" => 'speciality_'.$k.'', "value" => $val, "msg" => 'To pole nie może być puste');
				$this->errors[] = array("field" => $field.'['.$k.']', "value" => $val, "msg" => 'To pole nie może być puste');
				//					$this->errors[] = array("field" => $field.'_'.$k, "value" => $val, "msg" => 'To pole nie może być puste');

			}else {

				$result = SpecialtyDAL::GetResult(array($db_field_name=> addslashes($val)), array(), null, null, true);
				if($result > 0) {
					return true;
				} else {

					//     	    				$this->errors[] = array("field" => 'speciality_'.$k.'', "value" => $val, "msg" => $msg);
					$this->errors[] = array("field" => $field.'['.$k.']', "value" => $val, "msg" => $msg);
					//						$this->errors[] = array("field" => $field.'_'.$k, "value" => $val, "msg" => $msg);


				}
			}
		}
	}

	/**
     * Sprawdzenie czy numer specjalizacja jest w bazie
     *
     * @param <type> $field
     * @param <type> $msg
     */
	public function IsInDatabaseArticleCategory($field, $msg, $id) {
		$val = $this->values['name'];
		$result = MfArticleCategoryDescriptionDAL::GetResult(array('name'=> addslashes($val)), array(), null, null, true);
		if($result > 0 && $val != '') {
			if($id == -1) {
				$this->errors[] = array("field" => $field, "value" => $val, "msg" => $msg);
				return count($result);
			}
		} else {
			return false;
		}
	}

	public function IsNotProvince($field,$msg,$db_field_name = null) {
		$value = $this->GetValue($field);
		$sql = 'SELECT COUNT(*) AS count FROM nmd_province WHERE name LIKE "'.$value.'"';
		$result = Registry::Get('db')->prepare($sql)->execute()->FetchAllAssoc();
		if(intval($result[0]['count']) == 0) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
		}
	}

	public function IsNotCity($field,$msg,$db_field_name = null) {
		$value = $this->GetValue($field);
		$sql = 'SELECT COUNT(*) AS count FROM nmd_city WHERE name LIKE "'.$value.'"';
		$result = Registry::Get('db')->prepare($sql)->execute()->FetchAllAssoc();
		if(intval($result[0]['count']) == 0) {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
		}
	}

	public function IsArray($field, $msg, $fieldId = null) {

		$value = $this->GetValue($field);
		if(is_array($value) && !empty($value)) {
			return true;
		}
		else {
			if(is_null($fieldId)) {
				$this->errors[] = array("field" => $field."[0]", "value" => $value, "msg" => $msg);
				$this->errors[] = array("field" => $field."[1]", "value" => $value, "msg" => $msg);
				$this->errors[] = array("field" => $field."[2]", "value" => $value, "msg" => $msg);
			}else {
				$this->errors[] = array("field" => $fieldId, "value" => $value, "msg" => $msg);
			}
			return false;
		}
	}

	/**
     * Waliduje dane przy pomocy wprowadzonych validatorow
     *
     */
	public function Validate() {
		foreach($this->validators as $validator) {
			if(isset($validator['field']) && isset($validator['match']) && isset($validator['msg'])) {
				if($validator['match'] == 'empty') {
					$this->IsEmpty($validator['field'], $validator['msg']);
				} else if ($validator['match'] == 'string') {
					$this->IsString($validator['field'], $validator['msg']);
				} else if ($validator['match'] == 'number') {
					$this->IsNumber($validator['field'], $validator['msg']);
				} else if ($validator['match'] == 'integer') {
					$this->IsInteger($validator['field'], $validator['msg']);
				} else if ($validator['match'] == 'float') {
					$this->IsFloat($validator['field'], $validator['msg']);
				} else if ($validator['match'] == 'alpha') {
					$this->IsAlpha($validator['field'], $validator['msg']);
				} else if ($validator['match'] == 'range') {
					$this->IsWithinRange($validator['field'], $validator['msg'], $validator['data']['min'], $validator['data']['max']);
				} else if ($validator['match'] == 'email') {
					$this->IsEmail($validator['field'], $validator['msg']);
				}
			}
		}
	}

	public function CheckDimensions($file, $width, $height) {
		//Utils::ArrayDisplay($file);
		$dimensions = getimagesize($file['tmp_name']);
		$img_width = $dimensions[0];
		$img_height = $dimensions[1];
		if($img_width != $width || $img_height != $height) {
			$this->errors[] = array("field" => $field, "value" => $val, "msg" => $msg);
			return false;
		} else {
			return true;
		}
	}

	/**
     * Sprawdza czy email
     *
     * @param string $field
     * @param string $msg
     * @return boolean
     */
	public function IsPostalCode($field, $msg) {
		$value = $this->GetValue($field);
		$pattern = "/^[0-9]{2}[-][0-9]{3}$/";
		if(preg_match($pattern, $value)) {
			return true;
		}
		else {
			$this->errors[] = array("field" => $field, "value" => $value, "msg" => $msg);
			return false;
		}
	}
	public function setValues($data) {
		$this->values = $data;
	}
}

                        ?>