<?php
/*************************************************** 
* FileUpload Component 
* 
* Manages uploaded files to be saved to the file system. 

*/ 
class FileUploadComponent extends Component { 
 
  var $fileModel = 'File'; 

  var $fileDir = 'documents'; 
  var $imageDir = 'profile'; 

  var $imageAllowedTypes = array( 
    'image/jpeg', 
    'image/gif', 
    'image/png', 
    'image/pjpeg', 
    'image/x-png' 
  ); 
  
  var $fields = array('name'=>'name','type'=>'type','size'=>'size'); 
 
  var $uploadedFile = false; 
 
  var $data = array(); 
  var $params = array(); 
   
  var $fileName = null; 
  

  
  var $entity = null; 
  var $entity_id = null; 
   

  var $success = false; 
  var $uploadDetected = false; 
 
  var $errors = array(); 
  var $fileVar = array();
  /*************************************************** 
    * Initializes FileUploadComponent for use in the controller 
    * 
    * @param object $controller A reference to the instantiating controller object 
    * @return void 
    * @access public 
    */ 
  function initialize(Controller $controller = null){ 
    $this->data = $controller->data; 
    $this->params = $controller->params;	
  } 
  /*************************************************** 
    * Main execution method.  Handles file upload automatically upon detection and verification. 
    * 
    * @param object $controller A reference to the instantiating controller object 
    * @return void 
    * @access public 
    */ 
  function startupFile($files, $entity, $entity_id =0){ 
	$this->uploadedFile = $files;
	$this->entity = $entity;
	$this->entity_id = $entity_id;
    $this->_processFile(); 
  } 
   

  function removeFile($name = null){ 
    if(!$name) return false; 
     
    $up_dir = WWW_ROOT .'files'. DS. $this->fileDir .DS; 
    $target_path = $up_dir .  $name; 
    if(unlink($target_path)) return true; 
    else return false; 
  }  
  
  function removeImage($name = null){ 
    if(!$name) return false; 
     
    $up_dir = WWW_ROOT .'files'. DS. $this->imageDir .DS; 
    $target_path = $up_dir .  $name; 
    if(unlink($target_path)) return true; 
    else return false; 
  } 
   

  function showErrors($sep = "<br />"){ 
    $retval = ""; 
    foreach($this->errors as $error){ 
      $retval .= "$error $sep"; 
    } 
    return $retval; 
  } 

  function _processFile(){ 
    $up_dir = WWW_ROOT .'files'. DS. $this->fileDir .DS; 
    $target_path = $up_dir . $this->uploadedFile['name']; 
    $temp_path = substr($target_path, 0, strlen($target_path) - strlen($this->_ext())); //temp path without the ext 
    //make sure the file doesn't already exist, if it does, add an itteration to it 
        $i=1; 
        while(file_exists($target_path)){ 
            $target_path = $temp_path . "-" . $i . $this->_ext(); 
            $i++; 
        } 
     
    $save_data = array(); 
    if(move_uploaded_file($this->uploadedFile['tmp_name'], $target_path)){ 
      //Final File Name 
      $this->finalFile = basename($target_path); 
      $model =& $this->getModel(); 
      $save_data['File'][$this->fields['name']] = $this->finalFile; 
      $save_data['File'][$this->fields['type']] = $this->uploadedFile['type']; 
      $save_data['File'][$this->fields['size']] = $this->uploadedFile['size']; 
	  $save_data['FileRelation']['entity_id'] = $this->entity_id;
	  $save_data['FileRelation']['entity_type'] = $this->entity;

	  $fileData = $model->saveAssociated($save_data);
	
      if(!$model || $fileData){ 
		
        $this->success = true; 
      } 
      else{ 
        $this->success = false; 
      } 
    } 
    else{ 
      $this->_error('FileUpload::processFile() - Unable to save temp file to file system.'); 
    } 
  } 
   
  /*************************************************** 
    * Returns a reference to the model object specified, and attempts 
    * to load it if it is not found. 
    * 
    * @param string $name Model name (defaults to FileUpload::$fileModel) 
    * @return object A reference to a model object 
    * @access public 
    */ 
    function &getModel($name = null) { 
        $model = null; 
        if (!$name) { 
            $name = $this->fileModel; 
        } 
     
    if($name){ 
		 $model = ClassRegistry::init($name); 
        if (empty($model) && $this->fileModel) { 
			$this->_error('FileUpload::getModel() - Model is not set or could not be found'); 
			return null; 
		} 
    } 
        return $model; 
    } 
   
  /*************************************************** 
    * Adds error messages to the component 
    * 
    * @param string $text String of error message to save 
    * @return void 
    * @access protected 
    */ 
  function _error($text){ 
    $message = __($text,true); 
    $this->errors[] = $message; 
    trigger_error($message,E_USER_WARNING); 
  } 
   
  /*************************************************** 
    * Checks if the uploaded type is allowed defined in the allowedTypes 
    * 
    * @return boolean if type is accepted 
    * @access protected 
    */ 
  function _checkType(){ 
    foreach($this->allowedTypes as $value){ 
      if(strtolower($this->uploadedFile['type']) == strtolower($value)){ 
        return true; 
      } 
    } 
    $this->_error(""); 
    return false; 
  } 

  /*************************************************** 
    * Returns the extension of the uploaded filename. 
    * 
    * @return string $extension A filename extension 
    * @access protected 
    */ 
  function _ext(){ 
    return strrchr($this->uploadedFile['name'],"."); 
  } 
 
} 