Upload.php 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.1.6 or newer
  6. *
  7. * @package CodeIgniter
  8. * @author EllisLab Dev Team
  9. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc.
  10. * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
  11. * @license http://codeigniter.com/user_guide/license.html
  12. * @link http://codeigniter.com
  13. * @since Version 1.0
  14. * @filesource
  15. */
  16. // ------------------------------------------------------------------------
  17. /**
  18. * File Uploading Class
  19. *
  20. * @package CodeIgniter
  21. * @subpackage Libraries
  22. * @category Uploads
  23. * @author EllisLab Dev Team
  24. * @link http://codeigniter.com/user_guide/libraries/file_uploading.html
  25. */
  26. class CI_Upload {
  27. public $max_size = 0;
  28. public $max_width = 0;
  29. public $max_height = 0;
  30. public $max_filename = 0;
  31. public $allowed_types = "";
  32. public $file_temp = "";
  33. public $file_name = "";
  34. public $orig_name = "";
  35. public $file_type = "";
  36. public $file_size = "";
  37. public $file_ext = "";
  38. public $upload_path = "";
  39. public $overwrite = FALSE;
  40. public $encrypt_name = FALSE;
  41. public $is_image = FALSE;
  42. public $image_width = '';
  43. public $image_height = '';
  44. public $image_type = '';
  45. public $image_size_str = '';
  46. public $error_msg = array();
  47. public $mimes = array();
  48. public $remove_spaces = TRUE;
  49. public $xss_clean = FALSE;
  50. public $temp_prefix = "temp_file_";
  51. public $client_name = '';
  52. protected $_file_name_override = '';
  53. /**
  54. * Constructor
  55. *
  56. * @access public
  57. */
  58. public function __construct($props = array())
  59. {
  60. if (count($props) > 0)
  61. {
  62. $this->initialize($props);
  63. }
  64. log_message('debug', "Upload Class Initialized");
  65. }
  66. // --------------------------------------------------------------------
  67. /**
  68. * Initialize preferences
  69. *
  70. * @param array
  71. * @return void
  72. */
  73. public function initialize($config = array())
  74. {
  75. $defaults = array(
  76. 'max_size' => 0,
  77. 'max_width' => 0,
  78. 'max_height' => 0,
  79. 'max_filename' => 0,
  80. 'allowed_types' => "",
  81. 'file_temp' => "",
  82. 'file_name' => "",
  83. 'orig_name' => "",
  84. 'file_type' => "",
  85. 'file_size' => "",
  86. 'file_ext' => "",
  87. 'upload_path' => "",
  88. 'overwrite' => FALSE,
  89. 'encrypt_name' => FALSE,
  90. 'is_image' => FALSE,
  91. 'image_width' => '',
  92. 'image_height' => '',
  93. 'image_type' => '',
  94. 'image_size_str' => '',
  95. 'error_msg' => array(),
  96. 'mimes' => array(),
  97. 'remove_spaces' => TRUE,
  98. 'xss_clean' => FALSE,
  99. 'temp_prefix' => "temp_file_",
  100. 'client_name' => ''
  101. );
  102. foreach ($defaults as $key => $val)
  103. {
  104. if (isset($config[$key]))
  105. {
  106. $method = 'set_'.$key;
  107. if (method_exists($this, $method))
  108. {
  109. $this->$method($config[$key]);
  110. }
  111. else
  112. {
  113. $this->$key = $config[$key];
  114. }
  115. }
  116. else
  117. {
  118. $this->$key = $val;
  119. }
  120. }
  121. // if a file_name was provided in the config, use it instead of the user input
  122. // supplied file name for all uploads until initialized again
  123. $this->_file_name_override = $this->file_name;
  124. }
  125. // --------------------------------------------------------------------
  126. /**
  127. * Perform the file upload
  128. *
  129. * @return bool
  130. */
  131. public function do_upload($field = 'userfile')
  132. {
  133. // Is $_FILES[$field] set? If not, no reason to continue.
  134. if ( ! isset($_FILES[$field]))
  135. {
  136. $this->set_error('upload_no_file_selected');
  137. return FALSE;
  138. }
  139. // Is the upload path valid?
  140. if ( ! $this->validate_upload_path())
  141. {
  142. // errors will already be set by validate_upload_path() so just return FALSE
  143. return FALSE;
  144. }
  145. // Was the file able to be uploaded? If not, determine the reason why.
  146. if ( ! is_uploaded_file($_FILES[$field]['tmp_name']))
  147. {
  148. $error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
  149. switch($error)
  150. {
  151. case 1: // UPLOAD_ERR_INI_SIZE
  152. $this->set_error('upload_file_exceeds_limit');
  153. break;
  154. case 2: // UPLOAD_ERR_FORM_SIZE
  155. $this->set_error('upload_file_exceeds_form_limit');
  156. break;
  157. case 3: // UPLOAD_ERR_PARTIAL
  158. $this->set_error('upload_file_partial');
  159. break;
  160. case 4: // UPLOAD_ERR_NO_FILE
  161. $this->set_error('upload_no_file_selected');
  162. break;
  163. case 6: // UPLOAD_ERR_NO_TMP_DIR
  164. $this->set_error('upload_no_temp_directory');
  165. break;
  166. case 7: // UPLOAD_ERR_CANT_WRITE
  167. $this->set_error('upload_unable_to_write_file');
  168. break;
  169. case 8: // UPLOAD_ERR_EXTENSION
  170. $this->set_error('upload_stopped_by_extension');
  171. break;
  172. default : $this->set_error('upload_no_file_selected');
  173. break;
  174. }
  175. return FALSE;
  176. }
  177. // Set the uploaded data as class variables
  178. $this->file_temp = $_FILES[$field]['tmp_name'];
  179. $this->file_size = $_FILES[$field]['size'];
  180. $this->_file_mime_type($_FILES[$field]);
  181. $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
  182. $this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
  183. $this->file_name = $this->_prep_filename($_FILES[$field]['name']);
  184. $this->file_ext = $this->get_extension($this->file_name);
  185. $this->client_name = $this->file_name;
  186. // Is the file type allowed to be uploaded?
  187. if ( ! $this->is_allowed_filetype())
  188. {
  189. $this->set_error('upload_invalid_filetype');
  190. return FALSE;
  191. }
  192. // if we're overriding, let's now make sure the new name and type is allowed
  193. if ($this->_file_name_override != '')
  194. {
  195. $this->file_name = $this->_prep_filename($this->_file_name_override);
  196. // If no extension was provided in the file_name config item, use the uploaded one
  197. if (strpos($this->_file_name_override, '.') === FALSE)
  198. {
  199. $this->file_name .= $this->file_ext;
  200. }
  201. // An extension was provided, lets have it!
  202. else
  203. {
  204. $this->file_ext = $this->get_extension($this->_file_name_override);
  205. }
  206. if ( ! $this->is_allowed_filetype(TRUE))
  207. {
  208. $this->set_error('upload_invalid_filetype');
  209. return FALSE;
  210. }
  211. }
  212. // Convert the file size to kilobytes
  213. if ($this->file_size > 0)
  214. {
  215. $this->file_size = round($this->file_size/1024, 2);
  216. }
  217. // Is the file size within the allowed maximum?
  218. if ( ! $this->is_allowed_filesize())
  219. {
  220. $this->set_error('upload_invalid_filesize');
  221. return FALSE;
  222. }
  223. // Are the image dimensions within the allowed size?
  224. // Note: This can fail if the server has an open_basdir restriction.
  225. if ( ! $this->is_allowed_dimensions())
  226. {
  227. $this->set_error('upload_invalid_dimensions');
  228. return FALSE;
  229. }
  230. // Sanitize the file name for security
  231. $CI =& get_instance();
  232. $this->file_name = $CI->security->sanitize_filename($this->file_name);
  233. // Truncate the file name if it's too long
  234. if ($this->max_filename > 0)
  235. {
  236. $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
  237. }
  238. // Remove white spaces in the name
  239. if ($this->remove_spaces == TRUE)
  240. {
  241. $this->file_name = preg_replace("/\s+/", "_", $this->file_name);
  242. }
  243. /*
  244. * Validate the file name
  245. * This function appends an number onto the end of
  246. * the file if one with the same name already exists.
  247. * If it returns false there was a problem.
  248. */
  249. $this->orig_name = $this->file_name;
  250. if ($this->overwrite == FALSE)
  251. {
  252. $this->file_name = $this->set_filename($this->upload_path, $this->file_name);
  253. if ($this->file_name === FALSE)
  254. {
  255. return FALSE;
  256. }
  257. }
  258. /*
  259. * Run the file through the XSS hacking filter
  260. * This helps prevent malicious code from being
  261. * embedded within a file. Scripts can easily
  262. * be disguised as images or other file types.
  263. */
  264. if ($this->xss_clean)
  265. {
  266. if ($this->do_xss_clean() === FALSE)
  267. {
  268. $this->set_error('upload_unable_to_write_file');
  269. return FALSE;
  270. }
  271. }
  272. /*
  273. * Move the file to the final destination
  274. * To deal with different server configurations
  275. * we'll attempt to use copy() first. If that fails
  276. * we'll use move_uploaded_file(). One of the two should
  277. * reliably work in most environments
  278. */
  279. if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
  280. {
  281. if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
  282. {
  283. $this->set_error('upload_destination_error');
  284. return FALSE;
  285. }
  286. }
  287. /*
  288. * Set the finalized image dimensions
  289. * This sets the image width/height (assuming the
  290. * file was an image). We use this information
  291. * in the "data" function.
  292. */
  293. $this->set_image_properties($this->upload_path.$this->file_name);
  294. return TRUE;
  295. }
  296. // --------------------------------------------------------------------
  297. /**
  298. * Finalized Data Array
  299. *
  300. * Returns an associative array containing all of the information
  301. * related to the upload, allowing the developer easy access in one array.
  302. *
  303. * @return array
  304. */
  305. public function data()
  306. {
  307. return array (
  308. 'file_name' => $this->file_name,
  309. 'file_type' => $this->file_type,
  310. 'file_path' => $this->upload_path,
  311. 'full_path' => $this->upload_path.$this->file_name,
  312. 'raw_name' => str_replace($this->file_ext, '', $this->file_name),
  313. 'orig_name' => $this->orig_name,
  314. 'client_name' => $this->client_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,
  322. );
  323. }
  324. // --------------------------------------------------------------------
  325. /**
  326. * Set Upload Path
  327. *
  328. * @param string
  329. * @return void
  330. */
  331. public function set_upload_path($path)
  332. {
  333. // Make sure it has a trailing slash
  334. $this->upload_path = rtrim($path, '/').'/';
  335. }
  336. // --------------------------------------------------------------------
  337. /**
  338. * Set the file name
  339. *
  340. * This function takes a filename/path as input and looks for the
  341. * existence of a file with the same name. If found, it will append a
  342. * number to the end of the filename to avoid overwriting a pre-existing file.
  343. *
  344. * @param string
  345. * @param string
  346. * @return string
  347. */
  348. public function set_filename($path, $filename)
  349. {
  350. if ($this->encrypt_name == TRUE)
  351. {
  352. mt_srand();
  353. $filename = md5(uniqid(mt_rand())).$this->file_ext;
  354. }
  355. if ( ! file_exists($path.$filename))
  356. {
  357. return $filename;
  358. }
  359. $filename = str_replace($this->file_ext, '', $filename);
  360. $new_filename = '';
  361. for ($i = 1; $i < 100; $i++)
  362. {
  363. if ( ! file_exists($path.$filename.$i.$this->file_ext))
  364. {
  365. $new_filename = $filename.$i.$this->file_ext;
  366. break;
  367. }
  368. }
  369. if ($new_filename == '')
  370. {
  371. $this->set_error('upload_bad_filename');
  372. return FALSE;
  373. }
  374. else
  375. {
  376. return $new_filename;
  377. }
  378. }
  379. // --------------------------------------------------------------------
  380. /**
  381. * Set Maximum File Size
  382. *
  383. * @param integer
  384. * @return void
  385. */
  386. public function set_max_filesize($n)
  387. {
  388. $this->max_size = ((int) $n < 0) ? 0: (int) $n;
  389. }
  390. // --------------------------------------------------------------------
  391. /**
  392. * Set Maximum File Name Length
  393. *
  394. * @param integer
  395. * @return void
  396. */
  397. public function set_max_filename($n)
  398. {
  399. $this->max_filename = ((int) $n < 0) ? 0: (int) $n;
  400. }
  401. // --------------------------------------------------------------------
  402. /**
  403. * Set Maximum Image Width
  404. *
  405. * @param integer
  406. * @return void
  407. */
  408. public function set_max_width($n)
  409. {
  410. $this->max_width = ((int) $n < 0) ? 0: (int) $n;
  411. }
  412. // --------------------------------------------------------------------
  413. /**
  414. * Set Maximum Image Height
  415. *
  416. * @param integer
  417. * @return void
  418. */
  419. public function set_max_height($n)
  420. {
  421. $this->max_height = ((int) $n < 0) ? 0: (int) $n;
  422. }
  423. // --------------------------------------------------------------------
  424. /**
  425. * Set Allowed File Types
  426. *
  427. * @param string
  428. * @return void
  429. */
  430. public function set_allowed_types($types)
  431. {
  432. if ( ! is_array($types) && $types == '*')
  433. {
  434. $this->allowed_types = '*';
  435. return;
  436. }
  437. $this->allowed_types = explode('|', $types);
  438. }
  439. // --------------------------------------------------------------------
  440. /**
  441. * Set Image Properties
  442. *
  443. * Uses GD to determine the width/height/type of image
  444. *
  445. * @param string
  446. * @return void
  447. */
  448. public function set_image_properties($path = '')
  449. {
  450. if ( ! $this->is_image())
  451. {
  452. return;
  453. }
  454. if (function_exists('getimagesize'))
  455. {
  456. if (FALSE !== ($D = @getimagesize($path)))
  457. {
  458. $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
  459. $this->image_width = $D['0'];
  460. $this->image_height = $D['1'];
  461. $this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
  462. $this->image_size_str = $D['3']; // string containing height and width
  463. }
  464. }
  465. }
  466. // --------------------------------------------------------------------
  467. /**
  468. * Set XSS Clean
  469. *
  470. * Enables the XSS flag so that the file that was uploaded
  471. * will be run through the XSS filter.
  472. *
  473. * @param bool
  474. * @return void
  475. */
  476. public function set_xss_clean($flag = FALSE)
  477. {
  478. $this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
  479. }
  480. // --------------------------------------------------------------------
  481. /**
  482. * Validate the image
  483. *
  484. * @return bool
  485. */
  486. public function is_image()
  487. {
  488. // IE will sometimes return odd mime-types during upload, so here we just standardize all
  489. // jpegs or pngs to the same file type.
  490. $png_mimes = array('image/x-png');
  491. $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');
  492. if (in_array($this->file_type, $png_mimes))
  493. {
  494. $this->file_type = 'image/png';
  495. }
  496. if (in_array($this->file_type, $jpeg_mimes))
  497. {
  498. $this->file_type = 'image/jpeg';
  499. }
  500. $img_mimes = array(
  501. 'image/gif',
  502. 'image/jpeg',
  503. 'image/png',
  504. );
  505. return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
  506. }
  507. // --------------------------------------------------------------------
  508. /**
  509. * Verify that the filetype is allowed
  510. *
  511. * @return bool
  512. */
  513. public function is_allowed_filetype($ignore_mime = FALSE)
  514. {
  515. if ($this->allowed_types == '*')
  516. {
  517. return TRUE;
  518. }
  519. if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
  520. {
  521. $this->set_error('upload_no_file_types');
  522. return FALSE;
  523. }
  524. $ext = strtolower(ltrim($this->file_ext, '.'));
  525. if ( ! in_array($ext, $this->allowed_types))
  526. {
  527. return FALSE;
  528. }
  529. // Images get some additional checks
  530. $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');
  531. if (in_array($ext, $image_types))
  532. {
  533. if (getimagesize($this->file_temp) === FALSE)
  534. {
  535. return FALSE;
  536. }
  537. }
  538. if ($ignore_mime === TRUE)
  539. {
  540. return TRUE;
  541. }
  542. $mime = $this->mimes_types($ext);
  543. if (is_array($mime))
  544. {
  545. if (in_array($this->file_type, $mime, TRUE))
  546. {
  547. return TRUE;
  548. }
  549. }
  550. elseif ($mime == $this->file_type)
  551. {
  552. return TRUE;
  553. }
  554. return FALSE;
  555. }
  556. // --------------------------------------------------------------------
  557. /**
  558. * Verify that the file is within the allowed size
  559. *
  560. * @return bool
  561. */
  562. public function is_allowed_filesize()
  563. {
  564. if ($this->max_size != 0 AND $this->file_size > $this->max_size)
  565. {
  566. return FALSE;
  567. }
  568. else
  569. {
  570. return TRUE;
  571. }
  572. }
  573. // --------------------------------------------------------------------
  574. /**
  575. * Verify that the image is within the allowed width/height
  576. *
  577. * @return bool
  578. */
  579. public function is_allowed_dimensions()
  580. {
  581. if ( ! $this->is_image())
  582. {
  583. return TRUE;
  584. }
  585. if (function_exists('getimagesize'))
  586. {
  587. $D = @getimagesize($this->file_temp);
  588. if ($this->max_width > 0 AND $D['0'] > $this->max_width)
  589. {
  590. return FALSE;
  591. }
  592. if ($this->max_height > 0 AND $D['1'] > $this->max_height)
  593. {
  594. return FALSE;
  595. }
  596. return TRUE;
  597. }
  598. return TRUE;
  599. }
  600. // --------------------------------------------------------------------
  601. /**
  602. * Validate Upload Path
  603. *
  604. * Verifies that it is a valid upload path with proper permissions.
  605. *
  606. *
  607. * @return bool
  608. */
  609. public function validate_upload_path()
  610. {
  611. if ($this->upload_path == '')
  612. {
  613. $this->set_error('upload_no_filepath');
  614. return FALSE;
  615. }
  616. if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE)
  617. {
  618. $this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
  619. }
  620. if ( ! @is_dir($this->upload_path))
  621. {
  622. $this->set_error('upload_no_filepath');
  623. return FALSE;
  624. }
  625. if ( ! is_really_writable($this->upload_path))
  626. {
  627. $this->set_error('upload_not_writable');
  628. return FALSE;
  629. }
  630. $this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path);
  631. return TRUE;
  632. }
  633. // --------------------------------------------------------------------
  634. /**
  635. * Extract the file extension
  636. *
  637. * @param string
  638. * @return string
  639. */
  640. public function get_extension($filename)
  641. {
  642. $x = explode('.', $filename);
  643. return '.'.end($x);
  644. }
  645. // --------------------------------------------------------------------
  646. /**
  647. * Clean the file name for security
  648. *
  649. * @deprecated 2.2.1 Alias for CI_Security::sanitize_filename()
  650. * @param string $filename
  651. * @return string
  652. */
  653. public function clean_file_name($filename)
  654. {
  655. $CI =& get_instance();
  656. return $CI->security->sanitize_filename($filename);
  657. }
  658. // --------------------------------------------------------------------
  659. /**
  660. * Limit the File Name Length
  661. *
  662. * @param string
  663. * @return string
  664. */
  665. public function limit_filename_length($filename, $length)
  666. {
  667. if (strlen($filename) < $length)
  668. {
  669. return $filename;
  670. }
  671. $ext = '';
  672. if (strpos($filename, '.') !== FALSE)
  673. {
  674. $parts = explode('.', $filename);
  675. $ext = '.'.array_pop($parts);
  676. $filename = implode('.', $parts);
  677. }
  678. return substr($filename, 0, ($length - strlen($ext))).$ext;
  679. }
  680. // --------------------------------------------------------------------
  681. /**
  682. * Runs the file through the XSS clean function
  683. *
  684. * This prevents people from embedding malicious code in their files.
  685. * I'm not sure that it won't negatively affect certain files in unexpected ways,
  686. * but so far I haven't found that it causes trouble.
  687. *
  688. * @return void
  689. */
  690. public function do_xss_clean()
  691. {
  692. $file = $this->file_temp;
  693. if (filesize($file) == 0)
  694. {
  695. return FALSE;
  696. }
  697. if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '')
  698. {
  699. $current = ini_get('memory_limit') * 1024 * 1024;
  700. // There was a bug/behavioural change in PHP 5.2, where numbers over one million get output
  701. // into scientific notation. number_format() ensures this number is an integer
  702. // http://bugs.php.net/bug.php?id=43053
  703. $new_memory = number_format(ceil(filesize($file) + $current), 0, '.', '');
  704. ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net
  705. }
  706. // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but
  707. // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
  708. // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
  709. // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
  710. // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
  711. // attempted XSS attack.
  712. if (function_exists('getimagesize') && @getimagesize($file) !== FALSE)
  713. {
  714. if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary
  715. {
  716. return FALSE; // Couldn't open the file, return FALSE
  717. }
  718. $opening_bytes = fread($file, 256);
  719. fclose($file);
  720. // These are known to throw IE into mime-type detection chaos
  721. // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title
  722. // title is basically just in SVG, but we filter it anyhow
  723. if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes))
  724. {
  725. return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good
  726. }
  727. else
  728. {
  729. return FALSE;
  730. }
  731. }
  732. if (($data = @file_get_contents($file)) === FALSE)
  733. {
  734. return FALSE;
  735. }
  736. $CI =& get_instance();
  737. return $CI->security->xss_clean($data, TRUE);
  738. }
  739. // --------------------------------------------------------------------
  740. /**
  741. * Set an error message
  742. *
  743. * @param string
  744. * @return void
  745. */
  746. public function set_error($msg)
  747. {
  748. $CI =& get_instance();
  749. $CI->lang->load('upload');
  750. if (is_array($msg))
  751. {
  752. foreach ($msg as $val)
  753. {
  754. $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val);
  755. $this->error_msg[] = $msg;
  756. log_message('error', $msg);
  757. }
  758. }
  759. else
  760. {
  761. $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
  762. $this->error_msg[] = $msg;
  763. log_message('error', $msg);
  764. }
  765. }
  766. // --------------------------------------------------------------------
  767. /**
  768. * Display the error message
  769. *
  770. * @param string
  771. * @param string
  772. * @return string
  773. */
  774. public function display_errors($open = '<p>', $close = '</p>')
  775. {
  776. $str = '';
  777. foreach ($this->error_msg as $val)
  778. {
  779. $str .= $open.$val.$close;
  780. }
  781. return $str;
  782. }
  783. // --------------------------------------------------------------------
  784. /**
  785. * List of Mime Types
  786. *
  787. * This is a list of mime types. We use it to validate
  788. * the "allowed types" set by the developer
  789. *
  790. * @param string
  791. * @return string
  792. */
  793. public function mimes_types($mime)
  794. {
  795. global $mimes;
  796. if (count($this->mimes) == 0)
  797. {
  798. if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
  799. {
  800. include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
  801. }
  802. elseif (is_file(APPPATH.'config/mimes.php'))
  803. {
  804. include(APPPATH.'config//mimes.php');
  805. }
  806. else
  807. {
  808. return FALSE;
  809. }
  810. $this->mimes = $mimes;
  811. unset($mimes);
  812. }
  813. return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
  814. }
  815. // --------------------------------------------------------------------
  816. /**
  817. * Prep Filename
  818. *
  819. * Prevents possible script execution from Apache's handling of files multiple extensions
  820. * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
  821. *
  822. * @param string
  823. * @return string
  824. */
  825. protected function _prep_filename($filename)
  826. {
  827. if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*')
  828. {
  829. return $filename;
  830. }
  831. $parts = explode('.', $filename);
  832. $ext = array_pop($parts);
  833. $filename = array_shift($parts);
  834. foreach ($parts as $part)
  835. {
  836. if ( ! in_array(strtolower($part), $this->allowed_types) OR $this->mimes_types(strtolower($part)) === FALSE)
  837. {
  838. $filename .= '.'.$part.'_';
  839. }
  840. else
  841. {
  842. $filename .= '.'.$part;
  843. }
  844. }
  845. $filename .= '.'.$ext;
  846. return $filename;
  847. }
  848. // --------------------------------------------------------------------
  849. /**
  850. * File MIME type
  851. *
  852. * Detects the (actual) MIME type of the uploaded file, if possible.
  853. * The input array is expected to be $_FILES[$field]
  854. *
  855. * @param array
  856. * @return void
  857. */
  858. protected function _file_mime_type($file)
  859. {
  860. // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
  861. $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';
  862. /* Fileinfo extension - most reliable method
  863. *
  864. * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the
  865. * more convenient FILEINFO_MIME_TYPE flag doesn't exist.
  866. */
  867. if (function_exists('finfo_file'))
  868. {
  869. $finfo = finfo_open(FILEINFO_MIME);
  870. 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
  871. {
  872. $mime = @finfo_file($finfo, $file['tmp_name']);
  873. finfo_close($finfo);
  874. /* According to the comments section of the PHP manual page,
  875. * it is possible that this function returns an empty string
  876. * for some files (e.g. if they don't exist in the magic MIME database)
  877. */
  878. if (is_string($mime) && preg_match($regexp, $mime, $matches))
  879. {
  880. $this->file_type = $matches[1];
  881. return;
  882. }
  883. }
  884. }
  885. /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
  886. * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
  887. * was reported in issue #750 (https://github.com/bcit-ci/CodeIgniter/issues/750) - it's better
  888. * than mime_content_type() as well, hence the attempts to try calling the command line with
  889. * three different functions.
  890. *
  891. * Notes:
  892. * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
  893. * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
  894. * due to security concerns, hence the function_exists() checks
  895. */
  896. if (DIRECTORY_SEPARATOR !== '\\')
  897. {
  898. $cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1';
  899. if (function_exists('exec'))
  900. {
  901. /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter.
  902. * However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites
  903. * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy
  904. * value, which is only put to allow us to get the return status code.
  905. */
  906. $mime = @exec($cmd, $mime, $return_status);
  907. if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches))
  908. {
  909. $this->file_type = $matches[1];
  910. return;
  911. }
  912. }
  913. if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec'))
  914. {
  915. $mime = @shell_exec($cmd);
  916. if (strlen($mime) > 0)
  917. {
  918. $mime = explode("\n", trim($mime));
  919. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
  920. {
  921. $this->file_type = $matches[1];
  922. return;
  923. }
  924. }
  925. }
  926. if (function_exists('popen'))
  927. {
  928. $proc = @popen($cmd, 'r');
  929. if (is_resource($proc))
  930. {
  931. $mime = @fread($proc, 512);
  932. @pclose($proc);
  933. if ($mime !== FALSE)
  934. {
  935. $mime = explode("\n", trim($mime));
  936. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
  937. {
  938. $this->file_type = $matches[1];
  939. return;
  940. }
  941. }
  942. }
  943. }
  944. }
  945. // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type'])
  946. if (function_exists('mime_content_type'))
  947. {
  948. $this->file_type = @mime_content_type($file['tmp_name']);
  949. if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string
  950. {
  951. return;
  952. }
  953. }
  954. $this->file_type = $file['type'];
  955. }
  956. // --------------------------------------------------------------------
  957. }
  958. // END Upload Class
  959. /* End of file Upload.php */
  960. /* Location: ./system/libraries/Upload.php */