Upload.php 30KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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 - 2019, 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 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://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 $config
  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' => substr($this->file_name, 0, -strlen($this->file_ext)),
  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. return $new_filename;
  599. }
  600. // --------------------------------------------------------------------
  601. /**
  602. * Set Maximum File Size
  603. *
  604. * @param int $n
  605. * @return CI_Upload
  606. */
  607. public function set_max_filesize($n)
  608. {
  609. $this->max_size = ($n < 0) ? 0 : (int) $n;
  610. return $this;
  611. }
  612. // --------------------------------------------------------------------
  613. /**
  614. * Set Maximum File Size
  615. *
  616. * An internal alias to set_max_filesize() to help with configuration
  617. * as initialize() will look for a set_<property_name>() method ...
  618. *
  619. * @param int $n
  620. * @return CI_Upload
  621. */
  622. protected function set_max_size($n)
  623. {
  624. return $this->set_max_filesize($n);
  625. }
  626. // --------------------------------------------------------------------
  627. /**
  628. * Set Maximum File Name Length
  629. *
  630. * @param int $n
  631. * @return CI_Upload
  632. */
  633. public function set_max_filename($n)
  634. {
  635. $this->max_filename = ($n < 0) ? 0 : (int) $n;
  636. return $this;
  637. }
  638. // --------------------------------------------------------------------
  639. /**
  640. * Set Maximum Image Width
  641. *
  642. * @param int $n
  643. * @return CI_Upload
  644. */
  645. public function set_max_width($n)
  646. {
  647. $this->max_width = ($n < 0) ? 0 : (int) $n;
  648. return $this;
  649. }
  650. // --------------------------------------------------------------------
  651. /**
  652. * Set Maximum Image Height
  653. *
  654. * @param int $n
  655. * @return CI_Upload
  656. */
  657. public function set_max_height($n)
  658. {
  659. $this->max_height = ($n < 0) ? 0 : (int) $n;
  660. return $this;
  661. }
  662. // --------------------------------------------------------------------
  663. /**
  664. * Set minimum image width
  665. *
  666. * @param int $n
  667. * @return CI_Upload
  668. */
  669. public function set_min_width($n)
  670. {
  671. $this->min_width = ($n < 0) ? 0 : (int) $n;
  672. return $this;
  673. }
  674. // --------------------------------------------------------------------
  675. /**
  676. * Set minimum image height
  677. *
  678. * @param int $n
  679. * @return CI_Upload
  680. */
  681. public function set_min_height($n)
  682. {
  683. $this->min_height = ($n < 0) ? 0 : (int) $n;
  684. return $this;
  685. }
  686. // --------------------------------------------------------------------
  687. /**
  688. * Set Allowed File Types
  689. *
  690. * @param mixed $types
  691. * @return CI_Upload
  692. */
  693. public function set_allowed_types($types)
  694. {
  695. $this->allowed_types = (is_array($types) OR $types === '*')
  696. ? $types
  697. : explode('|', $types);
  698. return $this;
  699. }
  700. // --------------------------------------------------------------------
  701. /**
  702. * Set Image Properties
  703. *
  704. * Uses GD to determine the width/height/type of image
  705. *
  706. * @param string $path
  707. * @return CI_Upload
  708. */
  709. public function set_image_properties($path = '')
  710. {
  711. if ($this->is_image() && function_exists('getimagesize'))
  712. {
  713. if (FALSE !== ($D = @getimagesize($path)))
  714. {
  715. $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
  716. $this->image_width = $D[0];
  717. $this->image_height = $D[1];
  718. $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown';
  719. $this->image_size_str = $D[3]; // string containing height and width
  720. }
  721. }
  722. return $this;
  723. }
  724. // --------------------------------------------------------------------
  725. /**
  726. * Set XSS Clean
  727. *
  728. * Enables the XSS flag so that the file that was uploaded
  729. * will be run through the XSS filter.
  730. *
  731. * @param bool $flag
  732. * @return CI_Upload
  733. */
  734. public function set_xss_clean($flag = FALSE)
  735. {
  736. $this->xss_clean = ($flag === TRUE);
  737. return $this;
  738. }
  739. // --------------------------------------------------------------------
  740. /**
  741. * Validate the image
  742. *
  743. * @return bool
  744. */
  745. public function is_image()
  746. {
  747. // IE will sometimes return odd mime-types during upload, so here we just standardize all
  748. // jpegs or pngs to the same file type.
  749. $png_mimes = array('image/x-png');
  750. $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');
  751. if (in_array($this->file_type, $png_mimes))
  752. {
  753. $this->file_type = 'image/png';
  754. }
  755. elseif (in_array($this->file_type, $jpeg_mimes))
  756. {
  757. $this->file_type = 'image/jpeg';
  758. }
  759. $img_mimes = array('image/gif', 'image/jpeg', 'image/png');
  760. return in_array($this->file_type, $img_mimes, TRUE);
  761. }
  762. // --------------------------------------------------------------------
  763. /**
  764. * Verify that the filetype is allowed
  765. *
  766. * @param bool $ignore_mime
  767. * @return bool
  768. */
  769. public function is_allowed_filetype($ignore_mime = FALSE)
  770. {
  771. if ($this->allowed_types === '*')
  772. {
  773. return TRUE;
  774. }
  775. if (empty($this->allowed_types) OR ! is_array($this->allowed_types))
  776. {
  777. $this->set_error('upload_no_file_types', 'debug');
  778. return FALSE;
  779. }
  780. $ext = strtolower(ltrim($this->file_ext, '.'));
  781. if ( ! in_array($ext, $this->allowed_types, TRUE))
  782. {
  783. return FALSE;
  784. }
  785. // Images get some additional checks
  786. if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE)
  787. {
  788. return FALSE;
  789. }
  790. if ($ignore_mime === TRUE)
  791. {
  792. return TRUE;
  793. }
  794. if (isset($this->_mimes[$ext]))
  795. {
  796. return is_array($this->_mimes[$ext])
  797. ? in_array($this->file_type, $this->_mimes[$ext], TRUE)
  798. : ($this->_mimes[$ext] === $this->file_type);
  799. }
  800. return FALSE;
  801. }
  802. // --------------------------------------------------------------------
  803. /**
  804. * Verify that the file is within the allowed size
  805. *
  806. * @return bool
  807. */
  808. public function is_allowed_filesize()
  809. {
  810. return ($this->max_size === 0 OR $this->max_size > $this->file_size);
  811. }
  812. // --------------------------------------------------------------------
  813. /**
  814. * Verify that the image is within the allowed width/height
  815. *
  816. * @return bool
  817. */
  818. public function is_allowed_dimensions()
  819. {
  820. if ( ! $this->is_image())
  821. {
  822. return TRUE;
  823. }
  824. if (function_exists('getimagesize'))
  825. {
  826. $D = @getimagesize($this->file_temp);
  827. if ($this->max_width > 0 && $D[0] > $this->max_width)
  828. {
  829. return FALSE;
  830. }
  831. if ($this->max_height > 0 && $D[1] > $this->max_height)
  832. {
  833. return FALSE;
  834. }
  835. if ($this->min_width > 0 && $D[0] < $this->min_width)
  836. {
  837. return FALSE;
  838. }
  839. if ($this->min_height > 0 && $D[1] < $this->min_height)
  840. {
  841. return FALSE;
  842. }
  843. }
  844. return TRUE;
  845. }
  846. // --------------------------------------------------------------------
  847. /**
  848. * Validate Upload Path
  849. *
  850. * Verifies that it is a valid upload path with proper permissions.
  851. *
  852. * @return bool
  853. */
  854. public function validate_upload_path()
  855. {
  856. if ($this->upload_path === '')
  857. {
  858. $this->set_error('upload_no_filepath', 'error');
  859. return FALSE;
  860. }
  861. if (realpath($this->upload_path) !== FALSE)
  862. {
  863. $this->upload_path = str_replace('\\', '/', realpath($this->upload_path));
  864. }
  865. if ( ! is_dir($this->upload_path))
  866. {
  867. $this->set_error('upload_no_filepath', 'error');
  868. return FALSE;
  869. }
  870. if ( ! is_really_writable($this->upload_path))
  871. {
  872. $this->set_error('upload_not_writable', 'error');
  873. return FALSE;
  874. }
  875. $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path);
  876. return TRUE;
  877. }
  878. // --------------------------------------------------------------------
  879. /**
  880. * Extract the file extension
  881. *
  882. * @param string $filename
  883. * @return string
  884. */
  885. public function get_extension($filename)
  886. {
  887. $x = explode('.', $filename);
  888. if (count($x) === 1)
  889. {
  890. return '';
  891. }
  892. $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x);
  893. return '.'.$ext;
  894. }
  895. // --------------------------------------------------------------------
  896. /**
  897. * Limit the File Name Length
  898. *
  899. * @param string $filename
  900. * @param int $length
  901. * @return string
  902. */
  903. public function limit_filename_length($filename, $length)
  904. {
  905. if (strlen($filename) < $length)
  906. {
  907. return $filename;
  908. }
  909. $ext = '';
  910. if (strpos($filename, '.') !== FALSE)
  911. {
  912. $parts = explode('.', $filename);
  913. $ext = '.'.array_pop($parts);
  914. $filename = implode('.', $parts);
  915. }
  916. return substr($filename, 0, ($length - strlen($ext))).$ext;
  917. }
  918. // --------------------------------------------------------------------
  919. /**
  920. * Runs the file through the XSS clean function
  921. *
  922. * This prevents people from embedding malicious code in their files.
  923. * I'm not sure that it won't negatively affect certain files in unexpected ways,
  924. * but so far I haven't found that it causes trouble.
  925. *
  926. * @return string
  927. */
  928. public function do_xss_clean()
  929. {
  930. $file = $this->file_temp;
  931. if (filesize($file) == 0)
  932. {
  933. return FALSE;
  934. }
  935. if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0)
  936. {
  937. $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890'));
  938. if ( ! empty($memory_limit[1]))
  939. {
  940. switch ($memory_limit[1][0])
  941. {
  942. case 'g':
  943. case 'G':
  944. $memory_limit[0] *= 1024 * 1024 * 1024;
  945. break;
  946. case 'm':
  947. case 'M':
  948. $memory_limit[0] *= 1024 * 1024;
  949. break;
  950. default:
  951. break;
  952. }
  953. }
  954. $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]);
  955. ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net
  956. }
  957. // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but
  958. // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
  959. // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
  960. // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
  961. // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
  962. // attempted XSS attack.
  963. if (function_exists('getimagesize') && @getimagesize($file) !== FALSE)
  964. {
  965. if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary
  966. {
  967. return FALSE; // Couldn't open the file, return FALSE
  968. }
  969. $opening_bytes = fread($file, 256);
  970. fclose($file);
  971. // These are known to throw IE into mime-type detection chaos
  972. // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title
  973. // title is basically just in SVG, but we filter it anyhow
  974. // if it's an image or no "triggers" detected in the first 256 bytes - we're good
  975. return ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes);
  976. }
  977. if (($data = @file_get_contents($file)) === FALSE)
  978. {
  979. return FALSE;
  980. }
  981. return $this->_CI->security->xss_clean($data, TRUE);
  982. }
  983. // --------------------------------------------------------------------
  984. /**
  985. * Set an error message
  986. *
  987. * @param string $msg
  988. * @return CI_Upload
  989. */
  990. public function set_error($msg, $log_level = 'error')
  991. {
  992. $this->_CI->lang->load('upload');
  993. is_array($msg) OR $msg = array($msg);
  994. foreach ($msg as $val)
  995. {
  996. $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val);
  997. $this->error_msg[] = $msg;
  998. log_message($log_level, $msg);
  999. }
  1000. return $this;
  1001. }
  1002. // --------------------------------------------------------------------
  1003. /**
  1004. * Display the error message
  1005. *
  1006. * @param string $open
  1007. * @param string $close
  1008. * @return string
  1009. */
  1010. public function display_errors($open = '<p>', $close = '</p>')
  1011. {
  1012. return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : '';
  1013. }
  1014. // --------------------------------------------------------------------
  1015. /**
  1016. * Prep Filename
  1017. *
  1018. * Prevents possible script execution from Apache's handling
  1019. * of files' multiple extensions.
  1020. *
  1021. * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
  1022. *
  1023. * @param string $filename
  1024. * @return string
  1025. */
  1026. protected function _prep_filename($filename)
  1027. {
  1028. if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE)
  1029. {
  1030. return $filename;
  1031. }
  1032. $ext = substr($filename, $ext_pos);
  1033. $filename = substr($filename, 0, $ext_pos);
  1034. return str_replace('.', '_', $filename).$ext;
  1035. }
  1036. // --------------------------------------------------------------------
  1037. /**
  1038. * File MIME type
  1039. *
  1040. * Detects the (actual) MIME type of the uploaded file, if possible.
  1041. * The input array is expected to be $_FILES[$field]
  1042. *
  1043. * @param array $file
  1044. * @return void
  1045. */
  1046. protected function _file_mime_type($file)
  1047. {
  1048. // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
  1049. $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';
  1050. /**
  1051. * Fileinfo extension - most reliable method
  1052. *
  1053. * Apparently XAMPP, CentOS, cPanel and who knows what
  1054. * other PHP distribution channels EXPLICITLY DISABLE
  1055. * ext/fileinfo, which is otherwise enabled by default
  1056. * since PHP 5.3 ...
  1057. */
  1058. if (function_exists('finfo_file'))
  1059. {
  1060. $finfo = @finfo_open(FILEINFO_MIME);
  1061. 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
  1062. {
  1063. $mime = @finfo_file($finfo, $file['tmp_name']);
  1064. finfo_close($finfo);
  1065. /* According to the comments section of the PHP manual page,
  1066. * it is possible that this function returns an empty string
  1067. * for some files (e.g. if they don't exist in the magic MIME database)
  1068. */
  1069. if (is_string($mime) && preg_match($regexp, $mime, $matches))
  1070. {
  1071. $this->file_type = $matches[1];
  1072. return;
  1073. }
  1074. }
  1075. }
  1076. /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
  1077. * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
  1078. * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
  1079. * than mime_content_type() as well, hence the attempts to try calling the command line with
  1080. * three different functions.
  1081. *
  1082. * Notes:
  1083. * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
  1084. * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
  1085. * due to security concerns, hence the function_usable() checks
  1086. */
  1087. if (DIRECTORY_SEPARATOR !== '\\')
  1088. {
  1089. $cmd = function_exists('escapeshellarg')
  1090. ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1'
  1091. : 'file --brief --mime '.$file['tmp_name'].' 2>&1';
  1092. if (function_usable('exec'))
  1093. {
  1094. /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter.
  1095. * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites
  1096. * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy
  1097. * value, which is only put to allow us to get the return status code.
  1098. */
  1099. $mime = @exec($cmd, $mime, $return_status);
  1100. if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches))
  1101. {
  1102. $this->file_type = $matches[1];
  1103. return;
  1104. }
  1105. }
  1106. if ( ! ini_get('safe_mode') && function_usable('shell_exec'))
  1107. {
  1108. $mime = @shell_exec($cmd);
  1109. if (strlen($mime) > 0)
  1110. {
  1111. $mime = explode("\n", trim($mime));
  1112. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
  1113. {
  1114. $this->file_type = $matches[1];
  1115. return;
  1116. }
  1117. }
  1118. }
  1119. if (function_usable('popen'))
  1120. {
  1121. $proc = @popen($cmd, 'r');
  1122. if (is_resource($proc))
  1123. {
  1124. $mime = @fread($proc, 512);
  1125. @pclose($proc);
  1126. if ($mime !== FALSE)
  1127. {
  1128. $mime = explode("\n", trim($mime));
  1129. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
  1130. {
  1131. $this->file_type = $matches[1];
  1132. return;
  1133. }
  1134. }
  1135. }
  1136. }
  1137. }
  1138. // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
  1139. if (function_exists('mime_content_type'))
  1140. {
  1141. $this->file_type = @mime_content_type($file['tmp_name']);
  1142. if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string
  1143. {
  1144. return;
  1145. }
  1146. }
  1147. $this->file_type = $file['type'];
  1148. }
  1149. }