PageRenderTime 27ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/system/libraries/Upload.php

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