Return to Snippet

Revision: 20511
at November 17, 2009 16:00 by djenniex


Updated Code
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * CodeIgniter Form Validation
 *
 * @version $Id: MY_Form_validation.php 83 2009-07-17 22:07:43Z djenniex $
 * @package
 * @subpackage Library
 * @category Validation
 */

/**
 * Form Validation
 *
 * This is an extension of the CodeIgniter Validation Class
 *
 * Adds validation rules
 */
class MY_Form_validation extends CI_Form_validation
{
    const DUMMY_ITEM   = 'DUMMY_ITEM';
    var $_error_prefix = '<span class="formerror small">';
    var $_error_suffix = '</span>';

	/**
     * Constructor
     *
     * @param array $rules
     * 
     * @return MY_Form_validation
     * @access public
     */
    public function __construct($rules = array())
    {
        parent::CI_Form_validation($rules);
        $this->CI->lang->load('upload');
        
        $this->CI->load->library('upload');
    }
    
    /**
     * PHP4 Constructor
     * 
     * @param array $rules
     * 
     * @return MY_Form_validation
     * @access public
     */
    public function MY_Form_validation($rules = array())
    {
        parent::CI_Form_validation($rules);
        $this->CI->lang->load('upload');
		$this->CI->load->library('upload');
    }
    
	/**
	 * Set Rules
	 *
	 * This function takes an array of field names and validation
	 * rules as input, validates the info, and stores it
	 *
	 * @param  mixed $field
	 * @param  string $label
	 * @param  mixed $rules
	 * 
	 * @return void
	 * @access public
	 * @see set_rules()
	 */
	function set_rules($field, $label = '', $rules = '')
	{
		// set a dummy post if we have only files that are processed 
		if (count($_POST) == 0 && count($_FILES) > 0) 
		{
		    // Add a dummy $_POST variable
		    $_POST[DUMMY_ITEM] = '';
		    parent::set_rules($field, $label, $rules);
		    unset($_POST[DUMMY_ITEM]);
			return;
		}
		
		// we are safe to run as is
		parent::set_rules($field, $label, $rules);
	}
    
	/**
	 * Run the Validator
	 *
	 * This function does all the work.
	 * 
	 * @param string $module
	 * @param string $group
	 *
	 * @access	public
	 * @return	bool
	 * @see run()
	 */	
    public function run($group = '')
    {        
        if (count($_POST) === 0 && count($_FILES) > 0)
        {
            // Add a dummy $_POST variable
            $_POST[DUMMY_ITEM] = '';
            $rc = parent::run($group);
            unset($_POST[DUMMY_ITEM]);
            return $rc;
        }
        
        // we are safe to run as is
        return parent::run($group);
    }
    
