File.php 11 KB

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