<?
////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////


include("../conf/preferences.php");
include("../conf/connections.php");
session_name(SYS_APP_SESSNAME);
session_start();
class Validation{
	public $xml;			
	public $xmldoc;			
	public $data=NULL;		
	public $values=NULL;	
	public $errors=NULL;	
	public $action=NULL;	
	private $current=NULL;	
	
	private function parseDate($value){
		$temp=explode(" ", $value);
		$fecha=explode("/",$temp[0]);
		$pattern=implode("",explode("/",CAL_DATE_FORMAT));
		$yuyu=$fecha[strripos($pattern,"Y")] . "-" . $fecha[strripos($pattern,"m")] . "-" . $fecha[strripos($pattern,"d")];
		if($temp[1]!=NULL) $yuyu.=" " . $temp[1];
		return $yuyu;
	}
	
	function Validation($param){
		if(!isset($param) || $param==NULL) die("Fatal error: Validation class not properly initialized.");
		$this->xml=$param->xpath('//validation/parent::*');
		$this->xmldoc=$param;
	}
	
	function proceed(){
		if($this->values==NULL || $this->data==NULL) die("Fatal error: Validation class needs values to operate on.");
		if($this->xml==NULL) return;
		foreach($this->xml as $item){
			$this->current=$item;
			$param=$this->values[(string)$item['name']];
			foreach($item->validation as $val){
				$valid=true;
				if(($item['multilang']=="true")){
					global $lngs;
					foreach($lngs as $lng=>$conf){
						$param=$_POST[$item['name']."_h_".$lng];
						if(method_exists($this,$val['type'])){
							$valid=$this->{(string)$val['type']}($param,$val);
							if($valid==false){
								$this->errors[(string)$item['name']].=str_replace("{@lang}",$conf['name'],$val['errortext'])."<br />";
								break;
							}
						}
					}
				}else{
					if(method_exists($this,$val['type'])) $valid=$this->{(string)$val['type']}($param,$val);
					if($valid==false){
						$this->errors[(string)$item['name']]=(string)$val['errortext'];
						break;
					}
				}
			}
		}
		$pass=$this->xmldoc->xpath('//control[@class="password"][hidden="true"]');
		foreach($pass as $item){
			$n1=$_POST[(string)$item['name']];
			$n2=$_POST[(string)$item['name']."_2"];
			if($n1 != $n2) $this->errors[(string)$item['name']]=PASSCTRL_NOMATCH;
		}
	}
	
	
	