    /**
	 * Executes the Validation routines
	 *
	 * @param	array
	 * @param	array
	 * @param	mixed
	 * @param	integer
	 * 
	 * @return	mixed
	 * @access	private
	 */	
	public function _execute($row, $rules, $postdata = NULL, $cycles = 0)
	{
	    if (isset($_FILES[$row['field']]))
	    {
	        // It's a file, so process it as a file
	        $postdata = $_FILES[$row['field']];
	        
	        // Before doing anything check for errors
	        if ($postdata['error'] !== UPLOAD_ERR_OK)
	        {
    	        switch ($postdata['error'])
    			{
    				case 1:	// UPLOAD_ERR_INI_SIZE
    					$error = $this->CI->lang->line('upload_file_exceeds_limit');
    					break;
    				case 2: // UPLOAD_ERR_FORM_SIZE
    					$error = $this->CI->lang->line('upload_file_exceeds_form_limit');
    					break;
    				case 3: // UPLOAD_ERR_PARTIAL
    				    $error = $this->CI->lang->line('upload_file_partial');
                        break;
    				case 4: // UPLOAD_ERR_NO_FILE
    				    $error = $this->CI->lang->line('upload_no_file_selected');
    					break;
    				case 6: // UPLOAD_ERR_NO_TMP_DIR
    					$error = $this->CI->lang->line('upload_no_temp_directory');
    					break;
    				case 7: // UPLOAD_ERR_CANT_WRITE
    					$error = $this->CI->lang->line('upload_unable_to_write_file');
    					break;
    				case 8: // UPLOAD_ERR_EXTENSION
    					$error = $this->CI->lang->line('upload_stopped_by_extension');
    					break;
    				default:   
    				    $error = $this->CI->lang->line('upload_no_file_selected');
    					break;
    			}
	            // Build the error message
				$message = sprintf($error, $this->_translate_fieldname($row['label']));

				// Save the error message
				$this->_field_data[$row['field']]['error'] = $message;
				
	            if ( ! isset($this->_error_array[$row['field']]))
				{
					$this->_error_array[$row['field']] = $message;
				}
	            return FALSE;
	        }
	        
	        $_in_array = FALSE;
	        
	        // If the field is blank, but NOT required, no further tests are necessary
	        $callback = FALSE;    
	        if ( !in_array('file_required', $rules) && $postdata['size'] == 0)
	        {
	            // Before we bail out, does the rule contain a callback?
	            if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
	            {
	                $callback = TRUE;
	                $rules = (array('1' => $match[1]));
	            }
	            else
	            {
	                return;
	            }
	        }

    		// Cycle through each rule and run it
	    	foreach ($rules As $rule)
		    {
    			// Is the rule a callback?			
    			$callback = FALSE;
    			if (substr($rule, 0, 9) == 'callback_')
    			{
    				$rule = substr($rule, 9);
    				$callback = TRUE;
    			}
    			
    			// Strip the parameter (if exists) from the rule
    			// Rules can contain a parameter: max_length[5]
    			$param = FALSE;
    			if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match))
    			{
    				$rule	= $match[1];
    				$param	= $match[2];
    			}
    			
    			// Call the function that corresponds to the rule
    			if ($callback === TRUE)
    			{
    				if ( ! method_exists($this->CI, $rule))
    				{ 		
    					continue;
    				}
    				
    				// Run the function and grab the result
    				$result = $this->CI->$rule($postdata, $param);
    
    				// Re-assign the result to the master data array
    				if ($_in_array == TRUE)
    				{
    					$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
    				}
    				else
    				{
    					$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
    				}
    			
    				// If the field isn't required and we just processed a callback we'll move on...
    				if ( ! in_array('file_required', $rules, TRUE) AND $result !== FALSE)
    				{
    				    // FIX: Should we continue or return here?
    					continue;
    				}
    			}
    			else
    			{				
    				if ( ! method_exists($this, $rule))
    				{
    					// If our own wrapper function doesn't exist we see if a native PHP function does. 
    					// Users can use any native PHP function call that has one param.
    					if (function_exists($rule))
    					{
    						$result = $rule($postdata);
    											
    						if ($_in_array == TRUE)
    						{
    							$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
    						}
    						else
    						{
    							$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
    						}
    					}
    										
    					continue;
    				}
    
    				$result = $this->$rule($postdata, $param);
    
    				if ($_in_array == TRUE)
    				{
    					$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
    				}
    				else
    				{
    					$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
    				}
    			}
    							
    			// Did the rule test negatively?  If so, grab the error.
    			if ($result === FALSE)
    			{			
    				if ( ! isset($this->_error_messages[$rule]))
    				{
    					if (FALSE === ($line = $this->CI->lang->line($rule)))
    					{
    						$line = 'Unable to access an error message corresponding to your field name.';
    					}						
    				}
    				else
    				{
    					$line = $this->_error_messages[$rule];
    				}
    				
    				// Is the parameter we are inserting into the error message the name
    				// of another field?  If so we need to grab its "field label"
    				if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
    				{
    					$param = $this->_field_data[$param]['label'];
    				}
    				
    				// Build the error message
    				$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
    
    				// Save the error message
    				$this->_field_data[$row['field']]['error'] = $message;
    				
    				if ( ! isset($this->_error_array[$row['field']]))
    				{
    					$this->_error_array[$row['field']] = $message;
    				}
    				
    				return;
    			}
    		}
	    }
	    else
	    {
	        parent::_execute($row, $rules, $postdata, $cycles);
	    }
	} 
    
	// File Upload Validation
	// --------------------------------------------------------------------
	
	/**
     * Required file is uploaded
     *  
     * @param mixed $file
     * 
     * @return boolean
     * @access public
     */
    public function file_required($file)
    {
        if ($file['size'] === 0)
        {
            $this->set_message('file_required', 'Uploading a file for %s is required.');
            return FALSE;
        }
        
        return TRUE;
    }
    
 	/**
     * File is within expected file size limit
     *  
     * @param mixed $file
     * @param mixed $max_size
     * 
     * @return boolean
     * @access public
     */
    public function max_file_size($file, $max_size)
    {
        $max_size_bit = $this->_let_to_bit($max_size);
        if ($file['size'] > $max_size_bit)
        {
            $this->set_message('max_file_size', '%s exceeds file size limit of ' . $max_size);
            return FALSE;
        }
        return TRUE;
    }
    
    /**
    * File is bigger than minimum size
    * 
    * @param mixed $file
    * @param mixed $min_size
    * 
    * @return boolean
    * @accesspublic
    */
    public function min_file_size($file, $min_size)
    {
        $min_size_bit = $this->_let_to_bit($min_size);
        if ($file['size'] < $min_size_bit)
        {
            $this->set_message('min_file_size', '%s file size is smaller than minimum required of ' . $min_size);
            return FALSE;
        }
        return TRUE;
    }
    
    /**
     * File extension for valid file types
     *   
     * @param mixed $file
     * @param mixed $extensions
     * 
     * @return boolean
     * @access public
     */
    public function valid_file_extension($file, $extensions)
    {
        // Check format type
        $allowed_types = explode('|', $extensions);

        if (count($allowed_types) == 0 OR ! is_array($allowed_types))
        {
			$this->set_message('valid_file_extension', $this->CI->lang->line('upload_no_file_types'));
            return FALSE;
        }
        
        $image_types = array('jpg', 'jpeg', 'gif', 'png', 'jpe');

        foreach ($allowed_types as $val)
        {
            $mime = $this->CI->upload->mimes_types(strtolower($val));
            
            // Images get some additional checks
            if (in_array($val, $image_types))
            {
                if (getimagesize($file['tmp_name']) === FALSE)
                {
                    $this->set_message('valid_file_extension', "%s size is insufficient.");
                    return FALSE;
                }
            }
                
            if (is_array($mime))
            {
                if (in_array($file['type'], $mime, TRUE))
                {
                    return TRUE;
                }
            }
            else
            {
                if ($mime == $file['type'])
                {
                    return TRUE;
                }
            }
        }
        
        $this->set_message('valid_file_extension', $this->CI->lang->line('upload_invalid_filetype'));
        return FALSE;        
    }
   
 	/**
     * Image is bigger than the dimensions given
     *  
     * @param mixed $file
     * @param array $dimensions
     * 
     * @return boolean
     * @access public
     */
    public function max_image_dimension($file, $dimensions)
    {
        $dimensions = explode(',', $dimensions);
        
        if (count($dimensions) !== 2)
        {
            // Bad size given
            $this->set_message('max_image_dimension', '%s has invalid rule expected similar to 150,300');
            return FALSE;
        }
        
        // Get image size
        $image_dimensions = $this->_get_image_dimension($file['tmp_name']);       
        if ( ! $image_dimensions)
        {
            $this->set_message('max_image_dimension', '%s dimensions was not detected.');
            return FALSE;        
        }
                
        if ($image_dimensions[0] < $dimensions[0] && $image_dimensions[1] < $dimensions[1])
        {
            return TRUE;
        }
    
        $this->set_message('max_image_dimension', '%s image size is too big.');
        return FALSE;
    }
    
	/**
     * Image is smaller than given dimension
     * 
     * @param mixed $file
     * @param array $dim
     * 
     * @return boolean
     * @access public
     */
    public function min_image_dimension($file, $dimensions)
    {
        $dimensions = explode(',', $dimensions);
        
        if (count($dimensions) !== 2)
        {
            // Bad size given
            $this->set_message('min_image_dimension', '%s has invalid rule expected similar to 150,300');
            return FALSE;
        }
        
        // Get image size
        $image_dimensions = $this->_get_image_dimension($file['tmp_name']);
        if ( ! $image_dimensions)
        {
            $this->set_message('min_image_dimension', '%s dimensions was not detected.');
            return FALSE;        
        }
        
        if ($image_dimensions[0] > $dimensions[0] && $image_dimensions[1] > $dimensions[1])
        {
            return TRUE;
        }
    
        $this->set_message('min_image_dimension', '%s image size is too big.');
        return FALSE;
    }
    
    /**
     * Determine the image dimension
     * 
     * @param mixed $file_name Path to the image file
     * 
     * @return array
     * @access private
     */
    private function _get_image_dimension($file_name)
    {
        if (function_exists('getimagesize'))
        {
            return @getimagesize($file_name);
        }
        
        return FALSE;
    }
    
    /**
     * Given an string in format of ###AA converts to number of bits it is assignin
     * 
     * @param string $value
     * 
     * @return integer
     * @access private
     */
    private function _let_to_bit($value)
    {
        // Split value from name
        if( ! preg_match('/([0-9]+)([ptgmkb]{1,2}|)/ui', $value, $matches))
        { 
            // Invalid input
            return FALSE;
        }
        
        if (empty($matches[2]))
        { 
            // No name -> Enter default value
            $matches[2] = 'KB';
        }
        
        if (strlen($matches[2]) == 1)
        { 
            // Shorted name -> full name
            $matches[2] .= 'B';
        }
        
        $bit = (substr($matches[2], -1) == 'B') ? 1024 : 1000;
        
        // Calculate bits
        switch(strtoupper(substr($matches[2], 0, 1)))
        {
            case 'P':
                $matches[1] *= $bit;
            case 'T':
                $matches[1] *= $bit;
            case 'G':
                $matches[1] *= $bit;
            case 'M':
                $matches[1] *= $bit;
            case 'K':
                $matches[1] *= $bit;
                break;
        }

        // Return the value in bits
        return $matches[1];
    }
	
	// --------------------------------------------------------------------
}

