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