File.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use SplFileObject;
  13. class File extends SplFileObject
  14. {
  15. /**
  16. * @var string 错误信息
  17. */
  18. private $error = '';
  19. /**
  20. * @var string 当前完整文件名
  21. */
  22. protected $filename;
  23. /**
  24. * @var string 上传文件名
  25. */
  26. protected $saveName;
  27. /**
  28. * @var string 文件上传命名规则
  29. */
  30. protected $rule = 'date';
  31. /**
  32. * @var array 文件上传验证规则
  33. */
  34. protected $validate = [];
  35. /**
  36. * @var bool 单元测试
  37. */
  38. protected $isTest;
  39. /**
  40. * @var array 上传文件信息
  41. */
  42. protected $info;
  43. /**
  44. * @var array 文件 hash 信息
  45. */
  46. protected $hash = [];
  47. /**
  48. * File constructor.
  49. * @access public
  50. * @param string $filename 文件名称
  51. * @param string $mode 访问模式
  52. */
  53. public function __construct($filename, $mode = 'r')
  54. {
  55. parent::__construct($filename, $mode);
  56. $this->filename = $this->getRealPath() ?: $this->getPathname();
  57. }
  58. /**
  59. * 设置是否是单元测试
  60. * @access public
  61. * @param bool $test 是否是测试
  62. * @return $this
  63. */
  64. public function isTest($test = false)
  65. {
  66. $this->isTest = $test;
  67. return $this;
  68. }
  69. /**
  70. * 设置上传信息
  71. * @access public
  72. * @param array $info 上传文件信息
  73. * @return $this
  74. */
  75. public function setUploadInfo($info)
  76. {
  77. $this->info = $info;
  78. return $this;
  79. }
  80. /**
  81. * 获取上传文件的信息
  82. * @access public
  83. * @param string $name 信息名称
  84. * @return array|string
  85. */
  86. public function getInfo($name = '')
  87. {
  88. return isset($this->info[$name]) ? $this->info[$name] : $this->info;
  89. }
  90. /**
  91. * 获取上传文件的文件名
  92. * @access public
  93. * @return string
  94. */
  95. public function getSaveName()
  96. {
  97. return $this->saveName;
  98. }
  99. /**
  100. * 设置上传文件的保存文件名
  101. * @access public
  102. * @param string $saveName 保存名称
  103. * @return $this
  104. */
  105. public function setSaveName($saveName)
  106. {
  107. $this->saveName = $saveName;
  108. return $this;
  109. }
  110. /**
  111. * 获取文件的哈希散列值
  112. * @access public
  113. * @param string $type 类型
  114. * @return string
  115. */
  116. public function hash($type = 'sha1')
  117. {
  118. if (!isset($this->hash[$type])) {
  119. $this->hash[$type] = hash_file($type, $this->filename);
  120. }
  121. return $this->hash[$type];
  122. }
  123. /**
  124. * 检查目录是否可写
  125. * @access protected
  126. * @param string $path 目录
  127. * @return boolean
  128. */
  129. protected function checkPath($path)
  130. {
  131. if (is_dir($path)) {
  132. return true;
  133. }
  134. if (@mkdir($path, 0755, true)) {
  135. return true;
  136. }
  137. if (is_dir($path)) {
  138. return true;
  139. }
  140. $this->error = ['directory {:path} creation failed', ['path' => $path]];
  141. return false;
  142. }
  143. /**
  144. * 获取文件类型信息
  145. * @access public
  146. * @return string
  147. */
  148. public function getMime()
  149. {
  150. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  151. return finfo_file($finfo, $this->filename);
  152. }
  153. /**
  154. * 设置文件的命名规则
  155. * @access public
  156. * @param string $rule 文件命名规则
  157. * @return $this
  158. */
  159. public function rule($rule)
  160. {
  161. $this->rule = $rule;
  162. return $this;
  163. }
  164. /**
  165. * 设置上传文件的验证规则
  166. * @access public
  167. * @param array $rule 验证规则
  168. * @return $this
  169. */
  170. public function validate(array $rule = [])
  171. {
  172. $this->validate = $rule;
  173. return $this;
  174. }
  175. /**
  176. * 检测是否合法的上传文件
  177. * @access public
  178. * @return bool
  179. */
  180. public function isValid()
  181. {
  182. return $this->isTest ? is_file($this->filename) : is_uploaded_file($this->filename);
  183. }
  184. /**
  185. * 检测上传文件
  186. * @access public
  187. * @param array $rule 验证规则
  188. * @return bool
  189. */
  190. public function check($rule = [])
  191. {
  192. $rule = $rule ?: $this->validate;
  193. /* 检查文件大小 */
  194. if (isset($rule['size']) && !$this->checkSize($rule['size'])) {
  195. $this->error = 'filesize not match';
  196. return false;
  197. }
  198. /* 检查文件 Mime 类型 */
  199. if (isset($rule['type']) && !$this->checkMime($rule['type'])) {
  200. $this->error = 'mimetype to upload is not allowed';
  201. return false;
  202. }
  203. /* 检查文件后缀 */
  204. if (isset($rule['ext']) && !$this->checkExt($rule['ext'])) {
  205. $this->error = 'extensions to upload is not allowed';
  206. return false;
  207. }
  208. /* 检查图像文件 */
  209. if (!$this->checkImg()) {
  210. $this->error = 'illegal image files';
  211. return false;
  212. }
  213. return true;
  214. }
  215. /**
  216. * 检测上传文件后缀
  217. * @access public
  218. * @param array|string $ext 允许后缀
  219. * @return bool
  220. */
  221. public function checkExt($ext)
  222. {
  223. if (is_string($ext)) {
  224. $ext = explode(',', $ext);
  225. }
  226. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  227. return in_array($extension, $ext);
  228. }
  229. /**
  230. * 检测图像文件
  231. * @access public
  232. * @return bool
  233. */
  234. public function checkImg()
  235. {
  236. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  237. // 如果上传的不是图片,或者是图片而且后缀确实符合图片类型则返回 true
  238. return !in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) || in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6, 13]);
  239. }
  240. /**
  241. * 判断图像类型
  242. * @access protected
  243. * @param string $image 图片名称
  244. * @return bool|int
  245. */
  246. protected function getImageType($image)
  247. {
  248. if (function_exists('exif_imagetype')) {
  249. return exif_imagetype($image);
  250. }
  251. try {
  252. $info = getimagesize($image);
  253. return $info ? $info[2] : false;
  254. } catch (\Exception $e) {
  255. return false;
  256. }
  257. }
  258. /**
  259. * 检测上传文件大小
  260. * @access public
  261. * @param integer $size 最大大小
  262. * @return bool
  263. */
  264. public function checkSize($size)
  265. {
  266. return $this->getSize() <= $size;
  267. }
  268. /**
  269. * 检测上传文件类型
  270. * @access public
  271. * @param array|string $mime 允许类型
  272. * @return bool
  273. */
  274. public function checkMime($mime)
  275. {
  276. $mime = is_string($mime) ? explode(',', $mime) : $mime;
  277. return in_array(strtolower($this->getMime()), $mime);
  278. }
  279. /**
  280. * 移动文件
  281. * @access public
  282. * @param string $path 保存路径
  283. * @param string|bool $savename 保存的文件名 默认自动生成
  284. * @param boolean $replace 同名文件是否覆盖
  285. * @return false|File
  286. */
  287. public function move($path, $savename = true, $replace = true)
  288. {
  289. // 文件上传失败,捕获错误代码
  290. if (!empty($this->info['error'])) {
  291. $this->error($this->info['error']);
  292. return false;
  293. }
  294. // 检测合法性
  295. if (!$this->isValid()) {
  296. $this->error = 'upload illegal files';
  297. return false;
  298. }
  299. // 验证上传
  300. if (!$this->check()) {
  301. return false;
  302. }
  303. $path = rtrim($path, DS) . DS;
  304. // 文件保存命名规则
  305. $saveName = $this->buildSaveName($savename);
  306. $filename = $path . $saveName;
  307. // 检测目录
  308. if (false === $this->checkPath(dirname($filename))) {
  309. return false;
  310. }
  311. // 不覆盖同名文件
  312. if (!$replace && is_file($filename)) {
  313. $this->error = ['has the same filename: {:filename}', ['filename' => $filename]];
  314. return false;
  315. }
  316. /* 移动文件 */
  317. if ($this->isTest) {
  318. rename($this->filename, $filename);
  319. } elseif (!move_uploaded_file($this->filename, $filename)) {
  320. $this->error = 'upload write error';
  321. return false;
  322. }
  323. // 返回 File 对象实例
  324. $file = new self($filename);
  325. $file->setSaveName($saveName)->setUploadInfo($this->info);
  326. return $file;
  327. }
  328. /**
  329. * 获取保存文件名
  330. * @access protected
  331. * @param string|bool $savename 保存的文件名 默认自动生成
  332. * @return string
  333. */
  334. protected function buildSaveName($savename)
  335. {
  336. // 自动生成文件名
  337. if (true === $savename) {
  338. if ($this->rule instanceof \Closure) {
  339. $savename = call_user_func_array($this->rule, [$this]);
  340. } else {
  341. switch ($this->rule) {
  342. case 'date':
  343. $savename = date('Ymd') . DS . md5(microtime(true));
  344. break;
  345. default:
  346. if (in_array($this->rule, hash_algos())) {
  347. $hash = $this->hash($this->rule);
  348. $savename = substr($hash, 0, 2) . DS . substr($hash, 2);
  349. } elseif (is_callable($this->rule)) {
  350. $savename = call_user_func($this->rule);
  351. } else {
  352. $savename = date('Ymd') . DS . md5(microtime(true));
  353. }
  354. }
  355. }
  356. } elseif ('' === $savename || false === $savename) {
  357. $savename = $this->getInfo('name');
  358. }
  359. if (!strpos($savename, '.')) {
  360. $savename .= '.' . pathinfo($this->getInfo('name'), PATHINFO_EXTENSION);
  361. }
  362. return $savename;
  363. }
  364. /**
  365. * 获取错误代码信息
  366. * @access private
  367. * @param int $errorNo 错误号
  368. * @return $this
  369. */
  370. private function error($errorNo)
  371. {
  372. switch ($errorNo) {
  373. case 1:
  374. case 2:
  375. $this->error = 'upload File size exceeds the maximum value';
  376. break;
  377. case 3:
  378. $this->error = 'only the portion of file is uploaded';
  379. break;
  380. case 4:
  381. $this->error = 'no file to uploaded';
  382. break;
  383. case 6:
  384. $this->error = 'upload temp dir not found';
  385. break;
  386. case 7:
  387. $this->error = 'file write error';
  388. break;
  389. default:
  390. $this->error = 'unknown upload error';
  391. }
  392. return $this;
  393. }
  394. /**
  395. * 获取错误信息(支持多语言)
  396. * @access public
  397. * @return string
  398. */
  399. public function getError()
  400. {
  401. if (is_array($this->error)) {
  402. list($msg, $vars) = $this->error;
  403. } else {
  404. $msg = $this->error;
  405. $vars = [];
  406. }
  407. return Lang::has($msg) ? Lang::get($msg, $vars) : $msg;
  408. }
  409. /**
  410. * 魔法方法,获取文件的 hash 值
  411. * @access public
  412. * @param string $method 方法名
  413. * @param mixed $args 调用参数
  414. * @return string
  415. */
  416. public function __call($method, $args)
  417. {
  418. return $this->hash($method);
  419. }
  420. }