/* End of file MY_Form_validation.php */
/* Location: ./system/application/library/MY_Form_validation.php */

Revision: 20510
at November 17, 2009 12:16 by djenniex


Initial Code
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * CodeIgniter Form Validation
 *
 * @version $Id: MY_Form_validation.php 83 2009-07-17 22:07:43Z djenniex $
 * @package
 * @subpackage Library
 * @category Validation
 */

/**
 * Form Validation
 *
 * This is an extension of the CodeIgniter Validation Class
 *
 * Adds validation rules
 */
class MY_Form_validation extends CI_Form_validation
{
    const DUMMY_ITEM   = 'DUMMY_ITEM';
    var $_error_prefix = '<span class="formerror small">';
    var $_error_suffix = '</span>';

	/**
     * Constructor
     *
     * @param array $rules
     * 
     * @return MY_Form_validation
     * @access public
     */
    public function __construct($rules = array())
    {
        parent::CI_Form_validation($rules);
        $this->CI->lang->load('upload');
        
        $this->CI->load->library('upload');
    }
    
    /**
     * PHP4 Constructor
     * 
     * @param array $rules
     * 
     * @return MY_Form_validation
     * @access public
     */
    public function MY_Form_validation($rules = array())
    {
        parent::CI_Form_validation($rules);
        $this->CI->lang->load('upload');
		$this->CI->load->library('upload');
    }
    
