Upload.php 32 KB

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