Uploader.class.php 13 KB

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