summaryrefslogtreecommitdiffstats
path: root/system/libraries/Upload.php
diff options
context:
space:
mode:
Diffstat (limited to 'system/libraries/Upload.php')
-rw-r--r--system/libraries/Upload.php1046
1 files changed, 619 insertions, 427 deletions
diff --git a/system/libraries/Upload.php b/system/libraries/Upload.php
index c188c39bc..b37cc2f59 100644
--- a/system/libraries/Upload.php
+++ b/system/libraries/Upload.php
@@ -1,19 +1,41 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP
*
- * @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
- * @link http://codeigniter.com
- * @since Version 1.0
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 1.0.0
* @filesource
*/
-
-// ------------------------------------------------------------------------
+defined('BASEPATH') OR exit('No direct script access allowed');
/**
* File Uploading Class
@@ -21,52 +43,260 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Uploads
- * @author ExpressionEngine Dev Team
- * @link http://codeigniter.com/user_guide/libraries/file_uploading.html
+ * @author EllisLab Dev Team
+ * @link https://codeigniter.com/user_guide/libraries/file_uploading.html
*/
class CI_Upload {
- public $max_size = 0;
- public $max_width = 0;
- public $max_height = 0;
- public $max_filename = 0;
- public $allowed_types = "";
- public $file_temp = "";
- public $file_name = "";
- public $orig_name = "";
- public $file_type = "";
- public $file_size = "";
- public $file_ext = "";
- public $upload_path = "";
- public $overwrite = FALSE;
- public $encrypt_name = FALSE;
- public $is_image = FALSE;
- public $image_width = '';
- public $image_height = '';
- public $image_type = '';
- public $image_size_str = '';
- public $error_msg = array();
- public $mimes = array();
- public $remove_spaces = TRUE;
- public $xss_clean = FALSE;
- public $temp_prefix = "temp_file_";
- public $client_name = '';
-
- protected $_file_name_override = '';
+ /**
+ * Maximum file size
+ *
+ * @var int
+ */
+ public $max_size = 0;
+
+ /**
+ * Maximum image width
+ *
+ * @var int
+ */
+ public $max_width = 0;
+
+ /**
+ * Maximum image height
+ *
+ * @var int
+ */
+ public $max_height = 0;
+
+ /**
+ * Minimum image width
+ *
+ * @var int
+ */
+ public $min_width = 0;
+
+ /**
+ * Minimum image height
+ *
+ * @var int
+ */
+ public $min_height = 0;
+
+ /**
+ * Maximum filename length
+ *
+ * @var int
+ */
+ public $max_filename = 0;
+
+ /**
+ * Maximum duplicate filename increment ID
+ *
+ * @var int
+ */
+ public $max_filename_increment = 100;
+
+ /**
+ * Allowed file types
+ *
+ * @var string
+ */
+ public $allowed_types = '';
+
+ /**
+ * Temporary filename
+ *
+ * @var string
+ */
+ public $file_temp = '';
+
+ /**
+ * Filename
+ *
+ * @var string
+ */
+ public $file_name = '';
+
+ /**
+ * Original filename
+ *
+ * @var string
+ */
+ public $orig_name = '';
+
+ /**
+ * File type
+ *
+ * @var string
+ */
+ public $file_type = '';
+
+ /**
+ * File size
+ *
+ * @var int
+ */
+ public $file_size = NULL;
+
+ /**
+ * Filename extension
+ *
+ * @var string
+ */
+ public $file_ext = '';
+
+ /**
+ * Force filename extension to lowercase
+ *
+ * @var string
+ */
+ public $file_ext_tolower = FALSE;
+
+ /**
+ * Upload path
+ *
+ * @var string
+ */
+ public $upload_path = '';
+
+ /**
+ * Overwrite flag
+ *
+ * @var bool
+ */
+ public $overwrite = FALSE;
+
+ /**
+ * Obfuscate filename flag
+ *
+ * @var bool
+ */
+ public $encrypt_name = FALSE;
+
+ /**
+ * Is image flag
+ *
+ * @var bool
+ */
+ public $is_image = FALSE;
+
+ /**
+ * Image width
+ *
+ * @var int
+ */
+ public $image_width = NULL;
+
+ /**
+ * Image height
+ *
+ * @var int
+ */
+ public $image_height = NULL;
+
+ /**
+ * Image type
+ *
+ * @var string
+ */
+ public $image_type = '';
+
+ /**
+ * Image size string
+ *
+ * @var string
+ */
+ public $image_size_str = '';
+
+ /**
+ * Error messages list
+ *
+ * @var array
+ */
+ public $error_msg = array();
+
+ /**
+ * Remove spaces flag
+ *
+ * @var bool
+ */
+ public $remove_spaces = TRUE;
+
+ /**
+ * MIME detection flag
+ *
+ * @var bool
+ */
+ public $detect_mime = TRUE;
+
+ /**
+ * XSS filter flag
+ *
+ * @var bool
+ */
+ public $xss_clean = FALSE;
+
+ /**
+ * Apache mod_mime fix flag
+ *
+ * @var bool
+ */
+ public $mod_mime_fix = TRUE;
+
+ /**
+ * Temporary filename prefix
+ *
+ * @var string
+ */
+ public $temp_prefix = 'temp_file_';
+
+ /**
+ * Filename sent by the client
+ *
+ * @var bool
+ */
+ public $client_name = '';
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Filename override
+ *
+ * @var string
+ */
+ protected $_file_name_override = '';
+
+ /**
+ * MIME types list
+ *
+ * @var array
+ */
+ protected $_mimes = array();
+
+ /**
+ * CI Singleton
+ *
+ * @var object
+ */
+ protected $_CI;
+
+ // --------------------------------------------------------------------
/**
* Constructor
*
- * @access public
+ * @param array $config
+ * @return void
*/
- public function __construct($props = array())
+ public function __construct($config = array())
{
- if (count($props) > 0)
- {
- $this->initialize($props);
- }
+ empty($config) OR $this->initialize($config, FALSE);
- log_message('debug', "Upload Class Initialized");
+ $this->_mimes =& get_mimes();
+ $this->_CI =& get_instance();
+
+ log_message('info', 'Upload Class Initialized');
}
// --------------------------------------------------------------------
@@ -74,63 +304,63 @@ class CI_Upload {
/**
* Initialize preferences
*
- * @param array
- * @return void
+ * @param array $config
+ * @param bool $reset
+ * @return CI_Upload
*/
- public function initialize($config = array())
+ public function initialize(array $config = array(), $reset = TRUE)
{
- $defaults = array(
- 'max_size' => 0,
- 'max_width' => 0,
- 'max_height' => 0,
- 'max_filename' => 0,
- 'allowed_types' => "",
- 'file_temp' => "",
- 'file_name' => "",
- 'orig_name' => "",
- 'file_type' => "",
- 'file_size' => "",
- 'file_ext' => "",
- 'upload_path' => "",
- 'overwrite' => FALSE,
- 'encrypt_name' => FALSE,
- 'is_image' => FALSE,
- 'image_width' => '',
- 'image_height' => '',
- 'image_type' => '',
- 'image_size_str' => '',
- 'error_msg' => array(),
- 'mimes' => array(),
- 'remove_spaces' => TRUE,
- 'xss_clean' => FALSE,
- 'temp_prefix' => "temp_file_",
- 'client_name' => ''
- );
-
-
- foreach ($defaults as $key => $val)
+ $reflection = new ReflectionClass($this);
+
+ if ($reset === TRUE)
{
- if (isset($config[$key]))
+ $defaults = $reflection->getDefaultProperties();
+ foreach (array_keys($defaults) as $key)
{
- $method = 'set_'.$key;
- if (method_exists($this, $method))
+ if ($key[0] === '_')
{
- $this->$method($config[$key]);
+ continue;
+ }
+
+ if (isset($config[$key]))
+ {
+ if ($reflection->hasMethod('set_'.$key))
+ {
+ $this->{'set_'.$key}($config[$key]);
+ }
+ else
+ {
+ $this->$key = $config[$key];
+ }
}
else
{
- $this->$key = $config[$key];
+ $this->$key = $defaults[$key];
}
}
- else
+ }
+ else
+ {
+ foreach ($config as $key => &$value)
{
- $this->$key = $val;
+ if ($key[0] !== '_' && $reflection->hasProperty($key))
+ {
+ if ($reflection->hasMethod('set_'.$key))
+ {
+ $this->{'set_'.$key}($value);
+ }
+ else
+ {
+ $this->$key = $value;
+ }
+ }
}
}
// if a file_name was provided in the config, use it instead of the user input
// supplied file name for all uploads until initialized again
$this->_file_name_override = $this->file_name;
+ return $this;
}
// --------------------------------------------------------------------
@@ -138,15 +368,36 @@ class CI_Upload {
/**
* Perform the file upload
*
+ * @param string $field
* @return bool
*/
public function do_upload($field = 'userfile')
{
+ // Is $_FILES[$field] set? If not, no reason to continue.
+ if (isset($_FILES[$field]))
+ {
+ $_file = $_FILES[$field];
+ }
+ // Does the field name contain array notation?
+ elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1)
+ {
+ $_file = $_FILES;
+ for ($i = 0; $i < $c; $i++)
+ {
+ // We can't track numeric iterations, only full field names are accepted
+ if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field]))
+ {
+ $_file = NULL;
+ break;
+ }
- // Is $_FILES[$field] set? If not, no reason to continue.
- if ( ! isset($_FILES[$field]))
+ $_file = $_file[$field];
+ }
+ }
+
+ if ( ! isset($_file))
{
- $this->set_error('upload_no_file_selected');
+ $this->set_error('upload_no_file_selected', 'debug');
return FALSE;
}
@@ -158,60 +409,66 @@ class CI_Upload {
}
// Was the file able to be uploaded? If not, determine the reason why.
- if ( ! is_uploaded_file($_FILES[$field]['tmp_name']))
+ if ( ! is_uploaded_file($_file['tmp_name']))
{
- $error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
+ $error = isset($_file['error']) ? $_file['error'] : 4;
- switch($error)
+ switch ($error)
{
- case 1: // UPLOAD_ERR_INI_SIZE
- $this->set_error('upload_file_exceeds_limit');
+ case UPLOAD_ERR_INI_SIZE:
+ $this->set_error('upload_file_exceeds_limit', 'info');
break;
- case 2: // UPLOAD_ERR_FORM_SIZE
- $this->set_error('upload_file_exceeds_form_limit');
+ case UPLOAD_ERR_FORM_SIZE:
+ $this->set_error('upload_file_exceeds_form_limit', 'info');
break;
- case 3: // UPLOAD_ERR_PARTIAL
- $this->set_error('upload_file_partial');
+ case UPLOAD_ERR_PARTIAL:
+ $this->set_error('upload_file_partial', 'debug');
break;
- case 4: // UPLOAD_ERR_NO_FILE
- $this->set_error('upload_no_file_selected');
+ case UPLOAD_ERR_NO_FILE:
+ $this->set_error('upload_no_file_selected', 'debug');
break;
- case 6: // UPLOAD_ERR_NO_TMP_DIR
- $this->set_error('upload_no_temp_directory');
+ case UPLOAD_ERR_NO_TMP_DIR:
+ $this->set_error('upload_no_temp_directory', 'error');
break;
- case 7: // UPLOAD_ERR_CANT_WRITE
- $this->set_error('upload_unable_to_write_file');
+ case UPLOAD_ERR_CANT_WRITE:
+ $this->set_error('upload_unable_to_write_file', 'error');
break;
- case 8: // UPLOAD_ERR_EXTENSION
- $this->set_error('upload_stopped_by_extension');
+ case UPLOAD_ERR_EXTENSION:
+ $this->set_error('upload_stopped_by_extension', 'debug');
break;
- default : $this->set_error('upload_no_file_selected');
+ default:
+ $this->set_error('upload_no_file_selected', 'debug');
break;
}
return FALSE;
}
-
// Set the uploaded data as class variables
- $this->file_temp = $_FILES[$field]['tmp_name'];
- $this->file_size = $_FILES[$field]['size'];
- $this->_file_mime_type($_FILES[$field]);
- $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
+ $this->file_temp = $_file['tmp_name'];
+ $this->file_size = $_file['size'];
+
+ // Skip MIME type detection?
+ if ($this->detect_mime !== FALSE)
+ {
+ $this->_file_mime_type($_file);
+ }
+
+ $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type);
$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
- $this->file_name = $this->_prep_filename($_FILES[$field]['name']);
+ $this->file_name = $this->_prep_filename($_file['name']);
$this->file_ext = $this->get_extension($this->file_name);
$this->client_name = $this->file_name;
// Is the file type allowed to be uploaded?
if ( ! $this->is_allowed_filetype())
{
- $this->set_error('upload_invalid_filetype');
+ $this->set_error('upload_invalid_filetype', 'debug');
return FALSE;
}
// if we're overriding, let's now make sure the new name and type is allowed
- if ($this->_file_name_override != '')
+ if ($this->_file_name_override !== '')
{
$this->file_name = $this->_prep_filename($this->_file_name_override);
@@ -220,16 +477,15 @@ class CI_Upload {
{
$this->file_name .= $this->file_ext;
}
-
- // An extension was provided, lets have it!
else
{
- $this->file_ext = $this->get_extension($this->_file_name_override);
+ // An extension was provided, let's have it!
+ $this->file_ext = $this->get_extension($this->_file_name_override);
}
if ( ! $this->is_allowed_filetype(TRUE))
{
- $this->set_error('upload_invalid_filetype');
+ $this->set_error('upload_invalid_filetype', 'debug');
return FALSE;
}
}
@@ -243,20 +499,20 @@ class CI_Upload {
// Is the file size within the allowed maximum?
if ( ! $this->is_allowed_filesize())
{
- $this->set_error('upload_invalid_filesize');
+ $this->set_error('upload_invalid_filesize', 'info');
return FALSE;
}
// Are the image dimensions within the allowed size?
- // Note: This can fail if the server has an open_basdir restriction.
+ // Note: This can fail if the server has an open_basedir restriction.
if ( ! $this->is_allowed_dimensions())
{
- $this->set_error('upload_invalid_dimensions');
+ $this->set_error('upload_invalid_dimensions', 'info');
return FALSE;
}
// Sanitize the file name for security
- $this->file_name = $this->clean_file_name($this->file_name);
+ $this->file_name = $this->_CI->security->sanitize_filename($this->file_name);
// Truncate the file name if it's too long
if ($this->max_filename > 0)
@@ -265,9 +521,15 @@ class CI_Upload {
}
// Remove white spaces in the name
- if ($this->remove_spaces == TRUE)
+ if ($this->remove_spaces === TRUE)
+ {
+ $this->file_name = preg_replace('/\s+/', '_', $this->file_name);
+ }
+
+ if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext)))
{
- $this->file_name = preg_replace("/\s+/", "_", $this->file_name);
+ // file_ext was previously lower-cased by a get_extension() call
+ $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext;
}
/*
@@ -277,44 +539,35 @@ class CI_Upload {
* If it returns false there was a problem.
*/
$this->orig_name = $this->file_name;
-
- if ($this->overwrite == FALSE)
+ if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name)))
{
- $this->file_name = $this->set_filename($this->upload_path, $this->file_name);
-
- if ($this->file_name === FALSE)
- {
- return FALSE;
- }
+ return FALSE;
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
- * embedded within a file. Scripts can easily
+ * embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
- if ($this->xss_clean)
+ if ($this->xss_clean && $this->do_xss_clean() === FALSE)
{
- if ($this->do_xss_clean() === FALSE)
- {
- $this->set_error('upload_unable_to_write_file');
- return FALSE;
- }
+ $this->set_error('upload_unable_to_write_file', 'error');
+ return FALSE;
}
/*
* Move the file to the final destination
* To deal with different server configurations
- * we'll attempt to use copy() first. If that fails
- * we'll use move_uploaded_file(). One of the two should
+ * we'll attempt to use copy() first. If that fails
+ * we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
{
if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
{
- $this->set_error('upload_destination_error');
+ $this->set_error('upload_destination_error', 'error');
return FALSE;
}
}
@@ -322,7 +575,7 @@ class CI_Upload {
/*
* Set the finalized image dimensions
* This sets the image width/height (assuming the
- * file was an image). We use this information
+ * file was an image). We use this information
* in the "data" function.
*/
$this->set_image_properties($this->upload_path.$this->file_name);
@@ -338,26 +591,34 @@ class CI_Upload {
* Returns an associative array containing all of the information
* related to the upload, allowing the developer easy access in one array.
*
- * @return array
+ * @param string $index
+ * @return mixed
*/
- public function data()
+ public function data($index = NULL)
{
- return array (
- 'file_name' => $this->file_name,
- 'file_type' => $this->file_type,
- 'file_path' => $this->upload_path,
- 'full_path' => $this->upload_path.$this->file_name,
- 'raw_name' => str_replace($this->file_ext, '', $this->file_name),
- 'orig_name' => $this->orig_name,
- 'client_name' => $this->client_name,
- 'file_ext' => $this->file_ext,
- 'file_size' => $this->file_size,
- 'is_image' => $this->is_image(),
- 'image_width' => $this->image_width,
- 'image_height' => $this->image_height,
- 'image_type' => $this->image_type,
- 'image_size_str' => $this->image_size_str,
- );
+ $data = array(
+ 'file_name' => $this->file_name,
+ 'file_type' => $this->file_type,
+ 'file_path' => $this->upload_path,
+ 'full_path' => $this->upload_path.$this->file_name,
+ 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)),
+ 'orig_name' => $this->orig_name,
+ 'client_name' => $this->client_name,
+ 'file_ext' => $this->file_ext,
+ 'file_size' => $this->file_size,
+ 'is_image' => $this->is_image(),
+ 'image_width' => $this->image_width,
+ 'image_height' => $this->image_height,
+ 'image_type' => $this->image_type,
+ 'image_size_str' => $this->image_size_str,
+ );
+
+ if ( ! empty($index))
+ {
+ return isset($data[$index]) ? $data[$index] : NULL;
+ }
+
+ return $data;
}
// --------------------------------------------------------------------
@@ -365,13 +626,14 @@ class CI_Upload {
/**
* Set Upload Path
*
- * @param string
- * @return void
+ * @param string $path
+ * @return CI_Upload
*/
public function set_upload_path($path)
{
// Make sure it has a trailing slash
$this->upload_path = rtrim($path, '/').'/';
+ return $this;
}
// --------------------------------------------------------------------
@@ -383,19 +645,18 @@ class CI_Upload {
* existence of a file with the same name. If found, it will append a
* number to the end of the filename to avoid overwriting a pre-existing file.
*
- * @param string
- * @param string
+ * @param string $path
+ * @param string $filename
* @return string
*/
public function set_filename($path, $filename)
{
- if ($this->encrypt_name == TRUE)
+ if ($this->encrypt_name === TRUE)
{
- mt_srand();
$filename = md5(uniqid(mt_rand())).$this->file_ext;
}
- if ( ! file_exists($path.$filename))
+ if ($this->overwrite === TRUE OR ! file_exists($path.$filename))
{
return $filename;
}
@@ -403,7 +664,7 @@ class CI_Upload {
$filename = str_replace($this->file_ext, '', $filename);
$new_filename = '';
- for ($i = 1; $i < 100; $i++)
+ for ($i = 1; $i < $this->max_filename_increment; $i++)
{
if ( ! file_exists($path.$filename.$i.$this->file_ext))
{
@@ -412,9 +673,9 @@ class CI_Upload {
}
}
- if ($new_filename == '')
+ if ($new_filename === '')
{
- $this->set_error('upload_bad_filename');
+ $this->set_error('upload_bad_filename', 'debug');
return FALSE;
}
else
@@ -428,12 +689,29 @@ class CI_Upload {
/**
* Set Maximum File Size
*
- * @param integer
- * @return void
+ * @param int $n
+ * @return CI_Upload
*/
public function set_max_filesize($n)
{
- $this->max_size = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_size = ($n < 0) ? 0 : (int) $n;
+ return $this;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Set Maximum File Size
+ *
+ * An internal alias to set_max_filesize() to help with configuration
+ * as initialize() will look for a set_<property_name>() method ...
+ *
+ * @param int $n
+ * @return CI_Upload
+ */
+ protected function set_max_size($n)
+ {
+ return $this->set_max_filesize($n);
}
// --------------------------------------------------------------------
@@ -441,12 +719,13 @@ class CI_Upload {
/**
* Set Maximum File Name Length
*
- * @param integer
- * @return void
+ * @param int $n
+ * @return CI_Upload
*/
public function set_max_filename($n)
{
- $this->max_filename = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_filename = ($n < 0) ? 0 : (int) $n;
+ return $this;
}
// --------------------------------------------------------------------
@@ -454,12 +733,13 @@ class CI_Upload {
/**
* Set Maximum Image Width
*
- * @param integer
- * @return void
+ * @param int $n
+ * @return CI_Upload
*/
public function set_max_width($n)
{
- $this->max_width = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_width = ($n < 0) ? 0 : (int) $n;
+ return $this;
}
// --------------------------------------------------------------------
@@ -467,12 +747,41 @@ class CI_Upload {
/**
* Set Maximum Image Height
*
- * @param integer
- * @return void
+ * @param int $n
+ * @return CI_Upload
*/
public function set_max_height($n)
{
- $this->max_height = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_height = ($n < 0) ? 0 : (int) $n;
+ return $this;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Set minimum image width
+ *
+ * @param int $n
+ * @return CI_Upload
+ */
+ public function set_min_width($n)
+ {
+ $this->min_width = ($n < 0) ? 0 : (int) $n;
+ return $this;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Set minimum image height
+ *
+ * @param int $n
+ * @return CI_Upload
+ */
+ public function set_min_height($n)
+ {
+ $this->min_height = ($n < 0) ? 0 : (int) $n;
+ return $this;
}
// --------------------------------------------------------------------
@@ -480,17 +789,15 @@ class CI_Upload {
/**
* Set Allowed File Types
*
- * @param string
- * @return void
+ * @param mixed $types
+ * @return CI_Upload
*/
public function set_allowed_types($types)
{
- if ( ! is_array($types) && $types == '*')
- {
- $this->allowed_types = '*';
- return;
- }
- $this->allowed_types = explode('|', $types);
+ $this->allowed_types = (is_array($types) OR $types === '*')
+ ? $types
+ : explode('|', $types);
+ return $this;
}
// --------------------------------------------------------------------
@@ -500,28 +807,25 @@ class CI_Upload {
*
* Uses GD to determine the width/height/type of image
*
- * @param string
- * @return void
+ * @param string $path
+ * @return CI_Upload
*/
public function set_image_properties($path = '')
{
- if ( ! $this->is_image())
- {
- return;
- }
-
- if (function_exists('getimagesize'))
+ if ($this->is_image() && function_exists('getimagesize'))
{
if (FALSE !== ($D = @getimagesize($path)))
{
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
- $this->image_width = $D['0'];
- $this->image_height = $D['1'];
- $this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
- $this->image_size_str = $D['3']; // string containing height and width
+ $this->image_width = $D[0];
+ $this->image_height = $D[1];
+ $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown';
+ $this->image_size_str = $D[3]; // string containing height and width
}
}
+
+ return $this;
}
// --------------------------------------------------------------------
@@ -532,12 +836,13 @@ class CI_Upload {
* Enables the XSS flag so that the file that was uploaded
* will be run through the XSS filter.
*
- * @param bool
- * @return void
+ * @param bool $flag
+ * @return CI_Upload
*/
public function set_xss_clean($flag = FALSE)
{
- $this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
+ $this->xss_clean = ($flag === TRUE);
+ return $this;
}
// --------------------------------------------------------------------
@@ -559,19 +864,14 @@ class CI_Upload {
{
$this->file_type = 'image/png';
}
-
- if (in_array($this->file_type, $jpeg_mimes))
+ elseif (in_array($this->file_type, $jpeg_mimes))
{
$this->file_type = 'image/jpeg';
}
- $img_mimes = array(
- 'image/gif',
- 'image/jpeg',
- 'image/png',
- );
+ $img_mimes = array('image/gif', 'image/jpeg', 'image/png');
- return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
+ return in_array($this->file_type, $img_mimes, TRUE);
}
// --------------------------------------------------------------------
@@ -579,37 +879,33 @@ class CI_Upload {
/**
* Verify that the filetype is allowed
*
+ * @param bool $ignore_mime
* @return bool
*/
public function is_allowed_filetype($ignore_mime = FALSE)
{
- if ($this->allowed_types == '*')
+ if ($this->allowed_types === '*')
{
return TRUE;
}
- if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
+ if (empty($this->allowed_types) OR ! is_array($this->allowed_types))
{
- $this->set_error('upload_no_file_types');
+ $this->set_error('upload_no_file_types', 'debug');
return FALSE;
}
$ext = strtolower(ltrim($this->file_ext, '.'));
- if ( ! in_array($ext, $this->allowed_types))
+ if ( ! in_array($ext, $this->allowed_types, TRUE))
{
return FALSE;
}
// Images get some additional checks
- $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');
-
- if (in_array($ext, $image_types))
+ if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE)
{
- if (getimagesize($this->file_temp) === FALSE)
- {
- return FALSE;
- }
+ return FALSE;
}
if ($ignore_mime === TRUE)
@@ -617,18 +913,11 @@ class CI_Upload {
return TRUE;
}
- $mime = $this->mimes_types($ext);
-
- if (is_array($mime))
- {
- if (in_array($this->file_type, $mime, TRUE))
- {
- return TRUE;
- }
- }
- elseif ($mime == $this->file_type)
+ if (isset($this->_mimes[$ext]))
{
- return TRUE;
+ return is_array($this->_mimes[$ext])
+ ? in_array($this->file_type, $this->_mimes[$ext], TRUE)
+ : ($this->_mimes[$ext] === $this->file_type);
}
return FALSE;
@@ -643,14 +932,7 @@ class CI_Upload {
*/
public function is_allowed_filesize()
{
- if ($this->max_size != 0 AND $this->file_size > $this->max_size)
- {
- return FALSE;
- }
- else
- {
- return TRUE;
- }
+ return ($this->max_size === 0 OR $this->max_size > $this->file_size);
}
// --------------------------------------------------------------------
@@ -671,17 +953,25 @@ class CI_Upload {
{
$D = @getimagesize($this->file_temp);
- if ($this->max_width > 0 AND $D['0'] > $this->max_width)
+ if ($this->max_width > 0 && $D[0] > $this->max_width)
{
return FALSE;
}
- if ($this->max_height > 0 AND $D['1'] > $this->max_height)
+ if ($this->max_height > 0 && $D[1] > $this->max_height)
{
return FALSE;
}
- return TRUE;
+ if ($this->min_width > 0 && $D[0] < $this->min_width)
+ {
+ return FALSE;
+ }
+
+ if ($this->min_height > 0 && $D[1] < $this->min_height)
+ {
+ return FALSE;
+ }
}
return TRUE;
@@ -694,35 +984,34 @@ class CI_Upload {
*
* Verifies that it is a valid upload path with proper permissions.
*
- *
* @return bool
*/
public function validate_upload_path()
{
- if ($this->upload_path == '')
+ if ($this->upload_path === '')
{
- $this->set_error('upload_no_filepath');
+ $this->set_error('upload_no_filepath', 'error');
return FALSE;
}
- if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE)
+ if (realpath($this->upload_path) !== FALSE)
{
- $this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
+ $this->upload_path = str_replace('\\', '/', realpath($this->upload_path));
}
- if ( ! @is_dir($this->upload_path))
+ if ( ! is_dir($this->upload_path))
{
- $this->set_error('upload_no_filepath');
+ $this->set_error('upload_no_filepath', 'error');
return FALSE;
}
if ( ! is_really_writable($this->upload_path))
{
- $this->set_error('upload_not_writable');
+ $this->set_error('upload_not_writable', 'error');
return FALSE;
}
- $this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path);
+ $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path);
return TRUE;
}
@@ -731,57 +1020,20 @@ class CI_Upload {
/**
* Extract the file extension
*
- * @param string
+ * @param string $filename
* @return string
*/
public function get_extension($filename)
{
$x = explode('.', $filename);
- return '.'.end($x);
- }
- // --------------------------------------------------------------------
+ if (count($x) === 1)
+ {
+ return '';
+ }
- /**
- * Clean the file name for security
- *
- * @param string
- * @return string
- */
- public function clean_file_name($filename)
- {
- $bad = array(
- "<!--",
- "-->",
- "'",
- "<",
- ">",
- '"',
- '&',
- '$',
- '=',
- ';',
- '?',
- '/',
- "%20",
- "%22",
- "%3c", // <
- "%253c", // <
- "%3e", // >
- "%0e", // >
- "%28", // (
- "%29", // )
- "%2528", // (
- "%26", // &
- "%24", // $
- "%3f", // ?
- "%3b", // ;
- "%3d" // =
- );
-
- $filename = str_replace($bad, '', $filename);
-
- return stripslashes($filename);
+ $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x);
+ return '.'.$ext;
}
// --------------------------------------------------------------------
@@ -789,7 +1041,8 @@ class CI_Upload {
/**
* Limit the File Name Length
*
- * @param string
+ * @param string $filename
+ * @param int $length
* @return string
*/
public function limit_filename_length($filename, $length)
@@ -819,7 +1072,7 @@ class CI_Upload {
* I'm not sure that it won't negatively affect certain files in unexpected ways,
* but so far I haven't found that it causes trouble.
*
- * @return void
+ * @return string
*/
public function do_xss_clean()
{
@@ -830,23 +1083,34 @@ class CI_Upload {
return FALSE;
}
- if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '')
+ if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0)
{
- $current = ini_get('memory_limit') * 1024 * 1024;
-
- // There was a bug/behavioural change in PHP 5.2, where numbers over one million get output
- // into scientific notation. number_format() ensures this number is an integer
- // http://bugs.php.net/bug.php?id=43053
-
- $new_memory = number_format(ceil(filesize($file) + $current), 0, '.', '');
+ $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890'));
+ if ( ! empty($memory_limit[1]))
+ {
+ switch ($memory_limit[1][0])
+ {
+ case 'g':
+ case 'G':
+ $memory_limit[0] *= 1024 * 1024 * 1024;
+ break;
+ case 'm':
+ case 'M':
+ $memory_limit[0] *= 1024 * 1024;
+ break;
+ default:
+ break;
+ }
+ }
- ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net
+ $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]);
+ ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net
}
// If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but
// IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
- // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
- // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
+ // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
+ // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
// processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
// attempted XSS attack.
@@ -864,14 +1128,8 @@ class CI_Upload {
// <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title
// title is basically just in SVG, but we filter it anyhow
- if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes))
- {
- return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good
- }
- else
- {
- return FALSE;
- }
+ // if it's an image or no "triggers" detected in the first 256 bytes - we're good
+ return ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes);
}
if (($data = @file_get_contents($file)) === FALSE)
@@ -879,8 +1137,7 @@ class CI_Upload {
return FALSE;
}
- $CI =& get_instance();
- return $CI->security->xss_clean($data, TRUE);
+ return $this->_CI->security->xss_clean($data, TRUE);
}
// --------------------------------------------------------------------
@@ -888,29 +1145,22 @@ class CI_Upload {
/**
* Set an error message
*
- * @param string
- * @return void
+ * @param string $msg
+ * @return CI_Upload
*/
- public function set_error($msg)
+ public function set_error($msg, $log_level = 'error')
{
- $CI =& get_instance();
- $CI->lang->load('upload');
+ $this->_CI->lang->load('upload');
- if (is_array($msg))
- {
- foreach ($msg as $val)
- {
- $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val);
- $this->error_msg[] = $msg;
- log_message('error', $msg);
- }
- }
- else
+ is_array($msg) OR $msg = array($msg);
+ foreach ($msg as $val)
{
- $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
+ $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val);
$this->error_msg[] = $msg;
- log_message('error', $msg);
+ log_message($log_level, $msg);
}
+
+ return $this;
}
// --------------------------------------------------------------------
@@ -918,56 +1168,13 @@ class CI_Upload {
/**
* Display the error message
*
- * @param string
- * @param string
+ * @param string $open
+ * @param string $close
* @return string
*/
public function display_errors($open = '<p>', $close = '</p>')
{
- $str = '';
- foreach ($this->error_msg as $val)
- {
- $str .= $open.$val.$close;
- }
-
- return $str;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * List of Mime Types
- *
- * This is a list of mime types. We use it to validate
- * the "allowed types" set by the developer
- *
- * @param string
- * @return string
- */
- public function mimes_types($mime)
- {
- global $mimes;
-
- if (count($this->mimes) == 0)
- {
- if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
- {
- include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
- }
- elseif (is_file(APPPATH.'config/mimes.php'))
- {
- include(APPPATH.'config//mimes.php');
- }
- else
- {
- return FALSE;
- }
-
- $this->mimes = $mimes;
- unset($mimes);
- }
-
- return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
+ return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : '';
}
// --------------------------------------------------------------------
@@ -975,38 +1182,24 @@ class CI_Upload {
/**
* Prep Filename
*
- * Prevents possible script execution from Apache's handling of files multiple extensions
- * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
+ * Prevents possible script execution from Apache's handling
+ * of files' multiple extensions.
+ *
+ * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
*
- * @param string
+ * @param string $filename
* @return string
*/
protected function _prep_filename($filename)
{
- if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*')
+ if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE)
{
return $filename;
}
- $parts = explode('.', $filename);
- $ext = array_pop($parts);
- $filename = array_shift($parts);
-
- foreach ($parts as $part)
- {
- if ( ! in_array(strtolower($part), $this->allowed_types) OR $this->mimes_types(strtolower($part)) === FALSE)
- {
- $filename .= '.'.$part.'_';
- }
- else
- {
- $filename .= '.'.$part;
- }
- }
-
- $filename .= '.'.$ext;
-
- return $filename;
+ $ext = substr($filename, $ext_pos);
+ $filename = substr($filename, 0, $ext_pos);
+ return str_replace('.', '_', $filename).$ext;
}
// --------------------------------------------------------------------
@@ -1017,7 +1210,7 @@ class CI_Upload {
* Detects the (actual) MIME type of the uploaded file, if possible.
* The input array is expected to be $_FILES[$field]
*
- * @param array
+ * @param array $file
* @return void
*/
protected function _file_mime_type($file)
@@ -1025,14 +1218,17 @@ class CI_Upload {
// We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
$regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';
- /* Fileinfo extension - most reliable method
+ /**
+ * Fileinfo extension - most reliable method
*
- * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the
- * more convenient FILEINFO_MIME_TYPE flag doesn't exist.
+ * Apparently XAMPP, CentOS, cPanel and who knows what
+ * other PHP distribution channels EXPLICITLY DISABLE
+ * ext/fileinfo, which is otherwise enabled by default
+ * since PHP 5.3 ...
*/
if (function_exists('finfo_file'))
{
- $finfo = finfo_open(FILEINFO_MIME);
+ $finfo = @finfo_open(FILEINFO_MIME);
if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system
{
$mime = @finfo_file($finfo, $file['tmp_name']);
@@ -1059,16 +1255,18 @@ class CI_Upload {
* Notes:
* - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
* - many system admins would disable the exec(), shell_exec(), popen() and similar functions
- * due to security concerns, hence the function_exists() checks
+ * due to security concerns, hence the function_usable() checks
*/
if (DIRECTORY_SEPARATOR !== '\\')
{
- $cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1';
+ $cmd = function_exists('escapeshellarg')
+ ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1'
+ : 'file --brief --mime '.$file['tmp_name'].' 2>&1';
- if (function_exists('exec'))
+ if (function_usable('exec'))
{
/* This might look confusing, as $mime is being populated with all of the output when set in the second parameter.
- * However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites
+ * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites
* anything that could already be set for $mime previously. This effectively makes the second parameter a dummy
* value, which is only put to allow us to get the return status code.
*/
@@ -1080,7 +1278,7 @@ class CI_Upload {
}
}
- if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec'))
+ if ( ! ini_get('safe_mode') && function_usable('shell_exec'))
{
$mime = @shell_exec($cmd);
if (strlen($mime) > 0)
@@ -1094,7 +1292,7 @@ class CI_Upload {
}
}
- if (function_exists('popen'))
+ if (function_usable('popen'))
{
$proc = @popen($cmd, 'r');
if (is_resource($proc))
@@ -1127,10 +1325,4 @@ class CI_Upload {
$this->file_type = $file['type'];
}
- // --------------------------------------------------------------------
-
}
-// END Upload Class
-
-/* End of file Upload.php */
-/* Location: ./system/libraries/Upload.php */