File.php 12 KB

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