	/**
	 * Set Rules
	 *
	 * This function takes an array of field names and validation
	 * rules as input, validates the info, and stores it
	 *
	 * @param  mixed $field
	 * @param  string $label
	 * @param  mixed $rules
	 * 
	 * @return void
	 * @access public
	 * @see set_rules()
	 */
	function set_rules($field, $label = '', $rules = '')
	{
		// set a dummy post if we have only files that are processed 
		if (count($_POST) == 0 && count($_FILES) > 0) 
		{
		    // Add a dummy $_POST variable
		    $_POST[DUMMY_ITEM] = '';
		    parent::set_rules($field, $label, $rules);
		    unset($_POST[DUMMY_ITEM]);
			return;
		}
		
		// we are safe to run as is
		parent::set_rules($field, $label, $rules);
	}
    
	/**
	 * Run the Validator
	 *
	 * This function does all the work.
	 * 
	 * @param string $module
	 * @param string $group
	 *
	 * @access	public
	 * @return	bool
	 * @see run()
	 */	
    public function run($group = '')
    {        
        if (count($_POST) === 0 && count($_FILES) > 0)
        {
            // Add a dummy $_POST variable
            $_POST[DUMMY_ITEM] = '';
            $rc = parent::run($group);
            unset($_POST[DUMMY_ITEM]);
            return $rc;
        }
        
        // we are safe to run as is
        return parent::run($group);
    }
    
