Uploader.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. /**
  3. * Created by JetBrains PhpStorm.
  4. * User: taoqili
  5. * Date: 12-7-18
  6. * Time: 上午11: 32
  7. * UEditor编辑器通用上传类
  8. */
  9. class Uploader
  10. {
  11. private $fileField; //文件域名
  12. private $file; //文件上传对象
  13. private $base64; //文件上传对象
  14. private $config; //配置信息
  15. private $oriName; //原始文件名
  16. private $fileName; //新文件名
  17. private $fullName; //完整文件名,即从当前配置目录开始的URL
  18. private $filePath; //完整文件名,即从当前配置目录开始的URL
  19. private $fileSize; //文件大小
  20. private $fileType; //文件类型
  21. private $stateInfo; //上传状态信息,
  22. private $stateMap = array( //上传状态映射表,国际化用户需考虑此处数据的国际化
  23. "SUCCESS", //上传成功标记,在UEditor中内不可改变,否则flash判断会出错
  24. "文件大小超出 upload_max_filesize 限制",
  25. "文件大小超出 MAX_FILE_SIZE 限制",
  26. "文件未被完整上传",
  27. "没有文件被上传",
  28. "上传文件为空",
  29. "ERROR_TMP_FILE" => "临时文件错误",
  30. "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
  31. "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
  32. "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
  33. "ERROR_CREATE_DIR" => "目录创建失败",
  34. "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
  35. "ERROR_FILE_MOVE" => "文件保存时出错",
  36. "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
  37. "ERROR_WRITE_CONTENT" => "写入文件内容错误",
  38. "ERROR_UNKNOWN" => "未知错误",
  39. "ERROR_DEAD_LINK" => "链接不可用",
  40. "ERROR_HTTP_LINK" => "链接不是http链接",
  41. "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确"
  42. );
  43. /**
  44. * 构造函数
  45. * @param string $fileField 表单名称
  46. * @param array $config 配置项
  47. * @param string $type 处理文件上传的方式
  48. */
  49. public function __construct($fileField, $config, $type = "upload")
  50. {
  51. $this->fileField = $fileField;
  52. $this->config = $config;
  53. $this->type = $type;
  54. if ($type == "remote") {
  55. $this->saveRemote();
  56. } else if($type == "base64") {
  57. $this->upBase64();
  58. } else {
  59. $this->upFile();
  60. }
  61. $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = mb_convert_encoding($this->stateMap['ERROR_TYPE_NOT_ALLOWED'], 'utf-8', 'auto');
  62. }
  63. /**
  64. * 上传文件的主处理方法
  65. * @return mixed
  66. */
  67. private function upFile()
  68. {
  69. $file = $this->file = $_FILES[$this->fileField];
  70. if (!$file) {
  71. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  72. return;
  73. }
  74. if ($this->file['error']) {
  75. $this->stateInfo = $this->getStateInfo($file['error']);
  76. return;
  77. } else if (!file_exists($file['tmp_name'])) {
  78. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  79. return;
  80. } else if (!is_uploaded_file($file['tmp_name'])) {
  81. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  82. return;
  83. }
  84. $this->oriName = $file['name'];
  85. $this->fileSize = $file['size'];
  86. $this->fileType = $this->getFileExt();
  87. $this->fullName = $this->getFullName();
  88. $this->filePath = $this->getFilePath();
  89. $this->fileName = $this->getFileName();
  90. $dirname = dirname($this->filePath);
  91. //检查文件大小是否超出限制
  92. if (!$this->checkSize()) {
  93. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  94. return;
  95. }
  96. //检查是否不允许的文件格式
  97. if (!$this->checkType()) {
  98. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  99. return;
  100. }
  101. //创建目录失败
  102. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  103. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  104. return;
  105. } else if (!is_writeable($dirname)) {
  106. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  107. return;
  108. }
  109. //移动文件
  110. if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  111. $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  112. } else { //移动成功
  113. $this->stateInfo = $this->stateMap[0];
  114. }
  115. }
  116. /**
  117. * 处理base64编码的图片上传
  118. * @return mixed
  119. */
  120. private function upBase64()
  121. {
  122. $base64Data = $_POST[$this->fileField];
  123. $img = base64_decode($base64Data);
  124. $this->oriName = $this->config['oriName'];
  125. $this->fileSize = strlen($img);
  126. $this->fileType = $this->getFileExt();
  127. $this->fullName = $this->getFullName();
  128. $this->filePath = $this->getFilePath();
  129. $this->fileName = $this->getFileName();
  130. $dirname = dirname($this->filePath);
  131. //检查文件大小是否超出限制
  132. if (!$this->checkSize()) {
  133. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  134. return;
  135. }
  136. //创建目录失败
  137. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  138. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  139. return;
  140. } else if (!is_writeable($dirname)) {
  141. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  142. return;
  143. }
  144. //移动文件
  145. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  146. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  147. } else { //移动成功
  148. $this->stateInfo = $this->stateMap[0];
  149. }
  150. }
  151. /**
  152. * 拉取远程图片
  153. * @return mixed
  154. */
  155. private function saveRemote()
  156. {
  157. $imgUrl = htmlspecialchars($this->fileField);
  158. $imgUrl = str_replace("&amp;", "&", $imgUrl);
  159. //获取带有GET参数的真实图片url路径
  160. $pathRes = parse_url($imgUrl);
  161. $queryString = isset($pathRes['query']) ? $pathRes['query'] : '';
  162. $imgUrl = str_replace('?' . $queryString, '', $imgUrl);
  163. //http开头验证
  164. if (strpos($imgUrl, "http") !== 0) {
  165. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  166. return;
  167. }
  168. //获取请求头并检测死链
  169. $heads = get_headers($imgUrl, 1);
  170. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  171. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  172. return;
  173. }
  174. //格式验证(扩展名验证和Content-Type验证)
  175. $fileType = strtolower(strrchr($imgUrl, '.'));
  176. if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
  177. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  178. return;
  179. }
  180. //打开输出缓冲区并获取远程图片
  181. ob_start();
  182. $context = stream_context_create(
  183. array('http' => array(
  184. 'follow_location' => false // don't follow redirects
  185. ))
  186. );
  187. readfile($imgUrl . '?' . $queryString, false, $context);
  188. $img = ob_get_contents();
  189. ob_end_clean();
  190. preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
  191. $this->oriName = $m ? $m[1]:"";
  192. $this->fileSize = strlen($img);
  193. $this->fileType = $this->getFileExt();
  194. $this->fullName = $this->getFullName();
  195. $this->filePath = $this->getFilePath();
  196. $this->fileName = $this->getFileName();
  197. $dirname = dirname($this->filePath);
  198. //检查文件大小是否超出限制
  199. if (!$this->checkSize()) {
  200. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  201. return;
  202. }
  203. //检查文件内容是否真的是图片
  204. if (substr(mime_content_type($this->filePath), 0, 5) != 'image') {
  205. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  206. return;
  207. }
  208. //创建目录失败
  209. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  210. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  211. return;
  212. } else if (!is_writeable($dirname)) {
  213. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  214. return;
  215. }
  216. //移动文件
  217. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  218. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  219. } else { //移动成功
  220. $this->stateInfo = $this->stateMap[0];
  221. }
  222. }
  223. /**
  224. * 上传错误检查
  225. * @param $errCode
  226. * @return string
  227. */
  228. private function getStateInfo($errCode)
  229. {
  230. return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
  231. }
  232. /**
  233. * 获取文件扩展名
  234. * @return string
  235. */
  236. private function getFileExt()
  237. {
  238. return strtolower(strrchr($this->oriName, '.'));
  239. }
  240. /**
  241. * 重命名文件
  242. * @return string
  243. */
  244. private function getFullName()
  245. {
  246. //替换日期事件
  247. $t = time();
  248. $d = explode('-', date("Y-y-m-d-H-i-s"));
  249. $format = $this->config["pathFormat"];
  250. $format = str_replace("{yyyy}", $d[0], $format);
  251. $format = str_replace("{yy}", $d[1], $format);
  252. $format = str_replace("{mm}", $d[2], $format);
  253. $format = str_replace("{dd}", $d[3], $format);
  254. $format = str_replace("{hh}", $d[4], $format);
  255. $format = str_replace("{ii}", $d[5], $format);
  256. $format = str_replace("{ss}", $d[6], $format);
  257. $format = str_replace("{time}", $t, $format);
  258. //过滤文件名的非法字符,并替换文件名
  259. $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
  260. $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
  261. $format = str_replace("{filename}", $oriName, $format);
  262. //替换随机字符串
  263. $randNum = rand(1, 10000000000) . rand(1, 10000000000);
  264. if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
  265. $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
  266. }
  267. if($this->fileType){
  268. $ext = $this->fileType;
  269. } else {
  270. $ext = $this->getFileExt();
  271. }
  272. return $format . $ext;
  273. }
  274. /**
  275. * 获取文件名
  276. * @return string
  277. */
  278. private function getFileName () {
  279. return substr($this->filePath, strrpos($this->filePath, '/') + 1);
  280. }
  281. /**
  282. * 获取文件完整路径
  283. * @return string
  284. */
  285. private function getFilePath()
  286. {
  287. $fullname = $this->fullName;
  288. $rootPath = $_SERVER['DOCUMENT_ROOT'].substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME'])));
  289. if (substr($fullname, 0, 1) != '/') {
  290. $fullname = '/' . $fullname;
  291. }
  292. return $rootPath . $fullname;
  293. }
  294. /**
  295. * 文件类型检测
  296. * @return bool
  297. */
  298. private function checkType()
  299. {
  300. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  301. }
  302. /**
  303. * 文件大小检测
  304. * @return bool
  305. */
  306. private function checkSize()
  307. {
  308. return $this->fileSize <= ($this->config["maxSize"]);
  309. }
  310. /**
  311. * 获取当前上传成功文件的各项信息
  312. * @return array
  313. */
  314. public function getFileInfo()
  315. {
  316. return array(
  317. "state" => $this->stateInfo,
  318. "url" => $this->fullName,
  319. "title" => $this->fileName,
  320. "original" => $this->oriName,
  321. "type" => $this->fileType,
  322. "size" => $this->fileSize
  323. );
  324. }
  325. }