0
0

File.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 protected
  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. }
  139. $this->error = ['directory {:path} creation failed', ['path' => $path]];
  140. return false;
  141. }
  142. /**
  143. * 获取文件类型信息
  144. * @access public
  145. * @return string
  146. */
  147. public function getMime()
  148. {
  149. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  150. return finfo_file($finfo, $this->filename);
  151. }
  152. /**
  153. * 设置文件的命名规则
  154. * @access public
  155. * @param string $rule 文件命名规则
  156. * @return $this
  157. */
  158. public function rule($rule)
  159. {
  160. $this->rule = $rule;
  161. return $this;
  162. }
  163. /**
  164. * 设置上传文件的验证规则
  165. * @access public
  166. * @param array $rule 验证规则
  167. * @return $this
  168. */
  169. public function validate($rule = [])
  170. {
  171. $this->validate = $rule;
  172. return $this;
  173. }
  174. /**
  175. * 检测是否合法的上传文件
  176. * @access public
  177. * @return bool
  178. */
  179. public function isValid()
  180. {
  181. if ($this->isTest) {
  182. return is_file($this->filename);
  183. }
  184. return is_uploaded_file($this->filename);
  185. }
  186. /**
  187. * 检测上传文件
  188. * @access public
  189. * @param array $rule 验证规则
  190. * @return bool
  191. */
  192. public function check($rule = [])
  193. {
  194. $rule = $rule ?: $this->validate;
  195. if ((isset($rule['size']) && !$this->checkSize($rule['size']))
  196. || (isset($rule['type']) && !$this->checkMime($rule['type']))
  197. || (isset($rule['ext']) && !$this->checkExt($rule['ext']))
  198. || !$this->checkImg()) {
  199. return false;
  200. }
  201. return true;
  202. }
  203. /**
  204. * 检测上传文件后缀
  205. * @access public
  206. * @param array|string $ext 允许后缀
  207. * @return bool
  208. */
  209. public function checkExt($ext)
  210. {
  211. if (is_string($ext)) {
  212. $ext = explode(',', $ext);
  213. }
  214. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  215. if (!in_array($extension, $ext)) {
  216. $this->error = 'extensions to upload is not allowed';
  217. return false;
  218. }
  219. return true;
  220. }
  221. /**
  222. * 检测图像文件
  223. * @access public
  224. * @return bool
  225. */
  226. public function checkImg()
  227. {
  228. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  229. /* 对图像文件进行严格检测 */
  230. if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6, 13])) {
  231. $this->error = 'illegal image files';
  232. return false;
  233. }
  234. return true;
  235. }
  236. // 判断图像类型
  237. protected function getImageType($image)
  238. {
  239. if (function_exists('exif_imagetype')) {
  240. return exif_imagetype($image);
  241. }
  242. try {
  243. $info = getimagesize($image);
  244. return $info ? $info[2] : false;
  245. } catch (\Exception $e) {
  246. return false;
  247. }
  248. }
  249. /**
  250. * 检测上传文件大小
  251. * @access public
  252. * @param integer $size 最大大小
  253. * @return bool
  254. */
  255. public function checkSize($size)
  256. {
  257. if ($this->getSize() > (int) $size) {
  258. $this->error = 'filesize not match';
  259. return false;
  260. }
  261. return true;
  262. }
  263. /**
  264. * 检测上传文件类型
  265. * @access public
  266. * @param array|string $mime 允许类型
  267. * @return bool
  268. */
  269. public function checkMime($mime)
  270. {
  271. if (is_string($mime)) {
  272. $mime = explode(',', $mime);
  273. }
  274. if (!in_array(strtolower($this->getMime()), $mime)) {
  275. $this->error = 'mimetype to upload is not allowed';
  276. return false;
  277. }
  278. return true;
  279. }
  280. /**
  281. * 移动文件
  282. * @access public
  283. * @param string $path 保存路径
  284. * @param string|bool $savename 保存的文件名 默认自动生成
  285. * @param boolean $replace 同名文件是否覆盖
  286. * @param bool $autoAppendExt 自动补充扩展名
  287. * @return false|File false-失败 否则返回File实例
  288. */
  289. public function move($path, $savename = true, $replace = true, $autoAppendExt = true)
  290. {
  291. // 文件上传失败,捕获错误代码
  292. if (!empty($this->info['error'])) {
  293. $this->error($this->info['error']);
  294. return false;
  295. }
  296. // 检测合法性
  297. if (!$this->isValid()) {
  298. $this->error = 'upload illegal files';
  299. return false;
  300. }
  301. // 验证上传
  302. if (!$this->check()) {
  303. return false;
  304. }
  305. $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
  306. // 文件保存命名规则
  307. $saveName = $this->buildSaveName($savename, $autoAppendExt);
  308. $filename = $path . $saveName;
  309. // 检测目录
  310. if (false === $this->checkPath(dirname($filename))) {
  311. return false;
  312. }
  313. /* 不覆盖同名文件 */
  314. if (!$replace && is_file($filename)) {
  315. $this->error = ['has the same filename: {:filename}', ['filename' => $filename]];
  316. return false;
  317. }
  318. /* 移动文件 */
  319. if ($this->isTest) {
  320. rename($this->filename, $filename);
  321. } elseif (!move_uploaded_file($this->filename, $filename)) {
  322. $this->error = 'upload write error';
  323. return false;
  324. }
  325. // 返回 File对象实例
  326. $file = new self($filename);
  327. $file->setSaveName($saveName);
  328. $file->setUploadInfo($this->info);
  329. return $file;
  330. }
  331. /**
  332. * 获取保存文件名
  333. * @access protected
  334. * @param string|bool $savename 保存的文件名 默认自动生成
  335. * @param bool $autoAppendExt 自动补充扩展名
  336. * @return string
  337. */
  338. protected function buildSaveName($savename, $autoAppendExt = true)
  339. {
  340. if (true === $savename) {
  341. // 自动生成文件名
  342. $savename = $this->autoBuildName();
  343. } elseif ('' === $savename || false === $savename) {
  344. // 保留原文件名
  345. $savename = $this->getInfo('name');
  346. }
  347. if ($autoAppendExt && false === strpos($savename, '.')) {
  348. $savename .= '.' . pathinfo($this->getInfo('name'), PATHINFO_EXTENSION);
  349. }
  350. return $savename;
  351. }
  352. /**
  353. * 自动生成文件名
  354. * @access protected
  355. * @return string
  356. */
  357. protected function autoBuildName()
  358. {
  359. if ($this->rule instanceof \Closure) {
  360. $savename = call_user_func_array($this->rule, [$this]);
  361. } else {
  362. switch ($this->rule) {
  363. case 'date':
  364. $savename = date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true));
  365. break;
  366. default:
  367. if (in_array($this->rule, hash_algos())) {
  368. $hash = $this->hash($this->rule);
  369. $savename = substr($hash, 0, 2) . DIRECTORY_SEPARATOR . substr($hash, 2);
  370. } elseif (is_callable($this->rule)) {
  371. $savename = call_user_func($this->rule);
  372. } else {
  373. $savename = date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true));
  374. }
  375. }
  376. }
  377. return $savename;
  378. }
  379. /**
  380. * 获取错误代码信息
  381. * @access private
  382. * @param int $errorNo 错误号
  383. */
  384. private function error($errorNo)
  385. {
  386. switch ($errorNo) {
  387. case 1:
  388. case 2:
  389. $this->error = 'upload File size exceeds the maximum value';
  390. break;
  391. case 3:
  392. $this->error = 'only the portion of file is uploaded';
  393. break;
  394. case 4:
  395. $this->error = 'no file to uploaded';
  396. break;
  397. case 6:
  398. $this->error = 'upload temp dir not found';
  399. break;
  400. case 7:
  401. $this->error = 'file write error';
  402. break;
  403. default:
  404. $this->error = 'unknown upload error';
  405. }
  406. }
  407. /**
  408. * 获取错误信息(支持多语言)
  409. * @access public
  410. * @return string
  411. */
  412. public function getError()
  413. {
  414. $lang = Container::get('lang');
  415. if (is_array($this->error)) {
  416. list($msg, $vars) = $this->error;
  417. } else {
  418. $msg = $this->error;
  419. $vars = [];
  420. }
  421. return $lang->has($msg) ? $lang->get($msg, $vars) : $msg;
  422. }
  423. public function __call($method, $args)
  424. {
  425. return $this->hash($method);
  426. }
  427. }