    /**
	 * Executes the Validation routines
	 *
	 * @param	array
	 * @param	array
	 * @param	mixed
	 * @param	integer
	 * 
	 * @return	mixed
	 * @access	private
	 */	
	public function _execute($row, $rules, $postdata = NULL, $cycles = 0)
	{
	    if (isset($_FILES[$row['field']]))
	    {
	        // It's a file, so process it as a file
	        $postdata = $_FILES[$row['field']];
	        
	        // Before doing anything check for errors
	        if ($postdata['error'] !== UPLOAD_ERR_OK)
	        {
    	        switch ($postdata['error'])
    			{
    				case 1:	// UPLOAD_ERR_INI_SIZE
    					$error = $this->CI->lang->line('upload_file_exceeds_limit');
    					break;
    				case 2: // UPLOAD_ERR_FORM_SIZE
    					$error = $this->CI->lang->line('upload_file_exceeds_form_limit');
    					break;
    				case 3: // UPLOAD_ERR_PARTIAL
    				    $error = $this->CI->lang->line('upload_file_partial');
                        break;
    				case 4: // UPLOAD_ERR_NO_FILE
    				    $error = $this->CI->lang->line('upload_no_file_selected');
    					break;
    				case 6: // UPLOAD_ERR_NO_TMP_DIR
    					$error = $this->CI->lang->line('upload_no_temp_directory');
    					break;
    				case 7: // UPLOAD_ERR_CANT_WRITE
    					$error = $this->CI->lang->line('upload_unable_to_write_file');
    					break;
    				case 8: // UPLOAD_ERR_EXTENSION
    					$error = $this->CI->lang->line('upload_stopped_by_extension');
    					break;
    				default:   
    				    $error = $this->CI->lang->line('upload_no_file_selected');
    					break;
    			}
	            // Build the error message
				$message = sprintf($error, $this->_translate_fieldname($row['label']));

				// Save the error message
				$this->_field_data[$row['field']]['error'] = $message;
				
	            if ( ! isset($this->_error_array[$row['field']]))
				{
					$this->_error_array[$row['field']] = $message;
				}
	            return FALSE;
	        }
	        
	        $_in_array = FALSE;
	        
	        // If the field is blank, but NOT required, no further tests are necessary
	        $callback = FALSE;    
	        if ( !in_array('file_required', $rules) && $postdata['size'] == 0)
	        {
	            // Before we bail out, does the rule contain a callback?
	            if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
	            {
	                $callback = TRUE;
	                $rules = (array('1' => $match[1]));
	            }
	            else
	            {
	                return;
	            }
	        }

    		// Cycle through each rule and run it
	    	foreach ($rules As $rule)
		    {
    			// Is the rule a callback?			
    			$callback = FALSE;
    			if (substr($rule, 0, 9) == 'callback_')
    			{
    				$rule = substr($rule, 9);
    				$callback = TRUE;
    			}
    			
    			// Strip the parameter (if exists) from the rule
    			// Rules can contain a parameter: max_length[5]
    			$param = FALSE;
    			if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match))
    			{
    				$rule	= $match[1];
    				$param	= $match[2];
    			}
    			
    			// Call the function that corresponds to the rule
    			if ($callback === TRUE)
    			{
    				if ( ! method_exists($this->CI, $rule))
    				{ 		
    					continue;
    				}
    				
    				// Run the function and grab the result
    				$result = $this->CI->$rule($postdata, $param);
    
    				// Re-assign the result to the master data array
    				if ($_in_array == TRUE)
    				{
    					$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
    				}
    				else
    				{
    					$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
    				}
    			
    				// If the field isn't required and we just processed a callback we'll move on...
    				if ( ! in_array('file_required', $rules, TRUE) AND $result !== FALSE)
    				{
    				    // FIX: Should we continue or return here?
    					continue;
    				}
    			}
    			else
    			{				
    				if ( ! method_exists($this, $rule))
    				{
    					// If our own wrapper function doesn't exist we see if a native PHP function does. 
    					// Users can use any native PHP function call that has one param.
    					if (function_exists($rule))
    					{
    						$result = $rule($postdata);
    											
    						if ($_in_array == TRUE)
    						{
    							$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
    						}
    						else
    						{
    							$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
    						}
    					}
    										
    					continue;
    				}
    
    				$result = $this->$rule($postdata, $param);
    
    				if ($_in_array == TRUE)
    				{
    					$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
    				}
    				else
    				{
    					$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
    				}
    			}
    							
    			// Did the rule test negatively?  If so, grab the error.
    			if ($result === FALSE)
    			{			
    				if ( ! isset($this->_error_messages[$rule]))
    				{
    					if (FALSE === ($line = $this->CI->lang->line($rule)))
    					{
    						$line = 'Unable to access an error message corresponding to your field name.';
    					}						
    				}
    				else
    				{
    					$line = $this->_error_messages[$rule];
    				}
    				
    				// Is the parameter we are inserting into the error message the name
    				// of another field?  If so we need to grab its "field label"
    				if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
    				{
    					$param = $this->_field_data[$param]['label'];
    				}
    				
    				// Build the error message
    				$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
    
    				// Save the error message
    				$this->_field_data[$row['field']]['error'] = $message;
    				
    				if ( ! isset($this->_error_array[$row['field']]))
    				{
    					$this->_error_array[$row['field']] = $message;
    				}
    				
    				return;
    			}
    		}
	    }
	    else
	    {
	        parent::_execute($row, $rules, $postdata, $cycles);
	    }
	} 
    
	// File Upload Validation
	// --------------------------------------------------------------------
	
	/**
     * Required file is uploaded
     *  
     * @param mixed $file
     * 
     * @return boolean
     * @access public
     */
    public function file_required($file)
    {
        if ($file['size'] === 0)
        {
            $this->set_message('file_required', 'Uploading a file for %s is required.');
            return FALSE;
        }
        
        return TRUE;
    }
    
 	/**
     * File is within expected file size limit
     *  
     * @param mixed $file
     * @param mixed $max_size
     * 
     * @return boolean
     * @access public
     */
    public function max_file_size($file, $max_size)
    {
        $max_size_bit = $this->_let_to_bit($max_size);
        if ($file['size'] > $max_size_bit)
        {
            $this->set_message('max_file_size', '%s exceeds file size limit of ' . $max_size);
            return FALSE;
        }
        return TRUE;
    }
    
    /**
    * File is bigger than minimum size
    * 
    * @param mixed $file
    * @param mixed $min_size
    * 
    * @return boolean
    * @accesspublic
    */
    public function min_file_size($file, $min_size)
    {
        $min_size_bit = $this->_let_to_bit($min_size);
        if ($file['size'] < $min_size_bit)
        {
            $this->set_message('min_file_size', '%s file size is smaller than minimum required of ' . $min_size);
            return FALSE;
        }
        return TRUE;
    }
    
    /**
     * File extension for valid file types
     *   
     * @param mixed $file
     * @param mixed $extensions
     * 
     * @return boolean
     * @access public
     */
    public function valid_file_extension($file, $extensions)
    {
        // Check format type
        $allowed_types = explode('|', $extensions);

        if (count($allowed_types) == 0 OR ! is_array($allowed_types))
        {
			$this->set_message('valid_file_extension', $this->CI->lang->line('upload_no_file_types'));
            return FALSE;
        }
        
        $image_types = array('jpg', 'jpeg', 'gif', 'png', 'jpe');

        foreach ($allowed_types as $val)
        {
            $mime = $this->CI->upload->mimes_types(strtolower($val));
            
            // Images get some additional checks
            if (in_array($val, $image_types))
            {
                if (getimagesize($file['tmp_name']) === FALSE)
                {
                    $this->set_message('valid_file_extension', "%s size is insufficient.");
                    return FALSE;
                }
            }
                
            if (is_array($mime))
            {
                if (in_array($file['type'], $mime, TRUE))
                {
                    return TRUE;
                }
            }
            else
            {
                if ($mime == $file['type'])
                {
                    return TRUE;
                }
            }
        }
        
        $this->set_message('valid_file_extension', $this->CI->lang->line('upload_invalid_filetype'));
        return FALSE;        
    }
   
 	/**
     * Image is bigger than the dimensions given
     *  
     * @param mixed $file
     * @param array $dimensions
     * 
     * @return boolean
     * @access public
     */
    public function max_image_dimension($file, $dimensions)
    {
        $dimensions = explode(',', $dimensions);
        
        if (count($dimensions) !== 2)
        {
            // Bad size given
            $this->set_message('max_image_dimension', '%s has invalid rule expected similar to 150,300');
            return FALSE;
        }
        
        // Get image size
        $image_dimensions = $this->_get_image_dimension($file['tmp_name']);       
        if ( ! $image_dimensions)
        {
            $this->set_message('max_image_dimension', '%s dimensions was not detected.');
            return FALSE;        
        }
                
        if ($image_dimensions[0] < $dimensions[0] && $image_dimensions[1] < $dimensions[1])
        {
            return TRUE;
        }
    
        $this->set_message('max_image_dimension', '%s image size is too big.');
        return FALSE;
    }
    
	/**
     * Image is smaller than given dimension
     * 
     * @param mixed $file
     * @param array $dim
     * 
     * @return boolean
     * @access public
     */
    public function min_image_dimension($file, $dimensions)
    {
        $dimensions = explode(',', $dimensions);
        
        if (count($dimensions) !== 2)
        {
            // Bad size given
            $this->set_message('min_image_dimension', '%s has invalid rule expected similar to 150,300');
            return FALSE;
        }
        
        // Get image size
        $image_dimensions = $this->_get_image_dimension($file['tmp_name']);
        if ( ! $image_dimensions)
        {
            $this->set_message('min_image_dimension', '%s dimensions was not detected.');
            return FALSE;        
        }
        
        if ($image_dimensions[0] > $dimensions[0] && $image_dimensions[1] > $dimensions[1])
        {
            return TRUE;
        }
    
        $this->set_message('min_image_dimension', '%s image size is too big.');
        return FALSE;
    }
    
    /**
     * Determine the image dimension
     * 
     * @param mixed $file_name Path to the image file
     * 
     * @return array
     * @access private
     */
    private function _get_image_dimension($file_name)
    {
        if (function_exists('getimagesize'))
        {
            return @getimagesize($file_name);
        }
        
        return FALSE;
    }
    
    /**
     * Given an string in format of ###AA converts to number of bits it is assignin
     * 
     * @param string $value
     * 
     * @return integer
     * @access private
     */
    private function _let_to_bit($value)
    {
        // Split value from name
        if( ! preg_match('/([0-9]+)([ptgmkb]{1,2}|)/ui', $value, $matches))
        { 
            // Invalid input
            return FALSE;
        }
        
        if (empty($matches[2]))
        { 
            // No name -> Enter default value
            $matches[2] = 'KB';
        }
        
        if (strlen($matches[2]) == 1)
        { 
            // Shorted name -> full name
            $matches[2] .= 'B';
        }
        
        $bit = (substr($matches[2], -1) == 'B') ? 1024 : 1000;
        
        // Calculate bits
        switch(strtoupper(substr($matches[2], 0, 1)))
        {
            case 'P':
            case 'T':
            case 'G':
            case 'M':
            case 'K':
                $matches[1] *= $bit;
                break;
        }

        // Return the value in bits
        return $matches[1];
    }
	
	// --------------------------------------------------------------------
}

/* End of file MY_Form_validation.php */
/* Location: ./system/application/library/MY_Form_validation.php */

Initial URL


Initial Description
Custom CodeIgniter form_validation class to validate uploaded files.

Initial Title
MY_Form_validation

Initial Tags
codeigniter

Initial Language
PHP