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.

371 lines
12 KiB

8 years ago
  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. "INVALID_URL" => "非法 URL",
  43. "INVALID_IP" => "非法 IP"
  44. );
  45. /**
  46. * 构造函数
  47. * @param string $fileField 表单名称
  48. * @param array $config 配置项
  49. * @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  50. */
  51. public function __construct($fileField, $config, $type = "upload")
  52. {
  53. $this->fileField = $fileField;
  54. $this->config = $config;
  55. $this->type = $type;
  56. if ($type == "remote") {
  57. $this->saveRemote();
  58. } else if($type == "base64") {
  59. $this->upBase64();
  60. } else {
  61. $this->upFile();
  62. }
  63. $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
  64. }
  65. /**
  66. * 上传文件的主处理方法
  67. * @return mixed
  68. */
  69. private function upFile()
  70. {
  71. $file = $this->file = $_FILES[$this->fileField];
  72. if (!$file) {
  73. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  74. return;
  75. }
  76. if ($this->file['error']) {
  77. $this->stateInfo = $this->getStateInfo($file['error']);
  78. return;
  79. } else if (!file_exists($file['tmp_name'])) {
  80. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  81. return;
  82. } else if (!is_uploaded_file($file['tmp_name'])) {
  83. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  84. return;
  85. }
  86. $this->oriName = $file['name'];
  87. $this->fileSize = $file['size'];
  88. $this->fileType = $this->getFileExt();
  89. $this->fullName = $this->getFullName();
  90. $this->filePath = $this->getFilePath();
  91. $this->fileName = $this->getFileName();
  92. $dirname = dirname($this->filePath);
  93. //检查文件大小是否超出限制
  94. if (!$this->checkSize()) {
  95. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  96. return;
  97. }
  98. //检查是否不允许的文件格式
  99. if (!$this->checkType()) {
  100. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  101. return;
  102. }
  103. //创建目录失败
  104. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  105. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  106. return;
  107. } else if (!is_writeable($dirname)) {
  108. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  109. return;
  110. }
  111. //移动文件
  112. if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  113. $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  114. } else { //移动成功
  115. $this->stateInfo = $this->stateMap[0];
  116. }
  117. }
  118. /**
  119. * 处理base64编码的图片上传
  120. * @return mixed
  121. */
  122. private function upBase64()
  123. {
  124. $base64Data = $_POST[$this->fileField];
  125. $img = base64_decode($base64Data);
  126. $this->oriName = $this->config['oriName'];
  127. $this->fileSize = strlen($img);
  128. $this->fileType = $this->getFileExt();
  129. $this->fullName = $this->getFullName();
  130. $this->filePath = $this->getFilePath();
  131. $this->fileName = $this->getFileName();
  132. $dirname = dirname($this->filePath);
  133. //检查文件大小是否超出限制
  134. if (!$this->checkSize()) {
  135. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  136. return;
  137. }
  138. //创建目录失败
  139. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  140. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  141. return;
  142. } else if (!is_writeable($dirname)) {
  143. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  144. return;
  145. }
  146. //移动文件
  147. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  148. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  149. } else { //移动成功
  150. $this->stateInfo = $this->stateMap[0];
  151. }
  152. }
  153. /**
  154. * 拉取远程图片
  155. * @return mixed
  156. */
  157. private function saveRemote()
  158. {
  159. $imgUrl = htmlspecialchars($this->fileField);
  160. $imgUrl = str_replace("&amp;", "&", $imgUrl);
  161. //http开头验证
  162. if (strpos($imgUrl, "http") !== 0) {
  163. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  164. return;
  165. }
  166. preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
  167. $host_with_protocol = count($matches) > 1 ? $matches[1] : '';
  168. // 判断是否是合法 url
  169. if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
  170. $this->stateInfo = $this->getStateInfo("INVALID_URL");
  171. return;
  172. }
  173. preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
  174. $host_without_protocol = count($matches) > 1 ? $matches[1] : '';
  175. // 此时提取出来的可能是 ip 也有可能是域名,先获取 ip
  176. $ip = gethostbyname($host_without_protocol);
  177. // 判断是否是私有 ip
  178. if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
  179. $this->stateInfo = $this->getStateInfo("INVALID_IP");
  180. return;
  181. }
  182. //获取请求头并检测死链
  183. $heads = get_headers($imgUrl, 1);
  184. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  185. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  186. return;
  187. }
  188. //格式验证(扩展名验证和Content-Type验证)
  189. $fileType = strtolower(strrchr($imgUrl, '.'));
  190. if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
  191. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  192. return;
  193. }
  194. //打开输出缓冲区并获取远程图片
  195. ob_start();
  196. $context = stream_context_create(
  197. array('http' => array(
  198. 'follow_location' => false // don't follow redirects
  199. ))
  200. );
  201. readfile($imgUrl, false, $context);
  202. $img = ob_get_contents();
  203. ob_end_clean();
  204. preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
  205. $this->oriName = $m ? $m[1]:"";
  206. $this->fileSize = strlen($img);
  207. $this->fileType = $this->getFileExt();
  208. $this->fullName = $this->getFullName();
  209. $this->filePath = $this->getFilePath();
  210. $this->fileName = $this->getFileName();
  211. $dirname = dirname($this->filePath);
  212. //检查文件大小是否超出限制
  213. if (!$this->checkSize()) {
  214. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  215. return;
  216. }
  217. //创建目录失败
  218. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  219. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  220. return;
  221. } else if (!is_writeable($dirname)) {
  222. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  223. return;
  224. }
  225. //移动文件
  226. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  227. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  228. } else { //移动成功
  229. $this->stateInfo = $this->stateMap[0];
  230. }
  231. }
  232. /**
  233. * 上传错误检查
  234. * @param $errCode
  235. * @return string
  236. */
  237. private function getStateInfo($errCode)
  238. {
  239. return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
  240. }
  241. /**
  242. * 获取文件扩展名
  243. * @return string
  244. */
  245. private function getFileExt()
  246. {
  247. return strtolower(strrchr($this->oriName, '.'));
  248. }
  249. /**
  250. * 重命名文件
  251. * @return string
  252. */
  253. private function getFullName()
  254. {
  255. //替换日期事件
  256. $t = time();
  257. $d = explode('-', date("Y-y-m-d-H-i-s"));
  258. $format = $this->config["pathFormat"];
  259. $format = str_replace("{yyyy}", $d[0], $format);
  260. $format = str_replace("{yy}", $d[1], $format);
  261. $format = str_replace("{mm}", $d[2], $format);
  262. $format = str_replace("{dd}", $d[3], $format);
  263. $format = str_replace("{hh}", $d[4], $format);
  264. $format = str_replace("{ii}", $d[5], $format);
  265. $format = str_replace("{ss}", $d[6], $format);
  266. $format = str_replace("{time}", $t, $format);
  267. //过滤文件名的非法自负,并替换文件名
  268. $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
  269. $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
  270. $format = str_replace("{filename}", $oriName, $format);
  271. //替换随机字符串
  272. $randNum = rand(1, 10000000000) . rand(1, 10000000000);
  273. if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
  274. $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
  275. }
  276. $ext = $this->getFileExt();
  277. return $format . $ext;
  278. }
  279. /**
  280. * 获取文件名
  281. * @return string
  282. */
  283. private function getFileName () {
  284. return substr($this->filePath, strrpos($this->filePath, '/') + 1);
  285. }
  286. /**
  287. * 获取文件完整路径
  288. * @return string
  289. */
  290. private function getFilePath()
  291. {
  292. $fullname = $this->fullName;
  293. $rootPath = $_SERVER['DOCUMENT_ROOT'];
  294. if (substr($fullname, 0, 1) != '/') {
  295. $fullname = '/' . $fullname;
  296. }
  297. return $rootPath . $fullname;
  298. }
  299. /**
  300. * 文件类型检测
  301. * @return bool
  302. */
  303. private function checkType()
  304. {
  305. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  306. }
  307. /**
  308. * 文件大小检测
  309. * @return bool
  310. */
  311. private function checkSize()
  312. {
  313. return $this->fileSize <= ($this->config["maxSize"]);
  314. }
  315. /**
  316. * 获取当前上传成功文件的各项信息
  317. * @return array
  318. */
  319. public function getFileInfo()
  320. {
  321. return array(
  322. "state" => $this->stateInfo,
  323. "url" => $this->fullName,
  324. "title" => $this->fileName,
  325. "original" => $this->oriName,
  326. "type" => $this->fileType,
  327. "size" => $this->fileSize
  328. );
  329. }
  330. }