Uploader.class.php 12 KB

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