<?
////////////////////////////////////////////////////
// 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");
session_name(SYS_APP_SESSNAME);
session_start();
include("../conf/connections.php");
class FileOps{
	public $resId='';
	public $recId=NULL;
	private $sql=array();
	
	function FileOps($param=NULL){
		if($param==NULL) die("Fatal error (FileOps class): No current resource specified.");
		$this->resId=$param;
	}	

	function prepareFile($value,$nodo,$action,$oldvalue=NULL){
		if($nodo['class']!="file" && $nodo['class']!="imageprocess") return false;
		$value=$this->convertName($value);										
		$rutabase="../../" . SYS_BASE_UPLOAD;									
		$rutadestino=$rutabase . $nodo->uploaddir . "/";						
		$tmpname="../../" . SYS_TEMP_UPLOADS . session_id() . "_" . $value;		
		$destname=$this->getUniqueName($rutadestino . $value);					
		$resultado=true;
		$subtype=$nodo->subtype;												
		$campo=(string)$nodo['name'];											
		$finfo=$this->getPhysicalFileInfo($tmpname);							
		

		if($_SESSION['uploads'][$this->resId][$campo]!=NULL){
			if($action=="edit"){
				$sql="SELECT * FROM " . SYS_MEDIA_TABLE . " WHERE idres='" . $this->resId . "' AND idrec=" . $this->recId . " AND field='$campo'";
				$q1=mysql_query($sql) or die($sql);
				while($f1=mysql_fetch_assoc($q1)){
					if($f['readonly']!=1){		
						if($f['shared']==1){	
						}
						@unlink($f1['filename']);
						mysql_query("DELETE FROM " . SYS_MEDIA_TABLE . " WHERE id={$f1['id']}");
					}
				}
			}
			if($value==NULL || $value=='') return;
		}else if($_SESSION['uploads'][$this->resId][$campo]==NULL){
			if($action=="edit" && ($value=='' || $value==NULL)){
				$sql="SELECT * FROM " . SYS_MEDIA_TABLE . " WHERE idres='" . $this->resId . "' AND idrec=" . $this->recId . " AND field='$campo'";
				$q1=mysql_query($sql);
				while($f1=mysql_fetch_assoc($q1)){
					if($f['readonly']!=1){		
						if($f['shared']==1){	
						}
						@unlink($f1['filename']);
						mysql_query("DELETE FROM " . SYS_MEDIA_TABLE . " WHERE id={$f1['id']}");
					}
				}
			}
		}


		if($action=="edit"){
			$sql="SELECT * FROM " . SYS_MEDIA_TABLE . " WHERE idres='" . $this->resId . "' AND idrec=" . $this->recId . " AND field='$campo'";
			$q=mysql_query($sql);
			if(mysql_num_rows($q)>0){
				while($f=mysql_fetch_assoc($q)){
					if($f['readonly']==1){
					}else{
						if(!file_exists($tmpname)) return;
						$this->generateVersions($value,$nodo,$action,$rutadestino);				
						@unlink($f['filename']);												
						mysql_query("DELETE FROM" . SYS_MEDIA_TABLE . "WHERE id={$f['id']}");	
					}
				}
			}else{
				if(!file_exists($tmpname)) return;
				$this->generateVersions($value,$nodo,$action,$rutadestino);		
				
			}
		}else{
			if(!file_exists($tmpname)) return;
			$this->generateVersions($value,$nodo,$action,$rutadestino);		
			
		}
		
		
		if((string)$nodo->maintain_original!='false'){
			$resultado=copy($tmpname,$destname);
			$this->sql[]="INSERT INTO " . SYS_MEDIA_TABLE . "(dateuploaded, idres, idrec, field, filename, folder, alt, longdesc, icon, version, metadata, temp, shared, readonly, type, ext, iduser, size, width, height, duration) VALUES(NOW(), '" . $this->resId . "', " . ($action=="insert" ? "NULL" : $this->recId) . ", '$campo', '" . ($destname) . "', '" . $version['uploaddir'] . "', '', '', NULL, '', '', " . ($action=="insert" ? 1 : 0) . ", 0, 0, '$subtype', '" . $finfo['extension'] . "', " . $_SESSION[session_id()]['id'] . ", " . filesize($destname) . ", NULL, NULL, NULL)";
		}
		if($resultado) unlink($tmpname);
		
		foreach($this->sql as $sentencia){
			$q=mysql_query($sentencia);
		}
	}
	
