You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

479 rivejä
12 KiB

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