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.

313 lines
12 KiB

  1. <?php
  2. namespace common\widgets\ueditor;
  3. class Uploader
  4. {
  5. private $fileField; //文件域名
  6. private $file; //文件上传对象
  7. private $base64; //文件上传对象
  8. private $config; //配置信息
  9. private $oriName; //原始文件名
  10. private $fileName; //新文件名
  11. private $fullName; //完整文件名,即从当前配置目录开始的URL
  12. private $filePath; //完整文件名,即从当前配置目录开始的URL
  13. private $fileSize; //文件大小
  14. private $fileType; //文件类型
  15. private $stateInfo; //上传状态信息,
  16. private $stateMap = array( //上传状态映射表,国际化用户需考虑此处数据的国际化
  17. "SUCCESS", //上传成功标记,在UEditor中内不可改变,否则flash判断会出错
  18. "文件大小超出 upload_max_filesize 限制",
  19. "文件大小超出 MAX_FILE_SIZE 限制",
  20. "文件未被完整上传",
  21. "没有文件被上传",
  22. "上传文件为空",
  23. "ERROR_TMP_FILE" => "临时文件错误",
  24. "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
  25. "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
  26. "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
  27. "ERROR_CREATE_DIR" => "目录创建失败",
  28. "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
  29. "ERROR_FILE_MOVE" => "文件保存时出错",
  30. "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
  31. "ERROR_WRITE_CONTENT" => "写入文件内容错误",
  32. "ERROR_UNKNOWN" => "未知错误",
  33. "ERROR_DEAD_LINK" => "链接不可用",
  34. "ERROR_HTTP_LINK" => "链接不是http链接",
  35. "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确"
  36. );
  37. /**
  38. * 构造函数
  39. * @param $fileField 表单名称
  40. * @param $config 配置项
  41. * @param string $type 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  42. */
  43. public function __construct($fileField, $config, $type = "upload")
  44. {
  45. $this->fileField = $fileField;
  46. $this->config = $config;
  47. $this->type = $type;
  48. if ($type == "remote") {
  49. $this->saveRemote();
  50. } else if ($type == "base64") {
  51. $this->upBase64();
  52. } else {
  53. $this->upFile();
  54. }
  55. // $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
  56. }
  57. /**
  58. * 上传文件的主处理方法
  59. * @return mixed
  60. */
  61. private function upFile()
  62. {
  63. $file = $this->file = $_FILES[$this->fileField];
  64. if (!$file) {
  65. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  66. return;
  67. }
  68. if ($this->file['error']) {
  69. $this->stateInfo = $this->getStateInfo($file['error']);
  70. return;
  71. } else if (!file_exists($file['tmp_name'])) {
  72. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  73. return;
  74. } else if (!is_uploaded_file($file['tmp_name'])) {
  75. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  76. return;
  77. }
  78. $this->oriName = $file['name'];
  79. $this->fileSize = $file['size'];
  80. $this->fileType = $this->getFileExt();
  81. $this->fullName = $this->getFullName();
  82. $this->filePath = $this->getFilePath();
  83. $this->fileName = $this->getFileName();
  84. $dirname = dirname($this->filePath);
  85. //检查文件大小是否超出限制
  86. if (!$this->checkSize()) {
  87. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  88. return;
  89. }
  90. //检查是否不允许的文件格式
  91. if (!$this->checkType()) {
  92. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  93. return;
  94. }
  95. //创建目录失败
  96. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  97. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  98. return;
  99. } else if (!is_writeable($dirname)) {
  100. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  101. return;
  102. }
  103. //移动文件
  104. if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  105. $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  106. } else { //移动成功
  107. $this->stateInfo = $this->stateMap[0];
  108. }
  109. }
  110. /**
  111. * 处理base64编码的图片上传
  112. * @return mixed
  113. */
  114. private function upBase64()
  115. {
  116. $base64Data = $_POST[$this->fileField];
  117. $img = base64_decode($base64Data);
  118. $this->oriName = $this->config['oriName'];
  119. $this->fileSize = strlen($img);
  120. $this->fileType = $this->getFileExt();
  121. $this->fullName = $this->getFullName();
  122. $this->filePath = $this->getFilePath();
  123. $this->fileName = $this->getFileName();
  124. $dirname = dirname($this->filePath);
  125. //检查文件大小是否超出限制
  126. if (!$this->checkSize()) {
  127. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  128. return;
  129. }
  130. //创建目录失败
  131. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  132. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  133. return;
  134. } else if (!is_writeable($dirname)) {
  135. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  136. return;
  137. }
  138. //移动文件
  139. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  140. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  141. } else { //移动成功
  142. $this->stateInfo = $this->stateMap[0];
  143. }
  144. }
  145. /**
  146. * 拉取远程图片
  147. * @return mixed
  148. */
  149. private function saveRemote()
  150. {
  151. $imgUrl = htmlspecialchars($this->fileField);
  152. $imgUrl = str_replace("&amp;", "&", $imgUrl);
  153. //http开头验证
  154. if (strpos($imgUrl, "http") !== 0) {
  155. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  156. return;
  157. }
  158. //获取请求头并检测死链
  159. $heads = get_headers($imgUrl);
  160. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  161. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  162. return;
  163. }
  164. //格式验证(扩展名验证和Content-Type验证)
  165. $fileType = strtolower(strrchr($imgUrl, '.'));
  166. if (!in_array($fileType, $this->config['allowFiles']) || stristr($heads['Content-Type'], "image")) {
  167. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  168. return;
  169. }
  170. //打开输出缓冲区并获取远程图片
  171. ob_start();
  172. $context = stream_context_create(
  173. array('http' => array(
  174. 'follow_location' => false // don't follow redirects
  175. ))
  176. );
  177. readfile($imgUrl, false, $context);
  178. $img = ob_get_contents();
  179. ob_end_clean();
  180. preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
  181. $this->oriName = $m ? $m[1] : "";
  182. $this->fileSize = strlen($img);
  183. $this->fileType = $this->getFileExt();
  184. $this->fullName = $this->getFullName();
  185. $this->filePath = $this->getFilePath();
  186. $this->fileName = $this->getFileName();
  187. $dirname = dirname($this->filePath);
  188. //检查文件大小是否超出限制
  189. if (!$this->checkSize()) {
  190. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  191. return;
  192. }
  193. //创建目录失败
  194. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  195. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  196. return;
  197. } else if (!is_writeable($dirname)) {
  198. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  199. return;
  200. }
  201. //移动文件
  202. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  203. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  204. } else { //移动成功
  205. $this->stateInfo = $this->stateMap[0];
  206. }
  207. }
  208. /**
  209. * 上传错误检查
  210. * @param $errCode
  211. * @return string
  212. */
  213. private function getStateInfo($errCode)
  214. {
  215. return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
  216. }
  217. /**
  218. * 获取文件扩展名
  219. * @return string
  220. */
  221. private function getFileExt()
  222. {
  223. return strtolower(strrchr($this->oriName, '.'));
  224. }
  225. /**
  226. * 重命名文件
  227. * @return string
  228. */
  229. private function getFullName()
  230. {
  231. //替换日期事件
  232. $t = time();
  233. $d = explode('-', date("Y-y-m-d-H-i-s"));
  234. $format = $this->config["pathFormat"];
  235. $format = str_replace("{yyyy}", $d[0], $format);
  236. $format = str_replace("{yy}", $d[1], $format);
  237. $format = str_replace("{mm}", $d[2], $format);
  238. $format = str_replace("{dd}", $d[3], $format);
  239. $format = str_replace("{hh}", $d[4], $format);
  240. $format = str_replace("{ii}", $d[5], $format);
  241. $format = str_replace("{ss}", $d[6], $format);
  242. $format = str_replace("{time}", $t, $format);
  243. //过滤文件名的非法自负,并替换文件名
  244. $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
  245. $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
  246. $format = str_replace("{filename}", $oriName, $format);
  247. //替换随机字符串
  248. //origin begin
  249. //$randNum = rand(1, 10000000000) . rand(1, 10000000000);
  250. //origin end
  251. //willeny begin
  252. $randNum=rand(1, 9999) . rand(1, 999);
  253. //willeny end
  254. if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
  255. $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
  256. }
  257. $ext = $this->getFileExt();
  258. return $format . $ext;
  259. }
  260. /**
  261. * 获取文件名
  262. * @return string
  263. */
  264. private function getFileName()
  265. {
  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 = isset($this->config['uploadFilePath'])&&!empty($this->config['uploadFilePath'])?$this->config['uploadFilePath']:$_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. }