Uploader.class.php 11 KB

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