Uploader.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  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'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
  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. //http开头验证
  160. if (strpos($imgUrl, "http") !== 0) {
  161. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  162. return;
  163. }
  164. //获取请求头并检测死链
  165. $heads = get_headers($imgUrl);
  166. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  167. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  168. return;
  169. }
  170. //格式验证(扩展名验证和Content-Type验证)
  171. $tempImgUrl = explode("?",$imgUrl);
  172. $fileType = strtolower(strrchr($tempImgUrl[0], '.'));
  173. if (!in_array($fileType, $this->config['allowFiles']) || stristr($heads['Content-Type'], "image")) {
  174. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  175. return;
  176. }
  177. //打开输出缓冲区并获取远程图片
  178. ob_start();
  179. $context = stream_context_create(
  180. array('http' => array(
  181. 'follow_location' => false // don't follow redirects
  182. ))
  183. );
  184. readfile($imgUrl, false, $context);
  185. $img = ob_get_contents();
  186. ob_end_clean();
  187. preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
  188. $this->oriName = $m ? $m[1]:"";
  189. $this->fileSize = strlen($img);
  190. $this->fileType = $this->getFileExt();
  191. $this->fullName = $this->getFullName();
  192. $this->filePath = $this->getFilePath();
  193. $this->fileName = $this->getFileName();
  194. $dirname = dirname($this->filePath);
  195. //检查文件大小是否超出限制
  196. if (!$this->checkSize()) {
  197. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  198. return;
  199. }
  200. //创建目录失败
  201. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  202. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  203. return;
  204. } else if (!is_writeable($dirname)) {
  205. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  206. return;
  207. }
  208. //移动文件
  209. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  210. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  211. } else { //移动成功
  212. $this->stateInfo = $this->stateMap[0];
  213. }
  214. }
  215. /**
  216. * 上传错误检查
  217. * @param $errCode
  218. * @return string
  219. */
  220. private function getStateInfo($errCode)
  221. {
  222. return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
  223. }
  224. /**
  225. * 获取文件扩展名
  226. * @return string
  227. */
  228. private function getFileExt()
  229. {
  230. return strtolower(strrchr($this->oriName, '.'));
  231. }
  232. /**
  233. * 重命名文件
  234. * @return string
  235. */
  236. private function getFullName()
  237. {
  238. //替换日期事件
  239. $t = time();
  240. $d = explode('-', date("Y-y-m-d-H-i-s"));
  241. $format = $this->config["pathFormat"];
  242. $format = str_replace("{yyyy}", $d[0], $format);
  243. $format = str_replace("{yy}", $d[1], $format);
  244. $format = str_replace("{mm}", $d[2], $format);
  245. $format = str_replace("{dd}", $d[3], $format);
  246. $format = str_replace("{hh}", $d[4], $format);
  247. $format = str_replace("{ii}", $d[5], $format);
  248. $format = str_replace("{ss}", $d[6], $format);
  249. $format = str_replace("{time}", $t, $format);
  250. //过滤文件名的非法自负,并替换文件名
  251. $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
  252. $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
  253. $format = str_replace("{filename}", $oriName, $format);
  254. //替换随机字符串
  255. $randNum = rand(1, 10000000000) . rand(1, 10000000000);
  256. if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
  257. $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
  258. }
  259. $ext = $this->getFileExt();
  260. return $format . $ext;
  261. }
  262. /**
  263. * 获取文件名
  264. * @return string
  265. */
  266. private function getFileName () {
  267. return substr($this->filePath, strrpos($this->filePath, '/') + 1);
  268. }
  269. /**
  270. * 获取文件完整路径
  271. * @return string
  272. */
  273. private function getFilePath()
  274. {
  275. $fullname = $this->fullName;
  276. $rootPath = rtrim(str_replace('upload'.DIRECTORY_SEPARATOR,'',UPLOAD_PATH),DIRECTORY_SEPARATOR);//$_SERVER['DOCUMENT_ROOT'];
  277. if (substr($fullname, 0, 1) != '/') {
  278. $fullname = '/' . $fullname;
  279. }
  280. return $rootPath . $fullname;
  281. }
  282. /**
  283. * 文件类型检测
  284. * @return bool
  285. */
  286. private function checkType()
  287. {
  288. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  289. }
  290. /**
  291. * 文件大小检测
  292. * @return bool
  293. */
  294. private function checkSize()
  295. {
  296. return $this->fileSize <= ($this->config["maxSize"]);
  297. }
  298. /**
  299. * 获取当前上传成功文件的各项信息
  300. * @return array
  301. */
  302. public function getFileInfo()
  303. {
  304. return array(
  305. "state" => $this->stateInfo,
  306. "url" => UPLOAD_DOMAIN.ltrim($this->fullName,'/'),
  307. "title" => $this->fileName,
  308. "original" => $this->oriName,
  309. "type" => $this->fileType,
  310. "size" => $this->fileSize
  311. );
  312. }
  313. }