global $smarty;
global $storage;

$taxonomy 					= $this->getCollectionTaxonomy($CollectionID);
$FileFieldID 				= 0;
$CanMakeImageTransformation = 1;

foreach ($taxonomy as $k => $v)
{
	if ($v['CollectionInputType'] == 7)
	{
			$FileFieldID = $v['CollectionFieldId'];
	}
}

if ($FileFieldID > 0)
{
		$FieldName = $this -> _getCollectionFieldName($CollectionID, $FileFieldID);
		
		if (REMOTE_STORAGE == false)
		{
					//we need the upload to be properly made
					$error = $_FILES[$FieldName]['error'];
					
					if ($error != UPLOAD_ERR_OK) 
					{
							$CanMakeImageTransformation = 0;
					}
					
		}
		else
		{
					//we have to see if we can find the image
					$FileToTransform = $ColumnValues[$FieldName];
					
					$FileInfo = $storage->getFileByPath($FileToTransform);
					
					if (empty($FileInfo))
					{
							$CanMakeImageTransformation = 0;
					}
					else
					{
								  //row level access info
								  $user_id = isset($_SESSION['UserID'])?$_SESSION['UserID']:$_SESSION['AAuserid'];
								  //we set the user id for later use
								  $storage->setUserID($user_id);
								
								  $admin = false; 
								  if($_SESSION['FrontEndAdmin'] == 1)
								  {
									$admin = true;
								  }
								  
								  $storage->setAdmin($admin);
					
					}
					
					
		}
}
else
{
		$CanMakeImageTransformation = 0;
}



