1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008, 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
32 var $max_filename = 0;
33 var $allowed_types = "";
40 var $upload_path = "";
41 var $overwrite = FALSE;
42 var $encrypt_name = FALSE;
43 var $is_image = FALSE;
44 var $image_width = '';
45 var $image_height = '';
47 var $image_size_str = '';
48 var $error_msg = array();
50 var $remove_spaces = TRUE;
51 var $xss_clean = FALSE;
52 var $temp_prefix = "temp_file_";
59 function CI_Upload($props = array())
61 if (count($props) > 0)
63 $this->initialize($props);
66 log_message('debug', "Upload Class Initialized");
69 // --------------------------------------------------------------------
72 * Initialize preferences
78 function initialize($config = array())
85 'allowed_types' => "",
94 'encrypt_name' => FALSE,
99 'image_size_str' => '',
100 'error_msg' => array(),
102 'remove_spaces' => TRUE,
103 'xss_clean' => FALSE,
104 'temp_prefix' => "temp_file_"
108 foreach ($defaults as $key => $val)
110 if (isset($config[$key]))
112 $method = 'set_'.$key;
113 if (method_exists($this, $method))
115 $this->$method($config[$key]);
119 $this->$key = $config[$key];
129 // --------------------------------------------------------------------
132 * Perform the file upload
137 function do_upload($field = 'userfile')
139 // Is $_FILES[$field] set? If not, no reason to continue.
140 if ( ! isset($_FILES[$field]))
142 $this->set_error('upload_no_file_selected');
146 // Is the upload path valid?
147 if ( ! $this->validate_upload_path())
149 // errors will already be set by validate_upload_path() so just return FALSE
153 // Was the file able to be uploaded? If not, determine the reason why.
154 if ( ! is_uploaded_file($_FILES[$field]['tmp_name']))
156 $error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
160 case 1: // UPLOAD_ERR_INI_SIZE
161 $this->set_error('upload_file_exceeds_limit');
163 case 2: // UPLOAD_ERR_FORM_SIZE
164 $this->set_error('upload_file_exceeds_form_limit');
166 case 3: // UPLOAD_ERR_PARTIAL
167 $this->set_error('upload_file_partial');
169 case 4: // UPLOAD_ERR_NO_FILE
170 $this->set_error('upload_no_file_selected');
172 case 6: // UPLOAD_ERR_NO_TMP_DIR
173 $this->set_error('upload_no_temp_directory');
175 case 7: // UPLOAD_ERR_CANT_WRITE
176 $this->set_error('upload_unable_to_write_file');
178 case 8: // UPLOAD_ERR_EXTENSION
179 $this->set_error('upload_stopped_by_extension');
181 default : $this->set_error('upload_no_file_selected');
188 // Set the uploaded data as class variables
189 $this->file_temp = $_FILES[$field]['tmp_name'];
190 $this->file_name = $this->_prep_filename($_FILES[$field]['name']);
191 $this->file_size = $_FILES[$field]['size'];
192 $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
193 $this->file_type = strtolower($this->file_type);
194 $this->file_ext = $this->get_extension($_FILES[$field]['name']);
196 // Convert the file size to kilobytes
197 if ($this->file_size > 0)
199 $this->file_size = round($this->file_size/1024, 2);
202 // Is the file type allowed to be uploaded?
203 if ( ! $this->is_allowed_filetype())
205 $this->set_error('upload_invalid_filetype');
209 // Is the file size within the allowed maximum?
210 if ( ! $this->is_allowed_filesize())
212 $this->set_error('upload_invalid_filesize');
216 // Are the image dimensions within the allowed size?
217 // Note: This can fail if the server has an open_basdir restriction.
218 if ( ! $this->is_allowed_dimensions())
220 $this->set_error('upload_invalid_dimensions');
224 // Sanitize the file name for security
225 $this->file_name = $this->clean_file_name($this->file_name);
227 // Truncate the file name if it's too long
228 if ($this->max_filename > 0)
230 $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
233 // Remove white spaces in the name
234 if ($this->remove_spaces == TRUE)
236 $this->file_name = preg_replace("/\s+/", "_", $this->file_name);
240 * Validate the file name
241 * This function appends an number onto the end of
242 * the file if one with the same name already exists.
243 * If it returns false there was a problem.
245 $this->orig_name = $this->file_name;
247 if ($this->overwrite == FALSE)
249 $this->file_name = $this->set_filename($this->upload_path, $this->file_name);
251 if ($this->file_name === FALSE)
258 * Move the file to the final destination
259 * To deal with different server configurations
260 * we'll attempt to use copy() first. If that fails
261 * we'll use move_uploaded_file(). One of the two should
262 * reliably work in most environments
264 if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
266 if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
268 $this->set_error('upload_destination_error');
274 * Run the file through the XSS hacking filter
275 * This helps prevent malicious code from being
276 * embedded within a file. Scripts can easily
277 * be disguised as images or other file types.
279 if ($this->xss_clean == TRUE)
281 $this->do_xss_clean();
285 * Set the finalized image dimensions
286 * This sets the image width/height (assuming the
287 * file was an image). We use this information
288 * in the "data" function.
290 $this->set_image_properties($this->upload_path.$this->file_name);
295 // --------------------------------------------------------------------
298 * Finalized Data Array
300 * Returns an associative array containing all of the information
301 * related to the upload, allowing the developer easy access in one array.
309 'file_name' => $this->file_name,
310 'file_type' => $this->file_type,
311 'file_path' => $this->upload_path,
312 'full_path' => $this->upload_path.$this->file_name,
313 'raw_name' => str_replace($this->file_ext, '', $this->file_name),
314 'orig_name' => $this->orig_name,
315 'file_ext' => $this->file_ext,
316 'file_size' => $this->file_size,
317 'is_image' => $this->is_image(),
318 'image_width' => $this->image_width,
319 'image_height' => $this->image_height,
320 'image_type' => $this->image_type,
321 'image_size_str' => $this->image_size_str,
325 // --------------------------------------------------------------------
334 function set_upload_path($path)
336 // Make sure it has a trailing slash
337 $this->upload_path = rtrim($path, '/').'/';
340 // --------------------------------------------------------------------
345 * This function takes a filename/path as input and looks for the
346 * existence of a file with the same name. If found, it will append a
347 * number to the end of the filename to avoid overwriting a pre-existing file.
354 function set_filename($path, $filename)
356 if ($this->encrypt_name == TRUE)
359 $filename = md5(uniqid(mt_rand())).$this->file_ext;
362 if ( ! file_exists($path.$filename))
367 $filename = str_replace($this->file_ext, '', $filename);
370 for ($i = 1; $i < 100; $i++)
372 if ( ! file_exists($path.$filename.$i.$this->file_ext))
374 $new_filename = $filename.$i.$this->file_ext;
379 if ($new_filename == '')
381 $this->set_error('upload_bad_filename');
386 return $new_filename;
390 // --------------------------------------------------------------------
393 * Set Maximum File Size
399 function set_max_filesize($n)
401 $this->max_size = ((int) $n < 0) ? 0: (int) $n;
404 // --------------------------------------------------------------------
407 * Set Maximum File Name Length
413 function set_max_filename($n)
415 $this->max_filename = ((int) $n < 0) ? 0: (int) $n;
418 // --------------------------------------------------------------------
421 * Set Maximum Image Width
427 function set_max_width($n)
429 $this->max_width = ((int) $n < 0) ? 0: (int) $n;
432 // --------------------------------------------------------------------
435 * Set Maximum Image Height
441 function set_max_height($n)
443 $this->max_height = ((int) $n < 0) ? 0: (int) $n;
446 // --------------------------------------------------------------------
449 * Set Allowed File Types
455 function set_allowed_types($types)
457 $this->allowed_types = explode('|', $types);
460 // --------------------------------------------------------------------
463 * Set Image Properties
465 * Uses GD to determine the width/height/type of image
471 function set_image_properties($path = '')
473 if ( ! $this->is_image())
478 if (function_exists('getimagesize'))
480 if (FALSE !== ($D = @getimagesize($path)))
482 $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
484 $this->image_width = $D['0'];
485 $this->image_height = $D['1'];
486 $this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
487 $this->image_size_str = $D['3']; // string containing height and width
492 // --------------------------------------------------------------------
497 * Enables the XSS flag so that the file that was uploaded
498 * will be run through the XSS filter.
504 function set_xss_clean($flag = FALSE)
506 $this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
509 // --------------------------------------------------------------------
519 // IE will sometimes return odd mime-types during upload, so here we just standardize all
520 // jpegs or pngs to the same file type.
522 $png_mimes = array('image/x-png');
523 $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');
525 if (in_array($this->file_type, $png_mimes))
527 $this->file_type = 'image/png';
530 if (in_array($this->file_type, $jpeg_mimes))
532 $this->file_type = 'image/jpeg';
541 return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
544 // --------------------------------------------------------------------
547 * Verify that the filetype is allowed
552 function is_allowed_filetype()
554 if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
556 $this->set_error('upload_no_file_types');
560 foreach ($this->allowed_types as $val)
562 $mime = $this->mimes_types(strtolower($val));
566 if (in_array($this->file_type, $mime, TRUE))
573 if ($mime == $this->file_type)
583 // --------------------------------------------------------------------
586 * Verify that the file is within the allowed size
591 function is_allowed_filesize()
593 if ($this->max_size != 0 AND $this->file_size > $this->max_size)
603 // --------------------------------------------------------------------
606 * Verify that the image is within the allowed width/height
611 function is_allowed_dimensions()
613 if ( ! $this->is_image())
618 if (function_exists('getimagesize'))
620 $D = @getimagesize($this->file_temp);
622 if ($this->max_width > 0 AND $D['0'] > $this->max_width)
627 if ($this->max_height > 0 AND $D['1'] > $this->max_height)
638 // --------------------------------------------------------------------
641 * Validate Upload Path
643 * Verifies that it is a valid upload path with proper permissions.
649 function validate_upload_path()
651 if ($this->upload_path == '')
653 $this->set_error('upload_no_filepath');
657 if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE)
659 $this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
662 if ( ! @is_dir($this->upload_path))
664 $this->set_error('upload_no_filepath');
668 if ( ! is_really_writable($this->upload_path))
670 $this->set_error('upload_not_writable');
674 $this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path);
678 // --------------------------------------------------------------------
681 * Extract the file extension
687 function get_extension($filename)
689 $x = explode('.', $filename);
693 // --------------------------------------------------------------------
696 * Clean the file name for security
702 function clean_file_name($filename)
733 $filename = str_replace($bad, '', $filename);
735 return stripslashes($filename);
738 // --------------------------------------------------------------------
741 * Limit the File Name Length
747 function limit_filename_length($filename, $length)
749 if (strlen($filename) < $length)
755 if (strpos($filename, '.') !== FALSE)
757 $parts = explode('.', $filename);
758 $ext = '.'.array_pop($parts);
759 $filename = implode('.', $parts);
762 return substr($filename, 0, ($length - strlen($ext))).$ext;
765 // --------------------------------------------------------------------
768 * Runs the file through the XSS clean function
770 * This prevents people from embedding malicious code in their files.
771 * I'm not sure that it won't negatively affect certain files in unexpected ways,
772 * but so far I haven't found that it causes trouble.
777 function do_xss_clean()
779 $file = $this->upload_path.$this->file_name;
781 if (filesize($file) == 0)
786 if (($data = @file_get_contents($file)) === FALSE)
791 if ( ! $fp = @fopen($file, FOPEN_READ_WRITE))
796 $CI =& get_instance();
797 $data = $CI->input->xss_clean($data);
805 // --------------------------------------------------------------------
808 * Set an error message
814 function set_error($msg)
816 $CI =& get_instance();
817 $CI->lang->load('upload');
821 foreach ($msg as $val)
823 $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val);
824 $this->error_msg[] = $msg;
825 log_message('error', $msg);
830 $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
831 $this->error_msg[] = $msg;
832 log_message('error', $msg);
836 // --------------------------------------------------------------------
839 * Display the error message
846 function display_errors($open = '<p>', $close = '</p>')
849 foreach ($this->error_msg as $val)
851 $str .= $open.$val.$close;
857 // --------------------------------------------------------------------
862 * This is a list of mime types. We use it to validate
863 * the "allowed types" set by the developer
869 function mimes_types($mime)
873 if (count($this->mimes) == 0)
875 if (@require_once(APPPATH.'config/mimes'.EXT))
877 $this->mimes = $mimes;
882 return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
885 // --------------------------------------------------------------------
890 * Prevents possible script execution from Apache's handling of files multiple extensions
891 * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
897 function _prep_filename($filename)
899 if (strpos($filename, '.') === FALSE)
904 $parts = explode('.', $filename);
905 $ext = array_pop($parts);
906 $filename = array_shift($parts);
908 foreach ($parts as $part)
910 if ($this->mimes_types(strtolower($part)) === FALSE)
912 $filename .= '.'.$part.'_';
916 $filename .= '.'.$part;
920 $filename .= '.'.$ext;
925 // --------------------------------------------------------------------
930 /* End of file Upload.php */
931 /* Location: ./system/libraries/Upload.php */