	private function required($param,$val){
		if($this->current['class']=="password" && $_SERVER['REQUEST_METHOD']=='POST'){
			$sess=$_SESSION['form'][$_REQUEST['resId']]; $action=$sess['_action'];
			if($action=="insert"){
				return $param!='';
			}else if ($action=="edit" && $_POST[$this->current['name']."_check"]!="1"){
				return $param!='';
			}else{
				return true;
			}
		}else{
			return $param!='';
		}
	}
	
	
	private function isNumeric($param,$val){
		if($val['params']=='null'){
			return (is_numeric($param) || $param=='');
		}else{
			return is_numeric($param);
		}
	}
	
	
	private function isBoolean($param,$val){
		return ($param=="1" || $param=="0" || strtolower($param)=="true" || strtolower($param)=="false");
	}
	
	
	private function isEmail($param,$val){
		if(@eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $param) || ($val['params']=='null' && $param=='')) {
			return true;
		}else {
			return false;
		}	
	}
	
	
	private function isURL($param,$val){
		if(@eregi("(https?|ftp|file)://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", $param) || ($val['params']=='null' && $param=='')) {
			return true;
		}else {
			return false;
		}	
	}
	
	
	private function isValidIP($param,$val){
		if(ip2long($param)) {
			return true;
		}else {
			return false;
		}	
	}
	
	
	private function regexp($param,$val){
		$regex=(string)$val->regex;
		if (preg_match($regex, $param)) {  
			return true;  
		}else {  
			return false;  
		} 	
	}
	
	
	private function moreThan($param,$val){
		$value=$val['params'];
		return (float)$param>=(float)$value;
	}
	
	
	private function lessThan($param,$val){
		$value=$val['params'];
		return (float)$param<=(float)$value;
	}
	
	
	private function between($param,$val){
		$temp=explode(",",$val['params']);
		if((float)$param>=(float)$temp[0] && (float)$param<=(float)$temp[1]){
			return true;
		}else{
			return false;
		}
	}
	
	
	private function equal($param,$val){
		return $param!=(string)$val['params'];
	}
	
	
	private function notEqual($param,$val){
		return $param!=(string)$val['params'];
	}
	
	
	private function isUnique($param,$val){
		if($val['params']=='nullable' && $param=='') return true;
		
		$tabla=(string)$this->data->table;								
		$campo=(string)$this->current['name'];							
		$campoclave=(string)$this->data->field_key;	
		$comillas=(string)$this->current['type']=="string" ? "'" : "";	
		$modo=$this->action;
		$clave=$this->values[$campoclave];
		$cadena="SELECT * FROM $tabla WHERE $campo={$comillas}$param{$comillas}";
		if($modo=='edit') $cadena.=" AND $campoclave <> '$clave'";
		$q=mysql_query($cadena) or die(mysql_error()."<br />$cadena");
		return (mysql_num_rows($q)==0);
	}
	
	
	private function minStrength($param, $val){
		$campo=(string)$this->current['name'];
		if($this->action=="edit"){
			if($_POST[$campo."_check"]=="1") return true;
		}
		$fuerza=0;
		if(strlen($param)>6) $fuerza++;
		if(strlen($param)>9) $fuerza++;
		if(preg_match("/[A-Z]/",$param)>0) $fuerza++;
		if(preg_match("/[a-z]/",$param)>0) $fuerza++;
		if(preg_match("/[0-9]/",$param)>0) $fuerza++;
		return $fuerza>=(int)$val['params'];
	}
	
	
	private function validExtension($param,$val){
		$exts=explode(",",(string)$val['params']);
		$ext = substr(($t=strrchr($param,'.'))!==false?$t:'',1);
		return in_array($ext,$exts);
	}
	
	
	private function fileSize($param,$val){
		
	}
	
	
	private function len($param,$val){
		$caracteres=(int)$val['params'];
		return strlen($param)<=$caracteres;
	}
	
	
	private function match($param,$val){
		$otrocampo=(string)$val['params'];
		return $this->values[$otrocampo] == $param;
	}
	
	
	private function nomatch($param,$val){
		$otrocampo=(string)$val['params'];
		return $this->values[$otrocampo] != $param;
	}
	
	
	private function contains($param,$val){
		$needle=(string)$val['params'];
		return (stripos($param,$needle)!==false);
	}
	
	
	private function notContains($param,$val){
		$needle=(string)$val['params'];
		return (stripos($param,$needle)===false);
	}
	
	
	
	private function isValidDate($param,$val){
		if($param=='' || $param==NULL) return true;		
		return strtotime($fecha)!==false;
	}
	
	
	private function dateGreaterThan($param,$val){
		$f1=strtotime((string)$val['params']);
		$fecha=strtotime($this->parseDate($param));
		return $fecha>$f1;
	}
	
	
	private function dateLowerThan($param,$val){
		$f1=strtotime((string)$val['params']);
		$fecha=strtotime($this->parseDate($param));
		return $fecha<$f1;
	}
	
	
	private function dateBetween($param,$val){
		$fechas=explode(",",(string)$val['params']);
		$f1=strtotime($fechas[0]);
		$f2=strtotime($fechas[1]);
		$f=strtotime($this->parseDate($param));
		return ($f>$f1 && $f<$f2) ? true : false;
	}
	

	private function dateNotBetween($param,$val){
		$fechas=explode(",",(string)$val['params']);
		$f1=strtotime($fechas[0]);
		$f2=strtotime($fechas[1]);
		$f=strtotime($this->parseDate($param));
		return ($f>$f1 && $f<$f2) ? false : true;
	}
}
?>