	private function generateVersions($value,$nodo,$action,$rutadestino){
		foreach($nodo->version as $version){
			$temp=explode(".",$value);
			$ext=array_pop($temp);
			$newname=$version['prefix'] . implode(".",$temp) . $version['suffix'].".".$ext;
			$subtype=$nodo->subtype;
			$tmpname="../../" . SYS_TEMP_UPLOADS . session_id() . "_" . $value;
			$campo=(string)$nodo['name'];
			ini_set("memory_limit","128M");
			if(!is_dir($rutadestino . $version['uploaddir'])){mkdir($rutadestino . $version['uploaddir']);};
			switch($subtype){
				case "image":
				case "all":		
					if(substr($value,-3,3)=="swf") break;		
					$th=new Thumbnail($tmpname);
					if(isset($version['width']) && isset($version['height'])){
						$th->size((int)$version['width'],(int)$version['height']);
					}else{
						if(isset($version['width'])) $th->size_width((int)$version['width']);
						if(isset($version['height'])) $th->size_height((int)$version['height']);
					}
					$th->process();
					$temp=$th->dump();
					$q=isset($version['quality']) ? (int)$version['quality'] : 90;
					imagejpeg($temp,$rutadestino.$version['uploaddir']."/".$newname,$q);/**/
					break;
				case "document":
					break;
				default:
					break;
			}
			$this->sql[]="INSERT INTO " . SYS_MEDIA_TABLE . "(dateuploaded, idres, idrec, field, filename, folder, alt, longdesc, icon, version, metadata, temp, shared, readonly, type, ext, iduser, size, width, height, duration) VALUES(NOW(), '" . $this->resId . "', " . ($action=="insert" ? "NULL" : $this->recId) . ", '$campo', '" . ($rutadestino.$version['uploaddir']."/".$newname) . "', '" . $version['uploaddir'] . "', '', '', NULL, '" . $version['prefix'] . "', '', " . ($action=="insert" ? 1 : 0) . ", 0, 0, '$subtype', '$ext', " . $_SESSION[session_id()]['id'] . ", " . filesize($rutadestino.$version['uploaddir']."/".$newname) . ", NULL, NULL, NULL)";
		}
	}
	
	private function convertName($param){
		$param=utf8_decode($param);
		$param=str_replace(" ","_",$param);
		return $param;
	}
	
	public function getPhysicalFileInfo($ruta){
		if(!file_exists($ruta)) return false;
		$archivo=array();
		$partes=pathinfo($ruta);
		$archivo['dirname']=$partes['dirname'];
		$archivo['basename']=$partes['basename'];
		$archivo['extension']=$partes['extension'];
		$archivo['filename']=$partes['filename'];
		$archivo['size']=filesize($ruta);
		$archivo['ctime']=filectime($ruta);
		return $archivo;
	}
	
	public function getFullFileInfo($id){
		$sql="SELECT * FROM " . SYS_MEDIA_TABLE . " WHERE id=$id";
		$q=mysql_query($sql);
		$f=mysql_fetch_assoc($q);
		return $f;
	}
	
	public function getUniqueName($filename){
		if(!file_exists($filename)) return $filename;
		$partes=pathinfo($filename);
		$pattern = '/.+(\[([0-9]*?)\])\..+/';
		preg_match_all($pattern, $filename, $matches);
		if(count($matches[0])==0){
			$temp=explode(".", $filename);
			$temp[count($temp)-2].="[1]";
			$filename=implode(".",$temp);
			$filename=$this->getUniqueName($filename);
		}else{
			$index=(int)$matches[2][0];
			$index++;
			$filename=str_replace($matches[1][0],"[".$index."]",$filename);
			$filename=$this->getUniqueName($filename);
		}
		return $filename;
	}
}







?>