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_mime_type($_FILES[$field]);
200
$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
201
$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
202
$this->file_name = $this->_prep_filename($_FILES[$field]['name']);
203
$this->file_ext = $this->get_extension($this->file_name);
204
$this->client_name = $this->file_name;
206
// Is the file type allowed to be uploaded?
207
if ( ! $this->is_allowed_filetype())
209
$this->set_error('upload_invalid_filetype');
213
// if we're overriding, let's now make sure the new name and type is allowed
214
if ($this->_file_name_override != '')
216
$this->file_name = $this->_prep_filename($this->_file_name_override);
218
// If no extension was provided in the file_name config item, use the uploaded one
219
if (strpos($this->_file_name_override, '.') === FALSE)
221
$this->file_name .= $this->file_ext;
224
// An extension was provided, lets have it!
227
$this->file_ext = $this->get_extension($this->_file_name_override);
230
if ( ! $this->is_allowed_filetype(TRUE))
232
$this->set_error('upload_invalid_filetype');
237
// Convert the file size to kilobytes
238
if ($this->file_size > 0)
240
$this->file_size = round($this->file_size/1024, 2);
243
// Is the file size within the allowed maximum?
244
if ( ! $this->is_allowed_filesize())
246
$this->set_error('upload_invalid_filesize');
250
// Are the image dimensions within the allowed size?
251
// Note: This can fail if the server has an open_basdir restriction.
252
if ( ! $this->is_allowed_dimensions())
254
$this->set_error('upload_invalid_dimensions');
258
// Sanitize the file name for security
259
$this->file_name = $this->clean_file_name($this->file_name);
261
// Truncate the file name if it's too long
262
if ($this->max_filename > 0)
264
$this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
267
// Remove white spaces in the name
268
if ($this->remove_spaces == TRUE)
270
$this->file_name = preg_replace("/\s+/", "_", $this->file_name);
274
* Validate the file name
275
* This function appends an number onto the end of
276
* the file if one with the same name already exists.
277
* If it returns false there was a problem.
279
$this->orig_name = $this->file_name;
281
if ($this->overwrite == FALSE)
283
$this->file_name = $this->set_filename($this->upload_path, $this->file_name);
285
if ($this->file_name === FALSE)
292
* Run the file through the XSS hacking filter
293
* This helps prevent malicious code from being
294
* embedded within a file. Scripts can easily
295
* be disguised as images or other file types.
297
if ($this->xss_clean)
299
if ($this->do_xss_clean() === FALSE)
301
$this->set_error('upload_unable_to_write_file');
307
* Move the file to the final destination
308
* To deal with different server configurations
309
* we'll attempt to use copy() first. If that fails
310
* we'll use move_uploaded_file(). One of the two should
311
* reliably work in most environments
313
if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
315
if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
317
$this->set_error('upload_destination_error');
323
* Set the finalized image dimensions
324
* This sets the image width/height (assuming the
325
* file was an image). We use this information
326
* in the "data" function.
328
$this->set_image_properties($this->upload_path.$this->file_name);
333
// --------------------------------------------------------------------
336
* Finalized Data Array
338
* Returns an associative array containing all of the information
339
* related to the upload, allowing the developer easy access in one array.
343
public function data()
346
'file_name' => $this->file_name,
347
'file_type' => $this->file_type,
348
'file_path' => $this->upload_path,
349
'full_path' => $this->upload_path.$this->file_name,
350
'raw_name' => str_replace($this->file_ext, '', $this->file_name),
351
'orig_name' => $this->orig_name,
352
'client_name' => $this->client_name,
353
'file_ext' => $this->file_ext,
354
'file_size' => $this->file_size,
355
'is_image' => $this->is_image(),
356
'image_width' => $this->image_width,
357
'image_height' => $this->image_height,
358
'image_type' => $this->image_type,
359
'image_size_str' => $this->image_size_str,
363
// --------------------------------------------------------------------
371
public function set_upload_path($path)
373
// Make sure it has a trailing slash
374
$this->upload_path = rtrim($path, '/').'/';
377
// --------------------------------------------------------------------
382
* This function takes a filename/path as input and looks for the
383
* existence of a file with the same name. If found, it will append a
384
* number to the end of the filename to avoid overwriting a pre-existing file.
390
public function set_filename($path, $filename)
392
if ($this->encrypt_name == TRUE)
395
$filename = md5(uniqid(mt_rand())).$this->file_ext;
398
if ( ! file_exists($path.$filename))
403
$filename = str_replace($this->file_ext, '', $filename);
406
for ($i = 1; $i < 100; $i++)
408
if ( ! file_exists($path.$filename.$i.$this->file_ext))
410
$new_filename = $filename.$i.$this->file_ext;
415
if ($new_filename == '')
417
$this->set_error('upload_bad_filename');
422
return $new_filename;
426
// --------------------------------------------------------------------
429
* Set Maximum File Size
434
public function set_max_filesize($n)
436
$this->max_size = ((int) $n < 0) ? 0: (int) $n;
439
// --------------------------------------------------------------------
442
* Set Maximum File Name Length
447
public function set_max_filename($n)
449
$this->max_filename = ((int) $n < 0) ? 0: (int) $n;
452
// --------------------------------------------------------------------
455
* Set Maximum Image Width
460
public function set_max_width($n)
462
$this->max_width = ((int) $n < 0) ? 0: (int) $n;
465
// --------------------------------------------------------------------
468
* Set Maximum Image Height
473
public function set_max_height($n)
475
$this->max_height = ((int) $n < 0) ? 0: (int) $n;
478
// --------------------------------------------------------------------
481
* Set Allowed File Types
486
public function set_allowed_types($types)
488
if ( ! is_array($types) && $types == '*')
490
$this->allowed_types = '*';
493
$this->allowed_types = explode('|', $types);
496
// --------------------------------------------------------------------
499
* Set Image Properties
501
* Uses GD to determine the width/height/type of image
506
public function set_image_properties($path = '')
508
if ( ! $this->is_image())
513
if (function_exists('getimagesize'))
515
if (FALSE !== ($D = @getimagesize($path)))
517
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
519
$this->image_width = $D['0'];
520
$this->image_height = $D['1'];
521
$this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
522
$this->image_size_str = $D['3']; // string containing height and width
527
// --------------------------------------------------------------------
532
* Enables the XSS flag so that the file that was uploaded
533
* will be run through the XSS filter.
538
public function set_xss_clean($flag = FALSE)
540
$this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
543
// --------------------------------------------------------------------
550
public function is_image()
552
// IE will sometimes return odd mime-types during upload, so here we just standardize all
553
// jpegs or pngs to the same file type.
555
$png_mimes = array('image/x-png');
556
$jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');
558
if (in_array($this->file_type, $png_mimes))
560
$this->file_type = 'image/png';
563
if (in_array($this->file_type, $jpeg_mimes))
565
$this->file_type = 'image/jpeg';
574
return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
577
// --------------------------------------------------------------------
580
* Verify that the filetype is allowed
584
public function is_allowed_filetype($ignore_mime = FALSE)
586
if ($this->allowed_types == '*')
591
if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
593
$this->set_error('upload_no_file_types');
597
$ext = strtolower(ltrim($this->file_ext, '.'));
599
if ( ! in_array($ext, $this->allowed_types))
604
// Images get some additional checks
605
$image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');
607
if (in_array($ext, $image_types))
609
if (getimagesize($this->file_temp) === FALSE)
615
if ($ignore_mime === TRUE)
620
$mime = $this->mimes_types($ext);
624
if (in_array($this->file_type, $mime, TRUE))
629
elseif ($mime == $this->file_type)
637
// --------------------------------------------------------------------
640
* Verify that the file is within the allowed size
644
public function is_allowed_filesize()
646
if ($this->max_size != 0 AND $this->file_size > $this->max_size)
656
// --------------------------------------------------------------------
659
* Verify that the image is within the allowed width/height
663
public function is_allowed_dimensions()
665
if ( ! $this->is_image())
670
if (function_exists('getimagesize'))
672
$D = @getimagesize($this->file_temp);
674
if ($this->max_width > 0 AND $D['0'] > $this->max_width)
679
if ($this->max_height > 0 AND $D['1'] > $this->max_height)
690
// --------------------------------------------------------------------
693
* Validate Upload Path
695
* Verifies that it is a valid upload path with proper permissions.
700
public function validate_upload_path()
702
if ($this->upload_path == '')
704
$this->set_error('upload_no_filepath');
708
if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE)
710
$this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
713
if ( ! @is_dir($this->upload_path))
715
$this->set_error('upload_no_filepath');
719
if ( ! is_really_writable($this->upload_path))
721
$this->set_error('upload_not_writable');
725
$this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path);
729
// --------------------------------------------------------------------
732
* Extract the file extension
737
public function get_extension($filename)
739
$x = explode('.', $filename);
743
// --------------------------------------------------------------------
746
* Clean the file name for security
751
public function clean_file_name($filename)
782
$filename = str_replace($bad, '', $filename);
784
return stripslashes($filename);
787
// --------------------------------------------------------------------
790
* Limit the File Name Length
795
public function limit_filename_length($filename, $length)
797
if (strlen($filename) < $length)
803
if (strpos($filename, '.') !== FALSE)
805
$parts = explode('.', $filename);
806
$ext = '.'.array_pop($parts);
807
$filename = implode('.', $parts);
810
return substr($filename, 0, ($length - strlen($ext))).$ext;
813
// --------------------------------------------------------------------
816
* Runs the file through the XSS clean function
818
* This prevents people from embedding malicious code in their files.
819
* I'm not sure that it won't negatively affect certain files in unexpected ways,
820
* but so far I haven't found that it causes trouble.
824
public function do_xss_clean()
826
$file = $this->file_temp;
828
if (filesize($file) == 0)
833
if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '')
835
$current = ini_get('memory_limit') * 1024 * 1024;
837
// There was a bug/behavioural change in PHP 5.2, where numbers over one million get output
838
// into scientific notation. number_format() ensures this number is an integer
839
// http://bugs.php.net/bug.php?id=43053
841
$new_memory = number_format(ceil(filesize($file) + $current), 0, '.', '');
843
ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net
846
// If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but
847
// IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
848
// using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
849
// CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
850
// processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
851
// attempted XSS attack.
853
if (function_exists('getimagesize') && @getimagesize($file) !== FALSE)
855
if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary
857
return FALSE; // Couldn't open the file, return FALSE
860
$opening_bytes = fread($file, 256);
863
// These are known to throw IE into mime-type detection chaos
864
// <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title
865
// title is basically just in SVG, but we filter it anyhow
867
if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes))
869
return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good
877
if (($data = @file_get_contents($file)) === FALSE)
882
$CI =& get_instance();
883
return $CI->security->xss_clean($data, TRUE);
886
// --------------------------------------------------------------------
889
* Set an error message
894
public function set_error($msg)
896
$CI =& get_instance();
897
$CI->lang->load('upload');
901
foreach ($msg as $val)
903
$msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val);
904
$this->error_msg[] = $msg;
905
log_message('error', $msg);
910
$msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
911
$this->error_msg[] = $msg;
912
log_message('error', $msg);
916
// --------------------------------------------------------------------
919
* Display the error message
925
public function display_errors($open = '<p>', $close = '</p>')
928
foreach ($this->error_msg as $val)
930
$str .= $open.$val.$close;
936
// --------------------------------------------------------------------
941
* This is a list of mime types. We use it to validate
942
* the "allowed types" set by the developer
947
public function mimes_types($mime)
951
if (count($this->mimes) == 0)
953
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
955
include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
957
elseif (is_file(APPPATH.'config/mimes.php'))
959
include(APPPATH.'config//mimes.php');
966
$this->mimes = $mimes;
970
return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
973
// --------------------------------------------------------------------
978
* Prevents possible script execution from Apache's handling of files multiple extensions
979
* http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
984
protected function _prep_filename($filename)
986
if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*')
991
$parts = explode('.', $filename);
992
$ext = array_pop($parts);
993
$filename = array_shift($parts);
995
foreach ($parts as $part)
997
if ( ! in_array(strtolower($part), $this->allowed_types) OR $this->mimes_types(strtolower($part)) === FALSE)
999
$filename .= '.'.$part.'_';
1003
$filename .= '.'.$part;
1007
$filename .= '.'.$ext;
1012
// --------------------------------------------------------------------
1017
* Detects the (actual) MIME type of the uploaded file, if possible.
1018
* The input array is expected to be $_FILES[$field]
1023
protected function _file_mime_type($file)
1025
// We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
1026
$regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';
1028
/* Fileinfo extension - most reliable method
1030
* Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the
1031
* more convenient FILEINFO_MIME_TYPE flag doesn't exist.
1033
if (function_exists('finfo_file'))
1035
$finfo = finfo_open(FILEINFO_MIME);
1036
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
1038
$mime = @finfo_file($finfo, $file['tmp_name']);
1039
finfo_close($finfo);
1041
/* According to the comments section of the PHP manual page,
1042
* it is possible that this function returns an empty string
1043
* for some files (e.g. if they don't exist in the magic MIME database)
1045
if (is_string($mime) && preg_match($regexp, $mime, $matches))
1047
$this->file_type = $matches[1];
1053
/* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
1054
* which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
1055
* was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
1056
* than mime_content_type() as well, hence the attempts to try calling the command line with
1057
* three different functions.
1060
* - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
1061
* - many system admins would disable the exec(), shell_exec(), popen() and similar functions
1062
* due to security concerns, hence the function_exists() checks
1064
if (DIRECTORY_SEPARATOR !== '\\')
1066
$cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1';
1068
if (function_exists('exec'))
1070
/* This might look confusing, as $mime is being populated with all of the output when set in the second parameter.
1071
* However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites
1072
* anything that could already be set for $mime previously. This effectively makes the second parameter a dummy
1073
* value, which is only put to allow us to get the return status code.
1075
$mime = @exec($cmd, $mime, $return_status);
1076
if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches))
1078
$this->file_type = $matches[1];
1083
if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec'))
1085
$mime = @shell_exec($cmd);
1086
if (strlen($mime) > 0)
1088
$mime = explode("\n", trim($mime));
1089
if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
1091
$this->file_type = $matches[1];
1097
if (function_exists('popen'))
1099
$proc = @popen($cmd, 'r');
1100
if (is_resource($proc))
1102
$mime = @fread($proc, 512);
1104
if ($mime !== FALSE)
1106
$mime = explode("\n", trim($mime));
1107
if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
1109
$this->file_type = $matches[1];
1117
// Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type'])
1118
if (function_exists('mime_content_type'))
1120
$this->file_type = @mime_content_type($file['tmp_name']);
1121
if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string
1127
$this->file_type = $file['type'];
1130
// --------------------------------------------------------------------
1135
/* End of file Upload.php */
1136
/* Location: ./system/libraries/Upload.php */