Uploader.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <?php
  2. namespace My;
  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. "ERROR_IMAGES_HIGHT_PROPORTION" => "高度比例有误",
  46. );
  47. /**
  48. * 构造函数
  49. * @param string $fileField 表单名称
  50. * @param array $config 配置项
  51. * @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  52. */
  53. public function __construct($fileField, $config, $type = "upload")
  54. {
  55. $this->fileField = $fileField;
  56. $this->config = $config;
  57. $this->type = $type;
  58. if ($type == "remote") {
  59. $this->saveRemote();
  60. } else if($type == "base64") {
  61. $this->upBase64();
  62. } else {
  63. $this->upFile();
  64. }
  65. $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
  66. }
  67. /**
  68. * 上传文件的主处理方法
  69. * @return mixed
  70. */
  71. private function upFile()
  72. {
  73. $file = $this->file = $_FILES[$this->fileField];
  74. if (!$file) {
  75. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  76. return;
  77. }
  78. if ($this->file['error']) {
  79. $this->stateInfo = $this->getStateInfo($file['error']);
  80. return;
  81. } else if (!file_exists($file['tmp_name'])) {
  82. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  83. return;
  84. } else if (!is_uploaded_file($file['tmp_name'])) {
  85. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  86. return;
  87. }
  88. // 尺寸比例校验,高度差距上下5个像数
  89. $image_proportion = MyC('common_image_proportion', 0);
  90. if($image_proportion > 0)
  91. {
  92. if(I('get.path_type', 'Other') == 'Article' && I('get.action') == 'uploadimage')
  93. {
  94. $info = getimagesize($file['tmp_name']);
  95. $temp_height = $image_proportion/100*$info[0];
  96. if(($info[1] > $temp_height+5 || $info[1] < $temp_height-5))
  97. {
  98. $this->stateInfo = $this->getStateInfo("ERROR_IMAGES_HIGHT_PROPORTION");
  99. return;
  100. }
  101. }
  102. }
  103. $this->oriName = $file['name'];
  104. $this->fileSize = $file['size'];
  105. $this->fileType = $this->getFileExt();
  106. $this->fullName = $this->getFullName();
  107. $this->filePath = $this->getFilePath();
  108. $this->fileName = $this->getFileName();
  109. $dirname = dirname($this->filePath);
  110. //检查文件大小是否超出限制
  111. if (!$this->checkSize()) {
  112. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  113. return;
  114. }
  115. //检查是否不允许的文件格式
  116. if (!$this->checkType()) {
  117. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  118. return;
  119. }
  120. //创建目录失败
  121. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  122. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  123. return;
  124. } else if (!is_writeable($dirname)) {
  125. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  126. return;
  127. }
  128. //移动文件
  129. if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  130. $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  131. } else { //移动成功
  132. $this->stateInfo = $this->stateMap[0];
  133. }
  134. }
  135. /**
  136. * 处理base64编码的图片上传
  137. * @return mixed
  138. */
  139. private function upBase64()
  140. {
  141. $base64Data = $_POST[$this->fileField];
  142. $img = base64_decode($base64Data);
  143. $this->oriName = $this->config['oriName'];
  144. $this->fileSize = strlen($img);
  145. $this->fileType = $this->getFileExt();
  146. $this->fullName = $this->getFullName();
  147. $this->filePath = $this->getFilePath();
  148. $this->fileName = $this->getFileName();
  149. $dirname = dirname($this->filePath);
  150. //检查文件大小是否超出限制
  151. if (!$this->checkSize()) {
  152. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  153. return;
  154. }
  155. //创建目录失败
  156. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  157. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  158. return;
  159. } else if (!is_writeable($dirname)) {
  160. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  161. return;
  162. }
  163. //移动文件
  164. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  165. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  166. } else { //移动成功
  167. $this->stateInfo = $this->stateMap[0];
  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. }