if ($CanMakeImageTransformation == 1)
{
	
	//we need to write different code if we have remote storage active or not
  	if (REMOTE_STORAGE == false)
	{
			
			//we get the directory where we are going to put the file
			
			$SiteCfg           	= $smarty -> config_load('admin.conf' , 'CollectionsUploadDirectory');
			$UploadDirectories 	= $smarty -> get_config_vars();
			$UploadDirectory 	= UPLOADED_FILES_DIR . $UploadDirectories['CollectionsUploadDirectory'];
	
	
			$collectionSettings  = $this->getCollectionSettings($CollectionID);
			if ($collectionSettings)
			{
				if (count($collectionSettings[2]) > 0)
				{
					$UploadSettings = $collectionSettings[2];
					$UploadDirName = UPLOADED_FILES_DIR . $UploadSettings['UploadDir'];
					
					if (file_exists($_SERVER['DOCUMENT_ROOT'].$UploadDirName) && $UploadDirName !='')
					{
							$UploadDirectory = $UploadDirName;
							
					}
				}
			}
	
	} //end if we have remote storage active
	
	
	$collection_table = $this->_getCollectionTableName($CollectionID);
	$FieldName = $this -> _getCollectionFieldName($CollectionID, 'ID');
	
	if (intval($RowID) == 0)
	{
			$q = "SELECT $FieldName FROM $collection_table WHERE 1 ORDER by $FieldName DESC LIMIT 1";
			$res = $this -> db-> query($q);
			if($res -> numRows() == 0)
			{
				$id = 1;
			}
			else
			{
				$row = $res -> fetchRow(DB_FETCHMODE_ASSOC);
				$id = $row[$FieldName] + 1;
			}
	}
	else
	{
			$id = $RowID;
			
			//delete the current file if we are editing
			$oldValues = $this-> getCollectionSingleRow (array('collection_id' =>$CollectionID , 'row_id' => $RowID)); 
			$oldFileColumnName = $this -> _getCollectionFieldName($CollectionID, $FieldID);
			
			if (REMOTE_STORAGE == false)
			{					
					if (file_exists($_SERVER['DOCUMENT_ROOT'].$oldValues[$oldFileColumnName]))
					{
						unlink($_SERVER['DOCUMENT_ROOT'].$oldValues[$oldFileColumnName]);
					}
			}
			else
			{
					//we simply delete it because we will create a brand new one
					$TransformedFileInfo = $storage->getFileByPath($oldValues[$oldFileColumnName]);
					
					if (!empty($TransformedFileInfo))
					{
							
							$storage->deleteFileById($TransformedFileInfo[$this -> _getCollectionFieldName(STORAGE_FILES_COLLECTION, 'ID')] , true );
							
					}
					
					
					
								
			} //end if remote storage delete
			
	}
				
	//we need to get the filename that we are going to use for this transformation			
	if (REMOTE_STORAGE == false)
	{	
			$FieldName = $this -> _getCollectionFieldName($CollectionID, $FileFieldID);
			
			$tmp_name 	= $_FILES[$FieldName]["tmp_name"];
			$name 		= $_FILES[$FieldName]["name"];

	}
	else
	{
			$tmp_name 	= $FileInfo[$this -> _getCollectionFieldName(STORAGE_FILES_COLLECTION, STORAGE_FILES_PATH_COLUMN)];
			$name 		= $FileInfo[$this -> _getCollectionFieldName(STORAGE_FILES_COLLECTION, STORAGE_FILES_FILENAME_COLUMN)];
	
	}//end if storage active 		
	
	
		
		$path_parts = pathinfo($name);
		
		if(!isset($path_parts['filename']))   {$path_parts['filename'] = substr($path_parts['basename'], 0, strrpos($path_parts['basename'], '.'));}
		

		$originalfilename = $path_parts['filename'].".".$path_parts['extension'];
		$originalextension = $path_parts['extension'];
		$newname	= $path_parts['filename'].'.flv';
		
		//we save this value for later use
		$ActualFileName = $newname;
		
		
		if (REMOTE_STORAGE == false)
		{
				$newname 	= $UploadDirectory . $this->getCollectionUploadFileName($UploadDirectory , $newname);
		}
		else
		{
				//we also need to copy the file to the temporary dir
				$tmp_name = $storage->copyFileFromStorageToTmpFolder( $FileInfo , UPLOADED_FILES_DIR . STORAGE_TMP_DIR , "tmp-".date(time())."-" . $originalfilename );		
				$ActualFileName = "tnail-" . $newname;
				$newname = UPLOADED_FILES_DIR . STORAGE_TMP_DIR . $newname;
				
				$tmp_name = $_SERVER['DOCUMENT_ROOT'].$tmp_name;
										
		}		
		
		
		
		
		//we need to make one more check before starting to convert
		if ($tmp_name != '')	
		{
		
						if (preg_match("/video/i", mime_content_type($tmp_name)) || ( (mime_content_type($tmp_name) == 'text/plain' ||  mime_content_type($tmp_name) == 'application/octet-stream' ) && ( strtoupper($originalextension) == 'WMV'  || strtoupper($originalextension) == 'MOV' || strtoupper($originalextension) == 'MP4' || strtoupper($originalextension) == 'AVI' )) )
						{
										
																			
										
										$ExecStatement = 'export PATH=$PATH:/usr/local/bin/; export LD_LIBRARY_PATH=/usr/local/lib/; ffmpeg -i '.$tmp_name.' -y -sameq '. $_SERVER["DOCUMENT_ROOT"] .$newname;
										exec ($ExecStatement , $a , $b);
										
																		  
						 }
						 
						
						 
						 if ( strtoupper($originalextension) == 'FLV')
						 {
								
								copy($tmp_name, $_SERVER["DOCUMENT_ROOT"] . $newname );
														 
						 
						 }
						 
						 
						 
		}//end if last check for a tmp file to transform
		 		
				

				   
		if (REMOTE_STORAGE == true)
		{
					//we have to delete the temp file to free up server space
					if (file_exists($tmp_name))
					{
							unlink($tmp_name);
					} //end if temp file exists
					
					if (file_exists($_SERVER['DOCUMENT_ROOT'].$newname))
					{
								
								//we need to send the file to storage
								
								 
								  
								    if (!$storage->CanUserAccessStorage())
									{
											$Value = $this->db->quote('');
											
									}
									
									$storageArray = array();
									$storageArray['ActualFileName'] = $ActualFileName;
									$storageArray['ActualFilePath'] = $_SERVER['DOCUMENT_ROOT'].$newname;
									
									$returnDetails = $storage-> SendFileToStorage ($storageArray);
									
									
									
									if (count($returnDetails['errors'])> 0)
									{
											$Value = $this->db->quote('');
											
									}
									
									
									
									$PathToTheUploadedFile 	= $returnDetails['path'];
									$UploadedFileName 		= $returnDetails['filename'];
									
									$FileTypeArray = array();
									$FileTypeArray['tmp_name'] = $_SERVER['DOCUMENT_ROOT'].$newname;
									$FileTypeArray['type'] = mime_content_type($_SERVER['DOCUMENT_ROOT'].$newname);
									
									$FileType = $storage -> getFileTypeFromFileUpload($FileTypeArray);
									
									
									$args = array();
									$args['FileName'] = $FileInfo[$this->_getCollectionFieldName(STORAGE_FILES_COLLECTION,STORAGE_FILES_NAME_COLUMN)] . ' ' .$TransformationSize . ' Tnail';
									$args['FileType'] = $FileType;
									$args['PathToTheUploadedFile'] 	= $PathToTheUploadedFile;	
									$args['UploadedFileName'] 		= $UploadedFileName;
									
									$FileUploadID 			= $storage->SaveUploadedFile($args);
									
									if (intval($FileUploadID) > 0)
									{
											$Value = $this->db->quote($PathToTheUploadedFile);
											
									}
									else
									{
											$Value = $this->db->quote('');
											
									}			
									
								 	unlink($_SERVER['DOCUMENT_ROOT'].$newname);
								
								
								
					} //end if temp file exists
					else
					{
								//we set an empty filename if failed to create the transformed file
								$Value = $this->db->quote('');
					}
					
					
		}
		else
		{
					//if file exists we send it to be saved
					if (file_exists($_SERVER['DOCUMENT_ROOT'].$newname))
					{
								$Value = $this->db->quote($newname);
					} //end if temp file exists
					else
					{
								//we set an empty filename if failed to create the transformed file
								$Value = $this->db->quote('');
					}
					
					
		}
		   
	
} //end if can make image transformation