Upload.php 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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 - 2017, 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 - 2017, 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 $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. if(function_exists('mimes_types')){
  404. $this->file_type = preg_replace("/^(.+?);.*$/", "\\1",mimes_types($this->file_temp));
  405. }else{
  406. $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
  407. }
  408. $this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
  409. $this->file_name = $this->_prep_filename($_file['name']);
  410. $this->file_ext = $this->get_extension($this->file_name);
  411. $this->client_name = $this->file_name;
  412. // Is the file type allowed to be uploaded?
  413. if ( ! $this->is_allowed_filetype())
  414. {
  415. $this->set_error('upload_invalid_filetype', 'debug');
  416. return FALSE;
  417. }
  418. // if we're overriding, let's now make sure the new name and type is allowed
  419. if ($this->_file_name_override !== '')
  420. {
  421. $this->file_name = $this->_prep_filename($this->_file_name_override);
  422. // If no extension was provided in the file_name config item, use the uploaded one
  423. if (strpos($this->_file_name_override, '.') === FALSE)
  424. {
  425. $this->file_name .= $this->file_ext;
  426. }
  427. else
  428. {
  429. // An extension was provided, let's have it!
  430. $this->file_ext = $this->get_extension($this->_file_name_override);
  431. }
  432. if ( ! $this->is_allowed_filetype(TRUE))
  433. {
  434. $this->set_error('upload_invalid_filetype', 'debug');
  435. return FALSE;
  436. }
  437. }
  438. // Convert the file size to kilobytes
  439. if ($this->file_size > 0)
  440. {
  441. $this->file_size = round($this->file_size/1024, 2);
  442. }
  443. // Is the file size within the allowed maximum?
  444. if ( ! $this->is_allowed_filesize())
  445. {
  446. $this->set_error('upload_invalid_filesize', 'info');
  447. return FALSE;
  448. }
  449. // Are the image dimensions within the allowed size?
  450. // Note: This can fail if the server has an open_basedir restriction.
  451. if ( ! $this->is_allowed_dimensions())
  452. {
  453. $this->set_error('upload_invalid_dimensions', 'info');
  454. return FALSE;
  455. }
  456. // Sanitize the file name for security
  457. $this->file_name = $this->_CI->security->sanitize_filename($this->file_name);
  458. // Truncate the file name if it's too long
  459. if ($this->max_filename > 0)
  460. {
  461. $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
  462. }
  463. // Remove white spaces in the name
  464. if ($this->remove_spaces === TRUE)
  465. {
  466. $this->file_name = preg_replace('/\s+/', '_', $this->file_name);
  467. }
  468. if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext)))
  469. {
  470. // file_ext was previously lower-cased by a get_extension() call
  471. $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext;
  472. }
  473. /*
  474. * Validate the file name
  475. * This function appends an number onto the end of
  476. * the file if one with the same name already exists.
  477. * If it returns false there was a problem.
  478. */
  479. $this->orig_name = $this->file_name;
  480. if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name)))
  481. {
  482. return FALSE;
  483. }
  484. /*
  485. * Run the file through the XSS hacking filter
  486. * This helps prevent malicious code from being
  487. * embedded within a file. Scripts can easily
  488. * be disguised as images or other file types.
  489. */
  490. if ($this->xss_clean && $this->do_xss_clean() === FALSE)
  491. {
  492. $this->set_error('upload_unable_to_write_file', 'error');
  493. return FALSE;
  494. }
  495. /*
  496. * Move the file to the final destination
  497. * To deal with different server configurations
  498. * we'll attempt to use copy() first. If that fails
  499. * we'll use move_uploaded_file(). One of the two should
  500. * reliably work in most environments
  501. */
  502. if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
  503. {
  504. if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
  505. {
  506. $this->set_error('upload_destination_error', 'error');
  507. return FALSE;
  508. }
  509. }
  510. /*
  511. * Set the finalized image dimensions
  512. * This sets the image width/height (assuming the
  513. * file was an image). We use this information
  514. * in the "data" function.
  515. */
  516. $this->set_image_properties($this->upload_path.$this->file_name);
  517. return TRUE;
  518. }
  519. // --------------------------------------------------------------------
  520. /**
  521. * Finalized Data Array
  522. *
  523. * Returns an associative array containing all of the information
  524. * related to the upload, allowing the developer easy access in one array.
  525. *
  526. * @param string $index
  527. * @return mixed
  528. */
  529. public function data($index = NULL)
  530. {
  531. $data = array(
  532. 'file_name' => $this->file_name,
  533. 'file_type' => $this->file_type,
  534. 'file_path' => $this->upload_path,
  535. 'full_path' => $this->upload_path.$this->file_name,
  536. 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)),
  537. 'orig_name' => $this->orig_name,
  538. 'client_name' => $this->client_name,
  539. 'file_ext' => $this->file_ext,
  540. 'file_size' => $this->file_size,
  541. 'is_image' => $this->is_image(),
  542. 'image_width' => $this->image_width,
  543. 'image_height' => $this->image_height,
  544. 'image_type' => $this->image_type,
  545. 'image_size_str' => $this->image_size_str,
  546. );
  547. if ( ! empty($index))
  548. {
  549. return isset($data[$index]) ? $data[$index] : NULL;
  550. }
  551. return $data;
  552. }
  553. // --------------------------------------------------------------------
  554. /**
  555. * Set Upload Path
  556. *
  557. * @param string $path
  558. * @return CI_Upload
  559. */
  560. public function set_upload_path($path)
  561. {
  562. // Make sure it has a trailing slash
  563. $this->upload_path = rtrim($path, '/').'/';
  564. return $this;
  565. }
  566. // --------------------------------------------------------------------
  567. /**
  568. * Set the file name
  569. *
  570. * This function takes a filename/path as input and looks for the
  571. * existence of a file with the same name. If found, it will append a
  572. * number to the end of the filename to avoid overwriting a pre-existing file.
  573. *
  574. * @param string $path
  575. * @param string $filename
  576. * @return string
  577. */
  578. public function set_filename($path, $filename)
  579. {
  580. if ($this->encrypt_name === TRUE)
  581. {
  582. $filename = md5(uniqid(mt_rand())).$this->file_ext;
  583. }
  584. if ($this->overwrite === TRUE OR ! file_exists($path.$filename))
  585. {
  586. return $filename;
  587. }
  588. $filename = str_replace($this->file_ext, '', $filename);
  589. $new_filename = '';
  590. for ($i = 1; $i < $this->max_filename_increment; $i++)
  591. {
  592. if ( ! file_exists($path.$filename.$i.$this->file_ext))
  593. {
  594. $new_filename = $filename.$i.$this->file_ext;
  595. break;
  596. }
  597. }
  598. if ($new_filename === '')
  599. {
  600. $this->set_error('upload_bad_filename', 'debug');
  601. return FALSE;
  602. }
  603. else
  604. {
  605. return $new_filename;
  606. }
  607. }
  608. // --------------------------------------------------------------------
  609. /**
  610. * Set Maximum File Size
  611. *
  612. * @param int $n
  613. * @return CI_Upload
  614. */
  615. public function set_max_filesize($n)
  616. {
  617. $this->max_size = ($n < 0) ? 0 : (int) $n;
  618. return $this;
  619. }
  620. // --------------------------------------------------------------------
  621. /**
  622. * Set Maximum File Size
  623. *
  624. * An internal alias to set_max_filesize() to help with configuration
  625. * as initialize() will look for a set_<property_name>() method ...
  626. *
  627. * @param int $n
  628. * @return CI_Upload
  629. */
  630. protected function set_max_size($n)
  631. {
  632. return $this->set_max_filesize($n);
  633. }
  634. // --------------------------------------------------------------------
  635. /**
  636. * Set Maximum File Name Length
  637. *
  638. * @param int $n
  639. * @return CI_Upload
  640. */
  641. public function set_max_filename($n)
  642. {
  643. $this->max_filename = ($n < 0) ? 0 : (int) $n;
  644. return $this;
  645. }
  646. // --------------------------------------------------------------------
  647. /**
  648. * Set Maximum Image Width
  649. *
  650. * @param int $n
  651. * @return CI_Upload
  652. */
  653. public function set_max_width($n)
  654. {
  655. $this->max_width = ($n < 0) ? 0 : (int) $n;
  656. return $this;
  657. }
  658. // --------------------------------------------------------------------
  659. /**
  660. * Set Maximum Image Height
  661. *
  662. * @param int $n
  663. * @return CI_Upload
  664. */
  665. public function set_max_height($n)
  666. {
  667. $this->max_height = ($n < 0) ? 0 : (int) $n;
  668. return $this;
  669. }
  670. // --------------------------------------------------------------------
  671. /**
  672. * Set minimum image width
  673. *
  674. * @param int $n
  675. * @return CI_Upload
  676. */
  677. public function set_min_width($n)
  678. {
  679. $this->min_width = ($n < 0) ? 0 : (int) $n;
  680. return $this;
  681. }
  682. // --------------------------------------------------------------------
  683. /**
  684. * Set minimum image height
  685. *
  686. * @param int $n
  687. * @return CI_Upload
  688. */
  689. public function set_min_height($n)
  690. {
  691. $this->min_height = ($n < 0) ? 0 : (int) $n;
  692. return $this;
  693. }
  694. // --------------------------------------------------------------------
  695. /**
  696. * Set Allowed File Types
  697. *
  698. * @param mixed $types
  699. * @return CI_Upload
  700. */
  701. public function set_allowed_types($types)
  702. {
  703. $this->allowed_types = (is_array($types) OR $types === '*')
  704. ? $types
  705. : explode('|', $types);
  706. return $this;
  707. }
  708. // --------------------------------------------------------------------
  709. /**
  710. * Set Image Properties
  711. *
  712. * Uses GD to determine the width/height/type of image
  713. *
  714. * @param string $path
  715. * @return CI_Upload
  716. */
  717. public function set_image_properties($path = '')
  718. {
  719. if ($this->is_image() && function_exists('getimagesize'))
  720. {
  721. if (FALSE !== ($D = @getimagesize($path)))
  722. {
  723. $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
  724. $this->image_width = $D[0];
  725. $this->image_height = $D[1];
  726. $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown';
  727. $this->image_size_str = $D[3]; // string containing height and width
  728. }
  729. }
  730. return $this;
  731. }
  732. // --------------------------------------------------------------------
  733. /**
  734. * Set XSS Clean
  735. *
  736. * Enables the XSS flag so that the file that was uploaded
  737. * will be run through the XSS filter.
  738. *
  739. * @param bool $flag
  740. * @return CI_Upload
  741. */
  742. public function set_xss_clean($flag = FALSE)
  743. {
  744. $this->xss_clean = ($flag === TRUE);
  745. return $this;
  746. }
  747. // --------------------------------------------------------------------
  748. /**
  749. * Validate the image
  750. *
  751. * @return bool
  752. */
  753. public function is_image()
  754. {
  755. // IE will sometimes return odd mime-types during upload, so here we just standardize all
  756. // jpegs or pngs to the same file type.
  757. $png_mimes = array('image/x-png');
  758. $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');
  759. if (in_array($this->file_type, $png_mimes))
  760. {
  761. $this->file_type = 'image/png';
  762. }
  763. elseif (in_array($this->file_type, $jpeg_mimes))
  764. {
  765. $this->file_type = 'image/jpeg';
  766. }
  767. $img_mimes = array('image/gif', 'image/jpeg', 'image/png');
  768. return in_array($this->file_type, $img_mimes, TRUE);
  769. }
  770. // --------------------------------------------------------------------
  771. /**
  772. * Verify that the filetype is allowed
  773. *
  774. * @param bool $ignore_mime
  775. * @return bool
  776. */
  777. public function is_allowed_filetype($ignore_mime = FALSE)
  778. {
  779. if ($this->allowed_types === '*')
  780. {
  781. return TRUE;
  782. }
  783. if (empty($this->allowed_types) OR ! is_array($this->allowed_types))
  784. {
  785. $this->set_error('upload_no_file_types', 'debug');
  786. return FALSE;
  787. }
  788. $ext = strtolower(ltrim($this->file_ext, '.'));
  789. if ( ! in_array($ext, $this->allowed_types, TRUE))
  790. {
  791. return FALSE;
  792. }
  793. // Images get some additional checks
  794. if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE)
  795. {
  796. return FALSE;
  797. }
  798. if ($ignore_mime === TRUE)
  799. {
  800. return TRUE;
  801. }
  802. if (isset($this->_mimes[$ext]))
  803. {
  804. return is_array($this->_mimes[$ext])
  805. ? in_array($this->file_type, $this->_mimes[$ext], TRUE)
  806. : ($this->_mimes[$ext] === $this->file_type);
  807. }
  808. return FALSE;
  809. }
  810. // --------------------------------------------------------------------
  811. /**
  812. * Verify that the file is within the allowed size
  813. *
  814. * @return bool
  815. */
  816. public function is_allowed_filesize()
  817. {
  818. return ($this->max_size === 0 OR $this->max_size > $this->file_size);
  819. }
  820. // --------------------------------------------------------------------
  821. /**
  822. * Verify that the image is within the allowed width/height
  823. *
  824. * @return bool
  825. */
  826. public function is_allowed_dimensions()
  827. {
  828. if ( ! $this->is_image())
  829. {
  830. return TRUE;
  831. }
  832. if (function_exists('getimagesize'))
  833. {
  834. $D = @getimagesize($this->file_temp);
  835. if ($this->max_width > 0 && $D[0] > $this->max_width)
  836. {
  837. return FALSE;
  838. }
  839. if ($this->max_height > 0 && $D[1] > $this->max_height)
  840. {
  841. return FALSE;
  842. }
  843. if ($this->min_width > 0 && $D[0] < $this->min_width)
  844. {
  845. return FALSE;
  846. }
  847. if ($this->min_height > 0 && $D[1] < $this->min_height)
  848. {
  849. return FALSE;
  850. }
  851. }
  852. return TRUE;
  853. }
  854. // --------------------------------------------------------------------
  855. /**
  856. * Validate Upload Path
  857. *
  858. * Verifies that it is a valid upload path with proper permissions.
  859. *
  860. * @return bool
  861. */
  862. public function validate_upload_path()
  863. {
  864. if ($this->upload_path === '')
  865. {
  866. $this->set_error('upload_no_filepath', 'error');
  867. return FALSE;
  868. }
  869. if (realpath($this->upload_path) !== FALSE)
  870. {
  871. $this->upload_path = str_replace('\\', '/', realpath($this->upload_path));
  872. }
  873. if ( ! is_dir($this->upload_path))
  874. {
  875. $this->set_error('upload_no_filepath', 'error');
  876. return FALSE;
  877. }
  878. if ( ! is_really_writable($this->upload_path))
  879. {
  880. $this->set_error('upload_not_writable', 'error');
  881. return FALSE;
  882. }
  883. $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path);
  884. return TRUE;
  885. }
  886. // --------------------------------------------------------------------
  887. /**
  888. * Extract the file extension
  889. *
  890. * @param string $filename
  891. * @return string
  892. */
  893. public function get_extension($filename)
  894. {
  895. $x = explode('.', $filename);
  896. if (count($x) === 1)
  897. {
  898. return '';
  899. }
  900. $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x);
  901. return '.'.$ext;
  902. }
  903. // --------------------------------------------------------------------
  904. /**
  905. * Limit the File Name Length
  906. *
  907. * @param string $filename
  908. * @param int $length
  909. * @return string
  910. */
  911. public function limit_filename_length($filename, $length)
  912. {
  913. if (strlen($filename) < $length)
  914. {
  915. return $filename;
  916. }
  917. $ext = '';
  918. if (strpos($filename, '.') !== FALSE)
  919. {
  920. $parts = explode('.', $filename);
  921. $ext = '.'.array_pop($parts);
  922. $filename = implode('.', $parts);
  923. }
  924. return substr($filename, 0, ($length - strlen($ext))).$ext;
  925. }
  926. // --------------------------------------------------------------------
  927. /**
  928. * Runs the file through the XSS clean function
  929. *
  930. * This prevents people from embedding malicious code in their files.
  931. * I'm not sure that it won't negatively affect certain files in unexpected ways,
  932. * but so far I haven't found that it causes trouble.
  933. *
  934. * @return string
  935. */
  936. public function do_xss_clean()
  937. {
  938. $file = $this->file_temp;
  939. if (filesize($file) == 0)
  940. {
  941. return FALSE;
  942. }
  943. if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0)
  944. {
  945. $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890'));
  946. if ( ! empty($memory_limit[1]))
  947. {
  948. switch ($memory_limit[1][0])
  949. {
  950. case 'g':
  951. case 'G':
  952. $memory_limit[0] *= 1024 * 1024 * 1024;
  953. break;
  954. case 'm':
  955. case 'M':
  956. $memory_limit[0] *= 1024 * 1024;
  957. break;
  958. default:
  959. break;
  960. }
  961. }
  962. $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]);
  963. ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net
  964. }
  965. // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but
  966. // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
  967. // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
  968. // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
  969. // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
  970. // attempted XSS attack.
  971. if (function_exists('getimagesize') && @getimagesize($file) !== FALSE)
  972. {
  973. if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary
  974. {
  975. return FALSE; // Couldn't open the file, return FALSE
  976. }
  977. $opening_bytes = fread($file, 256);
  978. fclose($file);
  979. // These are known to throw IE into mime-type detection chaos
  980. // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title
  981. // title is basically just in SVG, but we filter it anyhow
  982. // if it's an image or no "triggers" detected in the first 256 bytes - we're good
  983. return ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes);
  984. }
  985. if (($data = @file_get_contents($file)) === FALSE)
  986. {
  987. return FALSE;
  988. }
  989. return $this->_CI->security->xss_clean($data, TRUE);
  990. }
  991. // --------------------------------------------------------------------
  992. /**
  993. * Set an error message
  994. *
  995. * @param string $msg
  996. * @return CI_Upload
  997. */
  998. public function set_error($msg, $log_level = 'error')
  999. {
  1000. $this->_CI->lang->load('upload');
  1001. is_array($msg) OR $msg = array($msg);
  1002. foreach ($msg as $val)
  1003. {
  1004. $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val);
  1005. $this->error_msg[] = $msg;
  1006. log_message($log_level, $msg);
  1007. }
  1008. return $this;
  1009. }
  1010. // --------------------------------------------------------------------
  1011. /**
  1012. * Display the error message
  1013. *
  1014. * @param string $open
  1015. * @param string $close
  1016. * @return string
  1017. */
  1018. public function display_errors($open = '<p>', $close = '</p>')
  1019. {
  1020. return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : '';
  1021. }
  1022. // --------------------------------------------------------------------
  1023. /**
  1024. * Prep Filename
  1025. *
  1026. * Prevents possible script execution from Apache's handling
  1027. * of files' multiple extensions.
  1028. *
  1029. * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
  1030. *
  1031. * @param string $filename
  1032. * @return string
  1033. */
  1034. protected function _prep_filename($filename)
  1035. {
  1036. if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE)
  1037. {
  1038. return $filename;
  1039. }
  1040. $ext = substr($filename, $ext_pos);
  1041. $filename = substr($filename, 0, $ext_pos);
  1042. return str_replace('.', '_', $filename).$ext;
  1043. }
  1044. // --------------------------------------------------------------------
  1045. /**
  1046. * File MIME type
  1047. *
  1048. * Detects the (actual) MIME type of the uploaded file, if possible.
  1049. * The input array is expected to be $_FILES[$field]
  1050. *
  1051. * @param array $file
  1052. * @return void
  1053. */
  1054. protected function _file_mime_type($file)
  1055. {
  1056. // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
  1057. $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';
  1058. /**
  1059. * Fileinfo extension - most reliable method
  1060. *
  1061. * Apparently XAMPP, CentOS, cPanel and who knows what
  1062. * other PHP distribution channels EXPLICITLY DISABLE
  1063. * ext/fileinfo, which is otherwise enabled by default
  1064. * since PHP 5.3 ...
  1065. */
  1066. if (function_exists('finfo_file'))
  1067. {
  1068. $finfo = @finfo_open(FILEINFO_MIME);
  1069. 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
  1070. {
  1071. $mime = @finfo_file($finfo, $file['tmp_name']);
  1072. finfo_close($finfo);
  1073. /* According to the comments section of the PHP manual page,
  1074. * it is possible that this function returns an empty string
  1075. * for some files (e.g. if they don't exist in the magic MIME database)
  1076. */
  1077. if (is_string($mime) && preg_match($regexp, $mime, $matches))
  1078. {
  1079. $this->file_type = $matches[1];
  1080. return;
  1081. }
  1082. }
  1083. }
  1084. /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
  1085. * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
  1086. * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
  1087. * than mime_content_type() as well, hence the attempts to try calling the command line with
  1088. * three different functions.
  1089. *
  1090. * Notes:
  1091. * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
  1092. * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
  1093. * due to security concerns, hence the function_usable() checks
  1094. */
  1095. if (DIRECTORY_SEPARATOR !== '\\')
  1096. {
  1097. $cmd = function_exists('escapeshellarg')
  1098. ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1'
  1099. : 'file --brief --mime '.$file['tmp_name'].' 2>&1';
  1100. if (function_usable('exec'))
  1101. {
  1102. /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter.
  1103. * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites
  1104. * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy
  1105. * value, which is only put to allow us to get the return status code.
  1106. */
  1107. $mime = @exec($cmd, $mime, $return_status);
  1108. if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches))
  1109. {
  1110. $this->file_type = $matches[1];
  1111. return;
  1112. }
  1113. }
  1114. if ( ! ini_get('safe_mode') && function_usable('shell_exec'))
  1115. {
  1116. $mime = @shell_exec($cmd);
  1117. if (strlen($mime) > 0)
  1118. {
  1119. $mime = explode("\n", trim($mime));
  1120. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
  1121. {
  1122. $this->file_type = $matches[1];
  1123. return;
  1124. }
  1125. }
  1126. }
  1127. if (function_usable('popen'))
  1128. {
  1129. $proc = @popen($cmd, 'r');
  1130. if (is_resource($proc))
  1131. {
  1132. $mime = @fread($proc, 512);
  1133. @pclose($proc);
  1134. if ($mime !== FALSE)
  1135. {
  1136. $mime = explode("\n", trim($mime));
  1137. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
  1138. {
  1139. $this->file_type = $matches[1];
  1140. return;
  1141. }
  1142. }
  1143. }
  1144. }
  1145. }
  1146. // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type'])
  1147. if (function_exists('mime_content_type'))
  1148. {
  1149. $this->file_type = @mime_content_type($file['tmp_name']);
  1150. if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string
  1151. {
  1152. return;
  1153. }
  1154. }
  1155. $this->file_type = $file['type'];
  1156. }
  1157. }