PageRenderTime 50ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Validate/File/MimeType.php

https://bitbucket.org/goldie/zend-framework1
PHP | 476 lines | 240 code | 53 blank | 183 comment | 40 complexity | 77093077516988b21c0a714af772fb5d MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Validate
  17. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * @see Zend_Validate_Abstract
  23. */
  24. require_once 'Zend/Validate/Abstract.php';
  25. /**
  26. * Validator for the mime type of a file
  27. *
  28. * @category Zend
  29. * @package Zend_Validate
  30. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  31. * @license http://framework.zend.com/license/new-bsd New BSD License
  32. */
  33. class Zend_Validate_File_MimeType extends Zend_Validate_Abstract
  34. {
  35. /**
  36. * @const Error type constants
  37. */
  38. const FALSE_TYPE = 'fileMimeTypeFalse';
  39. const NOT_DETECTED = 'fileMimeTypeNotDetected';
  40. const NOT_READABLE = 'fileMimeTypeNotReadable';
  41. /**
  42. * @var array Error message templates
  43. */
  44. protected $_messageTemplates = array(
  45. self::FALSE_TYPE => "File '%value%' has a false mimetype of '%type%'",
  46. self::NOT_DETECTED => "The mimetype of file '%value%' could not be detected",
  47. self::NOT_READABLE => "File '%value%' is not readable or does not exist",
  48. );
  49. /**
  50. * @var array
  51. */
  52. protected $_messageVariables = array(
  53. 'type' => '_type'
  54. );
  55. /**
  56. * @var string
  57. */
  58. protected $_type;
  59. /**
  60. * Mimetypes
  61. *
  62. * If null, there is no mimetype
  63. *
  64. * @var string|null
  65. */
  66. protected $_mimetype;
  67. /**
  68. * Magicfile to use
  69. *
  70. * @var string|null
  71. */
  72. protected $_magicfile;
  73. /**
  74. * Finfo object to use
  75. *
  76. * @var resource
  77. */
  78. protected $_finfo;
  79. /**
  80. * If no $_ENV['MAGIC'] is set, try and autodiscover it based on common locations
  81. * @var array
  82. */
  83. protected $_magicFiles = array(
  84. '/usr/share/misc/magic',
  85. '/usr/share/misc/magic.mime',
  86. '/usr/share/misc/magic.mgc',
  87. '/usr/share/mime/magic',
  88. '/usr/share/mime/magic.mime',
  89. '/usr/share/mime/magic.mgc',
  90. '/usr/share/file/magic',
  91. '/usr/share/file/magic.mime',
  92. '/usr/share/file/magic.mgc',
  93. );
  94. /**
  95. * Indicates whether use of $_magicFiles should be attempted.
  96. * @var boolean
  97. */
  98. protected $_tryCommonMagicFiles = true;
  99. /**
  100. * Option to allow header check
  101. *
  102. * @var boolean
  103. */
  104. protected $_headerCheck = false;
  105. /**
  106. * Holds error information returned by finfo_open
  107. *
  108. * @var array
  109. */
  110. protected $_finfoError;
  111. /**
  112. * Sets validator options
  113. *
  114. * Mimetype to accept
  115. *
  116. * @param string|array $mimetype MimeType
  117. * @throws Zend_Validate_Exception
  118. */
  119. public function __construct($mimetype)
  120. {
  121. if ($mimetype instanceof Zend_Config) {
  122. $mimetype = $mimetype->toArray();
  123. } elseif (is_string($mimetype)) {
  124. $mimetype = explode(',', $mimetype);
  125. } elseif (!is_array($mimetype)) {
  126. require_once 'Zend/Validate/Exception.php';
  127. throw new Zend_Validate_Exception("Invalid options to validator provided");
  128. }
  129. if (isset($mimetype['magicfile'])) {
  130. $this->setMagicFile($mimetype['magicfile']);
  131. unset($mimetype['magicfile']);
  132. }
  133. if (isset($mimetype['headerCheck'])) {
  134. $this->enableHeaderCheck($mimetype['headerCheck']);
  135. unset($mimetype['headerCheck']);
  136. }
  137. $this->setMimeType($mimetype);
  138. }
  139. /**
  140. * Returns the actual set magicfile
  141. *
  142. * Note that for PHP 5.3.0 or higher, we don't use $_ENV['MAGIC'] or try to
  143. * find a magic file in a common location as PHP now has a built-in internal
  144. * magic file.
  145. *
  146. * @return string
  147. */
  148. public function getMagicFile()
  149. {
  150. if (version_compare(PHP_VERSION, '5.3.0', '<')
  151. && null === $this->_magicfile) {
  152. if (!empty($_ENV['MAGIC'])) {
  153. $this->setMagicFile($_ENV['MAGIC']);
  154. } elseif (
  155. !(@ini_get("safe_mode") == 'On' || @ini_get("safe_mode") === 1)
  156. && $this->shouldTryCommonMagicFiles() // @see ZF-11784
  157. ) {
  158. require_once 'Zend/Validate/Exception.php';
  159. foreach ($this->_magicFiles as $file) {
  160. // supressing errors which are thrown due to openbase_dir restrictions
  161. try {
  162. $this->setMagicFile($file);
  163. if ($this->_magicfile !== null) {
  164. break;
  165. }
  166. } catch (Zend_Validate_Exception $e) {
  167. // Intentionally, catch and fall through
  168. }
  169. }
  170. }
  171. if ($this->_magicfile === null) {
  172. $this->_magicfile = false;
  173. }
  174. }
  175. return $this->_magicfile;
  176. }
  177. /**
  178. * Sets the magicfile to use
  179. * if null, the MAGIC constant from php is used
  180. * if the MAGIC file is errorous, no file will be set
  181. *
  182. * @param string $file
  183. * @throws Zend_Validate_Exception When finfo can not read the magicfile
  184. * @return Zend_Validate_File_MimeType Provides a fluent interface
  185. */
  186. public function setMagicFile($file)
  187. {
  188. if (empty($file)) {
  189. $this->_magicfile = null;
  190. } else if (!(class_exists('finfo', false))) {
  191. $this->_magicfile = null;
  192. require_once 'Zend/Validate/Exception.php';
  193. throw new Zend_Validate_Exception('Magicfile can not be set. There is no finfo extension installed');
  194. } else if (!is_file($file) || !is_readable($file)) {
  195. require_once 'Zend/Validate/Exception.php';
  196. throw new Zend_Validate_Exception('The given magicfile can not be read');
  197. } else {
  198. $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
  199. set_error_handler(array($this, '_errorHandler'), E_NOTICE | E_WARNING);
  200. $this->_finfo = finfo_open($const, $file);
  201. restore_error_handler();
  202. if (empty($this->_finfo)) {
  203. $this->_finfo = null;
  204. require_once 'Zend/Validate/Exception.php';
  205. throw new Zend_Validate_Exception(
  206. sprintf('The given magicfile ("%s") is not accepted by finfo', $file),
  207. null,
  208. $this->_finfoError
  209. );
  210. } else {
  211. $this->_magicfile = $file;
  212. }
  213. }
  214. return $this;
  215. }
  216. /**
  217. * Enables or disables attempts to try the common magic file locations
  218. * specified by Zend_Validate_File_MimeType::_magicFiles
  219. *
  220. * @param boolean $flag
  221. * @return Zend_Validate_File_MimeType Provides fluent interface
  222. * @see http://framework.zend.com/issues/browse/ZF-11784
  223. */
  224. public function setTryCommonMagicFilesFlag($flag = true)
  225. {
  226. $this->_tryCommonMagicFiles = (boolean) $flag;
  227. return $this;
  228. }
  229. /**
  230. * Accessor for Zend_Validate_File_MimeType::_magicFiles
  231. *
  232. * @return boolean
  233. * @see http://framework.zend.com/issues/browse/ZF-11784
  234. */
  235. public function shouldTryCommonMagicFiles()
  236. {
  237. return $this->_tryCommonMagicFiles;
  238. }
  239. /**
  240. * Returns the Header Check option
  241. *
  242. * @return boolean
  243. */
  244. public function getHeaderCheck()
  245. {
  246. return $this->_headerCheck;
  247. }
  248. /**
  249. * Defines if the http header should be used
  250. * Note that this is unsave and therefor the default value is false
  251. *
  252. * @param boolean $headerCheck
  253. * @return Zend_Validate_File_MimeType Provides a fluent interface
  254. */
  255. public function enableHeaderCheck($headerCheck = true)
  256. {
  257. $this->_headerCheck = (boolean) $headerCheck;
  258. return $this;
  259. }
  260. /**
  261. * Returns the set mimetypes
  262. *
  263. * @param boolean $asArray Returns the values as array, when false an concated string is returned
  264. * @return string|array
  265. */
  266. public function getMimeType($asArray = false)
  267. {
  268. $asArray = (bool) $asArray;
  269. $mimetype = (string) $this->_mimetype;
  270. if ($asArray) {
  271. $mimetype = explode(',', $mimetype);
  272. }
  273. return $mimetype;
  274. }
  275. /**
  276. * Sets the mimetypes
  277. *
  278. * @param string|array $mimetype The mimetypes to validate
  279. * @return Zend_Validate_File_Extension Provides a fluent interface
  280. */
  281. public function setMimeType($mimetype)
  282. {
  283. $this->_mimetype = null;
  284. $this->addMimeType($mimetype);
  285. return $this;
  286. }
  287. /**
  288. * Adds the mimetypes
  289. *
  290. * @param string|array $mimetype The mimetypes to add for validation
  291. * @throws Zend_Validate_Exception
  292. * @return Zend_Validate_File_Extension Provides a fluent interface
  293. */
  294. public function addMimeType($mimetype)
  295. {
  296. $mimetypes = $this->getMimeType(true);
  297. if (is_string($mimetype)) {
  298. $mimetype = explode(',', $mimetype);
  299. } elseif (!is_array($mimetype)) {
  300. require_once 'Zend/Validate/Exception.php';
  301. throw new Zend_Validate_Exception("Invalid options to validator provided");
  302. }
  303. if (isset($mimetype['magicfile'])) {
  304. unset($mimetype['magicfile']);
  305. }
  306. foreach ($mimetype as $content) {
  307. if (empty($content) || !is_string($content)) {
  308. continue;
  309. }
  310. $mimetypes[] = trim($content);
  311. }
  312. $mimetypes = array_unique($mimetypes);
  313. // Sanity check to ensure no empty values
  314. foreach ($mimetypes as $key => $mt) {
  315. if (empty($mt)) {
  316. unset($mimetypes[$key]);
  317. }
  318. }
  319. $this->_mimetype = implode(',', $mimetypes);
  320. return $this;
  321. }
  322. /**
  323. * Defined by Zend_Validate_Interface
  324. *
  325. * Returns true if the mimetype of the file matches the given ones. Also parts
  326. * of mimetypes can be checked. If you give for example "image" all image
  327. * mime types will be accepted like "image/gif", "image/jpeg" and so on.
  328. *
  329. * @param string $value Real file to check for mimetype
  330. * @param array $file File data from Zend_File_Transfer
  331. * @return boolean
  332. */
  333. public function isValid($value, $file = null)
  334. {
  335. if ($file === null) {
  336. $file = array(
  337. 'type' => null,
  338. 'name' => $value
  339. );
  340. }
  341. // Is file readable ?
  342. require_once 'Zend/Loader.php';
  343. if (!Zend_Loader::isReadable($value)) {
  344. return $this->_throw($file, self::NOT_READABLE);
  345. }
  346. $this->_type = $this->_detectMimeType($value);
  347. if (empty($this->_type) && $this->_headerCheck) {
  348. $this->_type = $file['type'];
  349. }
  350. if (empty($this->_type)) {
  351. return $this->_throw($file, self::NOT_DETECTED);
  352. }
  353. $mimetype = $this->getMimeType(true);
  354. if (in_array($this->_type, $mimetype)) {
  355. return true;
  356. }
  357. $types = explode('/', $this->_type);
  358. $types = array_merge($types, explode('-', $this->_type));
  359. $types = array_merge($types, explode(';', $this->_type));
  360. foreach($mimetype as $mime) {
  361. if (in_array($mime, $types)) {
  362. return true;
  363. }
  364. }
  365. return $this->_throw($file, self::FALSE_TYPE);
  366. }
  367. /**
  368. * Throws an error of the given type
  369. *
  370. * @param string $file
  371. * @param string $errorType
  372. * @return false
  373. */
  374. protected function _throw($file, $errorType)
  375. {
  376. $this->_value = $file['name'];
  377. $this->_error($errorType);
  378. return false;
  379. }
  380. /**
  381. * Try to detect mime type of given file.
  382. * @param string $file File which mime type should be detected
  383. * @return string File mime type or null if not detected
  384. */
  385. protected function _detectMimeType($file)
  386. {
  387. $mimefile = $this->getMagicFile();
  388. $type = null;
  389. if (class_exists('finfo', false)) {
  390. $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
  391. if (!empty($mimefile) && empty($this->_finfo)) {
  392. set_error_handler(array($this, '_errorHandler'), E_NOTICE | E_WARNING);
  393. $this->_finfo = finfo_open($const, $mimefile);
  394. restore_error_handler();
  395. }
  396. if (empty($this->_finfo)) {
  397. set_error_handler(array($this, '_errorHandler'), E_NOTICE | E_WARNING);
  398. $this->_finfo = finfo_open($const);
  399. restore_error_handler();
  400. }
  401. if (!empty($this->_finfo)) {
  402. $type = finfo_file($this->_finfo, $file);
  403. }
  404. }
  405. if (empty($type) &&
  406. (function_exists('mime_content_type') && ini_get('mime_magic.magicfile'))) {
  407. $type = mime_content_type($file);
  408. }
  409. return $type;
  410. }
  411. /**
  412. * Saves the provided error information by finfo_open to this instance
  413. *
  414. * @param integer $errno
  415. * @param string $errstr
  416. * @param string $errfile
  417. * @param integer $errline
  418. */
  419. protected function _errorHandler($errno, $errstr, $errfile, $errline)
  420. {
  421. $this->_finfoError = new ErrorException($errstr, $errno, 0, $errfile, $errline);
  422. }
  423. }