1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
19 * File Uploading Class
21 * @package CodeIgniter
22 * @subpackage Libraries
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/libraries/file_uploading.html
30 public $max_width = 0;
31 public $max_height = 0;
32 public $max_filename = 0;
33 public $allowed_types = "";
34 public $file_temp = "";
35 public $file_name = "";
36 public $orig_name = "";
37 public $file_type = "";
38 public $file_size = "";
39 public $file_ext = "";
40 public $upload_path = "";
41 public $overwrite = FALSE;
42 public $encrypt_name = FALSE;
43 public $is_image = FALSE;
44 public $image_width = '';
45 public $image_height = '';
46 public $image_type = '';
47 public $image_size_str = '';
48 public $error_msg = array();
49 public $mimes = array();
50 public $remove_spaces = TRUE;
51 public $xss_clean = FALSE;
52 public $temp_prefix = "temp_file_";
53 public $client_name = '';
55 protected $_file_name_override = '';
62 public function __construct($props = array())
64 if (count($props) > 0)
66 $this->initialize($props);
69 log_message('debug', "Upload Class Initialized");
72 // --------------------------------------------------------------------
75 * Initialize preferences
80 public function initialize($config = array())
87 'allowed_types' => "",
96 'encrypt_name' => FALSE,
101 'image_size_str' => '',
102 'error_msg' => array(),
104 'remove_spaces' => TRUE,
105 'xss_clean' => FALSE,
106 'temp_prefix' => "temp_file_",
111 foreach ($defaults as $key => $val)
113 if (isset($config[$key]))
115 $method = 'set_'.$key;
116 if (method_exists($this, $method))
118 $this->$method($config[$key]);
122 $this->$key = $config[$key];
131 // if a file_name was provided in the config, use it instead of the user input
132 // supplied file name for all uploads until initialized again
133 $this->_file_name_override = $this->file_name;
136 // --------------------------------------------------------------------
139 * Perform the file upload
143 public function do_upload($field = 'userfile')
146 // Is $_FILES[$field] set? If not, no reason to continue.
147 if ( ! isset($_FILES[$field]))
149 $this->set_error('upload_no_file_selected');
153 // Is the upload path valid?
154 if ( ! $this->validate_upload_path())
156 // errors will already be set by validate_upload_path() so just return FALSE
160 // Was the file able to be uploaded? If not, determine the reason why.
161 if ( ! is_uploaded_file($_FILES[$field]['tmp_name']))
163 $error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
167 case 1: // UPLOAD_ERR_INI_SIZE
168 $this->set_error('upload_file_exceeds_limit');
170 case 2: // UPLOAD_ERR_FORM_SIZE
171 $this->set_error('upload_file_exceeds_form_limit');
173 case 3: // UPLOAD_ERR_PARTIAL
174 $this->set_error('upload_file_partial');
176 case 4: // UPLOAD_ERR_NO_FILE
177 $this->set_error('upload_no_file_selected');
179 case 6: // UPLOAD_ERR_NO_TMP_DIR
180 $this->set_error('upload_no_temp_directory');
182 case 7: // UPLOAD_ERR_CANT_WRITE
183 $this->set_error('upload_unable_to_write_file');
185 case 8: // UPLOAD_ERR_EXTENSION
186 $this->set_error('upload_stopped_by_extension');
188 default : $this->set_error('upload_no_file_selected');
196 // Set the uploaded data as class variables
197 $this->file_temp = $_FILES[$field]['tmp_name'];
198 $this->file_size = $_FILES[$field]['size'];
199 $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
200 $this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
201 $this->file_name = $this->_prep_filename($_FILES[$field]['name']);
202 $this->file_ext = $this->get_extension($this->file_name);
203 $this->client_name = $this->file_name;
205 // Is the file type allowed to be uploaded?
206 if ( ! $this->is_allowed_filetype())
208 $this->set_error('upload_invalid_filetype');
212 // if we're overriding, let's now make sure the new name and type is allowed
213 if ($this->_file_name_override != '')
215 $this->file_name = $this->_prep_filename($this->_file_name_override);
217 // If no extension was provided in the file_name config item, use the uploaded one
218 if (strpos($this->_file_name_override, '.') === FALSE)
220 $this->file_name .= $this->file_ext;
223 // An extension was provided, lets have it!
226 $this->file_ext = $this->get_extension($this->_file_name_override);
229 if ( ! $this->is_allowed_filetype(TRUE))
231 $this->set_error('upload_invalid_filetype');
236 // Convert the file size to kilobytes
237 if ($this->file_size > 0)
239 $this->file_size = round($this->file_size/1024, 2);
242 // Is the file size within the allowed maximum?
243 if ( ! $this->is_allowed_filesize())
245 $this->set_error('upload_invalid_filesize');
249 // Are the image dimensions within the allowed size?
250 // Note: This can fail if the server has an open_basdir restriction.
251 if ( ! $this->is_allowed_dimensions())
253 $this->set_error('upload_invalid_dimensions');
257 // Sanitize the file name for security
258 $this->file_name = $this->clean_file_name($this->file_name);
260 // Truncate the file name if it's too long
261 if ($this->max_filename > 0)
263 $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
266 // Remove white spaces in the name
267 if ($this->remove_spaces == TRUE)
269 $this->file_name = preg_replace("/\s+/", "_", $this->file_name);
273 * Validate the file name
274 * This function appends an number onto the end of
275 * the file if one with the same name already exists.
276 * If it returns false there was a problem.
278 $this->orig_name = $this->file_name;
280 if ($this->overwrite == FALSE)
282 $this->file_name = $this->set_filename($this->upload_path, $this->file_name);
284 if ($this->file_name === FALSE)
291 * Run the file through the XSS hacking filter
292 * This helps prevent malicious code from being
293 * embedded within a file. Scripts can easily
294 * be disguised as images or other file types.
296 if ($this->xss_clean)
298 if ($this->do_xss_clean() === FALSE)
300 $this->set_error('upload_unable_to_write_file');
306 * Move the file to the final destination
307 * To deal with different server configurations
308 * we'll attempt to use copy() first. If that fails
309 * we'll use move_uploaded_file(). One of the two should
310 * reliably work in most environments
312 if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
314 if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
316 $this->set_error('upload_destination_error');
322 * Set the finalized image dimensions
323 * This sets the image width/height (assuming the
324 * file was an image). We use this information
325 * in the "data" function.
327 $this->set_image_properties($this->upload_path.$this->file_name);
332 // --------------------------------------------------------------------
335 * Finalized Data Array
337 * Returns an associative array containing all of the information
338 * related to the upload, allowing the developer easy access in one array.
342 public function data()
345 'file_name' => $this->file_name,
346 'file_type' => $this->file_type,
347 'file_path' => $this->upload_path,
348 'full_path' => $this->upload_path.$this->file_name,
349 'raw_name' => str_replace($this->file_ext, '', $this->file_name),
350 'orig_name' => $this->orig_name,
351 'client_name' => $this->client_name,
352 'file_ext' => $this->file_ext,
353 'file_size' => $this->file_size,
354 'is_image' => $this->is_image(),
355 'image_width' => $this->image_width,
356 'image_height' => $this->image_height,
357 'image_type' => $this->image_type,
358 'image_size_str' => $this->image_size_str,
362 // --------------------------------------------------------------------
370 public function set_upload_path($path)
372 // Make sure it has a trailing slash
373 $this->upload_path = rtrim($path, '/').'/';
376 // --------------------------------------------------------------------
381 * This function takes a filename/path as input and looks for the
382 * existence of a file with the same name. If found, it will append a
383 * number to the end of the filename to avoid overwriting a pre-existing file.
389 public function set_filename($path, $filename)
391 if ($this->encrypt_name == TRUE)
394 $filename = md5(uniqid(mt_rand())).$this->file_ext;
397 if ( ! file_exists($path.$filename))
402 $filename = str_replace($this->file_ext, '', $filename);
405 for ($i = 1; $i < 100; $i++)
407 if ( ! file_exists($path.$filename.$i.$this->file_ext))
409 $new_filename = $filename.$i.$this->file_ext;
414 if ($new_filename == '')
416 $this->set_error('upload_bad_filename');
421 return $new_filename;
425 // --------------------------------------------------------------------
428 * Set Maximum File Size
433 public function set_max_filesize($n)
435 $this->max_size = ((int) $n < 0) ? 0: (int) $n;
438 // --------------------------------------------------------------------
441 * Set Maximum File Name Length
446 public function set_max_filename($n)
448 $this->max_filename = ((int) $n < 0) ? 0: (int) $n;
451 // --------------------------------------------------------------------
454 * Set Maximum Image Width
459 public function set_max_width($n)
461 $this->max_width = ((int) $n < 0) ? 0: (int) $n;
464 // --------------------------------------------------------------------
467 * Set Maximum Image Height
472 public function set_max_height($n)
474 $this->max_height = ((int) $n < 0) ? 0: (int) $n;
477 // --------------------------------------------------------------------
480 * Set Allowed File Types
485 public function set_allowed_types($types)
487 if ( ! is_array($types) && $types == '*')
489 $this->allowed_types = '*';
492 $this->allowed_types = explode('|', $types);
495 // --------------------------------------------------------------------
498 * Set Image Properties
500 * Uses GD to determine the width/height/type of image
505 public function set_image_properties($path = '')
507 if ( ! $this->is_image())
512 if (function_exists('getimagesize'))
514 if (FALSE !== ($D = @getimagesize($path)))
516 $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
518 $this->image_width = $D['0'];
519 $this->image_height = $D['1'];
520 $this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
521 $this->image_size_str = $D['3']; // string containing height and width
526 // --------------------------------------------------------------------
531 * Enables the XSS flag so that the file that was uploaded
532 * will be run through the XSS filter.
537 public function set_xss_clean($flag = FALSE)
539 $this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
542 // --------------------------------------------------------------------
549 public function is_image()
551 // IE will sometimes return odd mime-types during upload, so here we just standardize all
552 // jpegs or pngs to the same file type.
554 $png_mimes = array('image/x-png');
555 $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');
557 if (in_array($this->file_type, $png_mimes))
559 $this->file_type = 'image/png';
562 if (in_array($this->file_type, $jpeg_mimes))
564 $this->file_type = 'image/jpeg';
573 return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
576 // --------------------------------------------------------------------
579 * Verify that the filetype is allowed
583 public function is_allowed_filetype($ignore_mime = FALSE)
585 if ($this->allowed_types == '*')
590 if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
592 $this->set_error('upload_no_file_types');
596 $ext = strtolower(ltrim($this->file_ext, '.'));
598 if ( ! in_array($ext, $this->allowed_types))
603 // Images get some additional checks
604 $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');
606 if (in_array($ext, $image_types))
608 if (getimagesize($this->file_temp) === FALSE)
614 if ($ignore_mime === TRUE)
619 $mime = $this->mimes_types($ext);
623 if (in_array($this->file_type, $mime, TRUE))
628 elseif ($mime == $this->file_type)
636 // --------------------------------------------------------------------
639 * Verify that the file is within the allowed size
643 public function is_allowed_filesize()
645 if ($this->max_size != 0 AND $this->file_size > $this->max_size)
655 // --------------------------------------------------------------------
658 * Verify that the image is within the allowed width/height
662 public function is_allowed_dimensions()
664 if ( ! $this->is_image())
669 if (function_exists('getimagesize'))
671 $D = @getimagesize($this->file_temp);
673 if ($this->max_width > 0 AND $D['0'] > $this->max_width)
678 if ($this->max_height > 0 AND $D['1'] > $this->max_height)
689 // --------------------------------------------------------------------
692 * Validate Upload Path
694 * Verifies that it is a valid upload path with proper permissions.
699 public function validate_upload_path()
701 if ($this->upload_path == '')
703 $this->set_error('upload_no_filepath');
707 if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE)
709 $this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
712 if ( ! @is_dir($this->upload_path))
714 $this->set_error('upload_no_filepath');
718 if ( ! is_really_writable($this->upload_path))
720 $this->set_error('upload_not_writable');
724 $this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path);
728 // --------------------------------------------------------------------
731 * Extract the file extension
736 public function get_extension($filename)
738 $x = explode('.', $filename);
742 // --------------------------------------------------------------------
745 * Clean the file name for security
750 public function clean_file_name($filename)
781 $filename = str_replace($bad, '', $filename);
783 return stripslashes($filename);
786 // --------------------------------------------------------------------
789 * Limit the File Name Length
794 public function limit_filename_length($filename, $length)
796 if (strlen($filename) < $length)
802 if (strpos($filename, '.') !== FALSE)
804 $parts = explode('.', $filename);
805 $ext = '.'.array_pop($parts);
806 $filename = implode('.', $parts);
809 return substr($filename, 0, ($length - strlen($ext))).$ext;
812 // --------------------------------------------------------------------
815 * Runs the file through the XSS clean function
817 * This prevents people from embedding malicious code in their files.
818 * I'm not sure that it won't negatively affect certain files in unexpected ways,
819 * but so far I haven't found that it causes trouble.
823 public function do_xss_clean()
825 $file = $this->file_temp;
827 if (filesize($file) == 0)
832 if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '')
834 $current = ini_get('memory_limit') * 1024 * 1024;
836 // There was a bug/behavioural change in PHP 5.2, where numbers over one million get output
837 // into scientific notation. number_format() ensures this number is an integer
838 // http://bugs.php.net/bug.php?id=43053
840 $new_memory = number_format(ceil(filesize($file) + $current), 0, '.', '');
842 ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net
845 // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but
846 // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
847 // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
848 // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
849 // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
850 // attempted XSS attack.
852 if (function_exists('getimagesize') && @getimagesize($file) !== FALSE)
854 if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary
856 return FALSE; // Couldn't open the file, return FALSE
859 $opening_bytes = fread($file, 256);
862 // These are known to throw IE into mime-type detection chaos
863 // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title
864 // title is basically just in SVG, but we filter it anyhow
866 if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes))
868 return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good
872 if (($data = @file_get_contents($file)) === FALSE)
877 $CI =& get_instance();
878 return $CI->security->xss_clean($data, TRUE);
881 // --------------------------------------------------------------------
884 * Set an error message
889 public function set_error($msg)
891 $CI =& get_instance();
892 $CI->lang->load('upload');
896 foreach ($msg as $val)
898 $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val);
899 $this->error_msg[] = $msg;
900 log_message('error', $msg);
905 $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
906 $this->error_msg[] = $msg;
907 log_message('error', $msg);
911 // --------------------------------------------------------------------
914 * Display the error message
920 public function display_errors($open = '<p>', $close = '</p>')
923 foreach ($this->error_msg as $val)
925 $str .= $open.$val.$close;
931 // --------------------------------------------------------------------
936 * This is a list of mime types. We use it to validate
937 * the "allowed types" set by the developer
942 public function mimes_types($mime)
946 if (count($this->mimes) == 0)
948 if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes'.EXT))
950 include(APPPATH.'config/'.ENVIRONMENT.'/mimes'.EXT);
952 elseif (is_file(APPPATH.'config/mimes'.EXT))
954 include(APPPATH.'config//mimes'.EXT);
961 $this->mimes = $mimes;
965 return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
968 // --------------------------------------------------------------------
973 * Prevents possible script execution from Apache's handling of files multiple extensions
974 * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
979 protected function _prep_filename($filename)
981 if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*')
986 $parts = explode('.', $filename);
987 $ext = array_pop($parts);
988 $filename = array_shift($parts);
990 foreach ($parts as $part)
992 if ( ! in_array(strtolower($part), $this->allowed_types) OR $this->mimes_types(strtolower($part)) === FALSE)
994 $filename .= '.'.$part.'_';
998 $filename .= '.'.$part;
1002 $filename .= '.'.$ext;
1007 // --------------------------------------------------------------------
1012 /* End of file Upload.php */
1013 /* Location: ./system/libraries/Upload.php */