<?php

class PG_Controller_Plugin_UploadloadFile
extends Zend_Controller_Plugin_Abstract
{
        public $enabled = true;

	public $files = null;

	public $file = null;

	// automatically create directory if it doesn't exist
	public $create_dir = true;

	public $errors = array();
        
        public function __construct()
        {
           $this->files = $_FILES;
        }
        
        
        
        public function uploadFile($filename,$folder, $size_limit = null)
	{
		
			
		$path = UPLOADS_PATH.'/'.$folder;
               
		if(isset($this->files[$filename]) && isset($this->files[$filename]['tmp_name']) && !empty($this->files[$filename]['tmp_name']))
		{
			
			$this->file = $this->files[$filename];
			if($this->checkPath($path))
			{
				if(is_uploaded_file($this->file['tmp_name']))
				{
					
					$file = uniqid().'.'.$this->ext();
					if(move_uploaded_file($this->file['tmp_name'], $path.'/'.$file))
					{
						/// file successfully saved
						return $file;
                                                 
					} else {
						$this->errors[] = __('There was an unknown error uploading the file');
						// there was an error uploading the file
						return false;
					}
				} else {
					// error: the specified file was not an uploaded file
					$this->errors[] = __('There seems to be an error with the uploaded file');
					return false;
				}
			} else {
				// There was an error with the directory permissions
				return false;
			}
		}
	}

	public function checkPath($path)
	{
		// check to see if directory exists
		if(is_dir($path))
		{
			if(is_writable($path))
			{
				// the direcotry exists and is writable
				return true;
			} else {
				// try to make directory writable
				if(@chmod($path, 0777))
				{
					return true;
				} else {
					$this->errors[] = __('There was a problem setting the permissions on the directory');
					return false;
				}
			}
		} else {
			// try creating directory
			if(mkdir($path, 0777, true))
			{
				return true;
			} else {
				$this->errors[] = __('The directory could not be created');
				return false;
			}
		}
	}

	public function ext()
	{
		$info =  pathinfo($this->file['name']);
		return $info['extension'];
	}
}
?>
