Uploader.php 13 KB

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