UeditorUploadController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <?php
  2. namespace App\Admin\Controllers;
  3. use App\Lib\Uploads\UploadHandler;
  4. use App\Wen\Utils\ImageUtils;
  5. use Dcat\Admin\Traits\HasUploadedFile;
  6. use Illuminate\Http\Request;
  7. use App\Http\Controllers\Controller;
  8. class UeditorUploadController extends Controller{
  9. use HasUploadedFile;
  10. private $fileField; //文件域名
  11. private $file; //文件上传对象
  12. private $base64; //文件上传对象
  13. private $config; //配置信息
  14. private $oriName; //原始文件名
  15. private $fileName; //新文件名
  16. private $fullName; //完整文件名,即从当前配置目录开始的URL
  17. private $filePath; //完整文件名,即从当前配置目录开始的URL
  18. private $fileSize; //文件大小
  19. private $fileType; //文件类型
  20. private $stateInfo; //上传状态信息,
  21. private $stateMap = array( //上传状态映射表,国际化用户需考虑此处数据的国际化
  22. "SUCCESS", //上传成功标记,在UEditor中内不可改变,否则flash判断会出错
  23. "文件大小超出 upload_max_filesize 限制",
  24. "文件大小超出 MAX_FILE_SIZE 限制",
  25. "文件未被完整上传",
  26. "没有文件被上传",
  27. "上传文件为空",
  28. "ERROR_TMP_FILE" => "临时文件错误",
  29. "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
  30. "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
  31. "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
  32. "ERROR_CREATE_DIR" => "目录创建失败",
  33. "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
  34. "ERROR_FILE_MOVE" => "文件保存时出错",
  35. "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
  36. "ERROR_WRITE_CONTENT" => "写入文件内容错误",
  37. "ERROR_UNKNOWN" => "未知错误",
  38. "ERROR_DEAD_LINK" => "链接不可用",
  39. "ERROR_HTTP_LINK" => "链接不是http链接",
  40. "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确",
  41. "INVALID_URL" => "非法 URL",
  42. "INVALID_IP" => "非法 IP"
  43. );
  44. /**
  45. * 构造函数
  46. * @param string $fileField 表单名称
  47. * @param array $config 配置项
  48. * @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  49. */
  50. public function init($fileField, $config, $type = "upload", $request = null)
  51. {
  52. $this->fileField = $fileField;
  53. $this->config = $config;
  54. $this->type = $type;
  55. if ($type == "remote") {
  56. $this->saveRemote($request);
  57. } else if($type == "base64") {
  58. $this->upBase64($request);
  59. } else {
  60. $this->upFile($request);
  61. }
  62. }
  63. public function handler(Request $request){
  64. $action = htmlspecialchars($request->action);
  65. $callback = $request->callback;
  66. if(_empty_($action)){
  67. return array(
  68. 'state'=> 'callback参数不合法'
  69. );
  70. }
  71. $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(app_path('Lib/Ueditor/config.json'))), true);
  72. switch ($action) {
  73. case 'config':
  74. $result = $CONFIG;
  75. break;
  76. /* 上传图片 */
  77. case 'uploadimage':
  78. /* 上传涂鸦 */
  79. case 'uploadscrawl':
  80. /* 上传视频 */
  81. case 'uploadvideo':
  82. /* 上传文件 */
  83. case 'uploadfile':
  84. $result = $this->action_upload($action, $CONFIG, $request);
  85. break;
  86. /* 列出图片 */
  87. case 'listimage':
  88. $result = $this->action_list($action, $CONFIG, $request);
  89. break;
  90. /* 列出文件 */
  91. case 'listfile':
  92. $result = $this->action_list($action, $CONFIG, $request);
  93. break;
  94. /* 抓取远程文件 */
  95. case 'catchimage':
  96. $result = $this->action_crawler($action, $CONFIG, $request);
  97. break;
  98. default:
  99. $result = array(
  100. 'state'=> '请求地址出错'
  101. );
  102. break;
  103. }
  104. /* 输出结果 */
  105. if ($callback) {
  106. if (preg_match("/^[\w_]+$/", $callback)) {
  107. return response( htmlspecialchars($callback) . '(' . json_encode($result). ')', 200)->withHeaders(['Content-Type' => 'text/html; charset=utf-8']);
  108. } else {
  109. return response(json_encode(array(
  110. 'state'=> 'callback参数不合法'
  111. )), 200)->withHeaders(['Content-Type' => 'text/html; charset=utf-8']);
  112. }
  113. } else {
  114. return response(json_encode($result), 200)->withHeaders(['Content-Type' => 'text/html; charset=utf-8']);
  115. }
  116. }
  117. private function action_list($action, $CONFIG, $request)
  118. {
  119. /* 判断类型 */
  120. switch ($action) {
  121. /* 列出文件 */
  122. case 'listfile':
  123. $allowFiles = $CONFIG['fileManagerAllowFiles'];
  124. $listSize = $CONFIG['fileManagerListSize'];
  125. $path = $CONFIG['fileManagerListPath'];
  126. break;
  127. /* 列出图片 */
  128. case 'listimage':
  129. default:
  130. $allowFiles = $CONFIG['imageManagerAllowFiles'];
  131. $listSize = $CONFIG['imageManagerListSize'];
  132. $path = $CONFIG['imageManagerListPath'];
  133. }
  134. $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
  135. /* 获取参数 */
  136. $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
  137. $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
  138. $end = $start + $size;
  139. /* 获取文件列表 */
  140. $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "" : "/") . $path;
  141. $files = $this->getfiles($path, $allowFiles);
  142. if (!count($files)) {
  143. return array(
  144. "state" => "no match file",
  145. "list" => array(),
  146. "start" => $start,
  147. "total" => count($files)
  148. );
  149. }
  150. /* 获取指定范围的列表 */
  151. $len = count($files);
  152. for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
  153. $list[] = $files[$i];
  154. }
  155. //倒序
  156. //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
  157. // $list[] = $files[$i];
  158. //}
  159. return array(
  160. "state" => "SUCCESS",
  161. "list" => $list,
  162. "start" => $start,
  163. "total" => count($files)
  164. );
  165. }
  166. /**
  167. * 遍历获取目录下的指定类型的文件
  168. * @param $path
  169. * @param array $files
  170. * @return array
  171. */
  172. private function getfiles($path, $allowFiles, &$files = array())
  173. {
  174. if (!is_dir($path)) return null;
  175. if(substr($path, strlen($path) - 1) != '/') $path .= '/';
  176. $handle = opendir($path);
  177. while (false !== ($file = readdir($handle))) {
  178. if ($file != '.' && $file != '..') {
  179. $path2 = $path . $file;
  180. if (is_dir($path2)) {
  181. getfiles($path2, $allowFiles, $files);
  182. } else {
  183. if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
  184. $files[] = array(
  185. 'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
  186. 'mtime'=> filemtime($path2)
  187. );
  188. }
  189. }
  190. }
  191. }
  192. return $files;
  193. }
  194. private function action_crawler($action, $CONFIG, $request){
  195. /* 上传配置 */
  196. $config = array(
  197. "pathFormat" => $CONFIG['catcherPathFormat'],
  198. "maxSize" => $CONFIG['catcherMaxSize'],
  199. "allowFiles" => $CONFIG['catcherAllowFiles'],
  200. "oriName" => "remote.png"
  201. );
  202. $fieldName = $CONFIG['catcherFieldName'];
  203. /* 抓取远程图片 */
  204. $list = array();
  205. $source = $request->images;
  206. foreach ($source as $imgUrl) {
  207. $this->init($imgUrl, $config, "remote", $request);
  208. $info = $this->getFileInfo();
  209. array_push($list, array(
  210. "state" => $info["state"],
  211. "url" => $info["url"],
  212. "size" => $info["size"],
  213. "title" => htmlspecialchars($info["title"]),
  214. "original" => htmlspecialchars($info["original"]),
  215. "source" => htmlspecialchars($imgUrl)
  216. ));
  217. }
  218. /* 返回抓取数据 */
  219. return array(
  220. 'state'=> count($list) ? 'SUCCESS':'ERROR',
  221. 'responseText' => '',
  222. 'list'=> $list
  223. );
  224. }
  225. private function action_upload($action, $CONFIG, $request){
  226. /* 上传配置 */
  227. $base64 = "upload";
  228. switch ($action) {
  229. case 'uploadimage':
  230. $config = array(
  231. "pathFormat" => $CONFIG['imagePathFormat'],
  232. "maxSize" => $CONFIG['imageMaxSize'],
  233. "allowFiles" => $CONFIG['imageAllowFiles']
  234. );
  235. $fieldName = $CONFIG['imageFieldName'];
  236. break;
  237. case 'uploadscrawl':
  238. $config = array(
  239. "pathFormat" => $CONFIG['scrawlPathFormat'],
  240. "maxSize" => $CONFIG['scrawlMaxSize'],
  241. "allowFiles" => $CONFIG['scrawlAllowFiles'],
  242. "oriName" => "scrawl.png"
  243. );
  244. $fieldName = $CONFIG['scrawlFieldName'];
  245. $base64 = "base64";
  246. break;
  247. case 'uploadvideo':
  248. $config = array(
  249. "pathFormat" => $CONFIG['videoPathFormat'],
  250. "maxSize" => $CONFIG['videoMaxSize'],
  251. "allowFiles" => $CONFIG['videoAllowFiles']
  252. );
  253. $fieldName = $CONFIG['videoFieldName'];
  254. break;
  255. case 'uploadfile':
  256. default:
  257. $config = array(
  258. "pathFormat" => $CONFIG['filePathFormat'],
  259. "maxSize" => $CONFIG['fileMaxSize'],
  260. "allowFiles" => $CONFIG['fileAllowFiles']
  261. );
  262. $fieldName = $CONFIG['fileFieldName'];
  263. break;
  264. }
  265. /* 生成上传实例对象并完成上传 */
  266. $this->init($fieldName, $config, $base64, $request);
  267. return $this->getFileInfo();
  268. }
  269. /**
  270. * 上传文件的主处理方法
  271. * @return mixed
  272. */
  273. private function upFile($request)
  274. {
  275. $file = $this->file();
  276. if(_empty_($file)){
  277. $file = $request->file('file');
  278. }
  279. if (!$file) {
  280. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  281. return;
  282. }
  283. $path = UploadHandler::handle($file);
  284. if($path){
  285. $this->oriName = '';
  286. $this->fileSize = 100;
  287. $this->fileType = '';
  288. $this->fullName = $path['url'];
  289. $this->filePath = $path['path'];
  290. $this->fileName = $path['name'];
  291. $this->stateInfo = $this->stateMap[0];
  292. }else{
  293. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  294. }
  295. }
  296. /**
  297. * 处理base64编码的图片上传
  298. * @return mixed
  299. */
  300. private function upBase64()
  301. {
  302. $base64Data = $_POST[$this->fileField];
  303. $img = base64_decode($base64Data);
  304. $this->oriName = $this->config['oriName'];
  305. $this->fileSize = strlen($img);
  306. $this->fileType = $this->getFileExt();
  307. $this->fullName = $this->getFullName();
  308. $this->filePath = $this->getFilePath();
  309. $this->fileName = $this->getFileName();
  310. $dirname = dirname($this->filePath);
  311. //检查文件大小是否超出限制
  312. if (!$this->checkSize()) {
  313. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  314. return;
  315. }
  316. //创建目录失败
  317. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  318. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  319. return;
  320. } else if (!is_writeable($dirname)) {
  321. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  322. return;
  323. }
  324. //移动文件
  325. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  326. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  327. } else { //移动成功
  328. $this->stateInfo = $this->stateMap[0];
  329. }
  330. }
  331. /**
  332. * 拉取远程图片
  333. * @return mixed
  334. */
  335. private function saveRemote($request)
  336. {
  337. $imgUrl = htmlspecialchars($this->fileField);
  338. $imgUrl = str_replace("&amp;", "&", $imgUrl);
  339. //http开头验证
  340. if (strpos($imgUrl, "http") !== 0) {
  341. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  342. return;
  343. }
  344. preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
  345. $host_with_protocol = count($matches) > 1 ? $matches[1] : '';
  346. // 判断是否是合法 url
  347. if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
  348. $this->stateInfo = $this->getStateInfo("INVALID_URL");
  349. return;
  350. }
  351. preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
  352. $host_without_protocol = count($matches) > 1 ? $matches[1] : '';
  353. // 此时提取出来的可能是 ip 也有可能是域名,先获取 ip
  354. $ip = gethostbyname($host_without_protocol);
  355. // 判断是否是私有 ip
  356. if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
  357. $this->stateInfo = $this->getStateInfo("INVALID_IP");
  358. return;
  359. }
  360. //获取请求头并检测死链
  361. $heads = get_headers($imgUrl, 1);
  362. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  363. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  364. return;
  365. }
  366. //格式验证(扩展名验证和Content-Type验证)
  367. $fileType = strtolower(strrchr($imgUrl, '.'));
  368. if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
  369. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  370. return;
  371. }
  372. $path = ImageUtils::upload_url_img($imgUrl, '', [], [], true, 1, 1, 3);
  373. if($path){
  374. $this->oriName = $imgUrl;
  375. $this->fileSize = 100;
  376. $this->fileType = '';
  377. $this->fullName = $path['url'];
  378. $this->filePath = $path['path'];
  379. $this->fileName = $path['name'];
  380. $this->stateInfo = $this->stateMap[0];
  381. }else{
  382. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  383. }
  384. }
  385. /**
  386. * 上传错误检查
  387. * @param $errCode
  388. * @return string
  389. */
  390. private function getStateInfo($errCode)
  391. {
  392. return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
  393. }
  394. /**
  395. * 获取文件扩展名
  396. * @return string
  397. */
  398. private function getFileExt()
  399. {
  400. return strtolower(strrchr($this->oriName, '.'));
  401. }
  402. /**
  403. * 重命名文件
  404. * @return string
  405. */
  406. private function getFullName()
  407. {
  408. //替换日期事件
  409. $t = time();
  410. $d = explode('-', date("Y-y-m-d-H-i-s"));
  411. $format = $this->config["pathFormat"];
  412. $format = str_replace("{yyyy}", $d[0], $format);
  413. $format = str_replace("{yy}", $d[1], $format);
  414. $format = str_replace("{mm}", $d[2], $format);
  415. $format = str_replace("{dd}", $d[3], $format);
  416. $format = str_replace("{hh}", $d[4], $format);
  417. $format = str_replace("{ii}", $d[5], $format);
  418. $format = str_replace("{ss}", $d[6], $format);
  419. $format = str_replace("{time}", $t, $format);
  420. //过滤文件名的非法自负,并替换文件名
  421. $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
  422. $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
  423. $format = str_replace("{filename}", $oriName, $format);
  424. //替换随机字符串
  425. $randNum = rand(1, 10000000000) . rand(1, 10000000000);
  426. if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
  427. $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
  428. }
  429. $ext = $this->getFileExt();
  430. return $format . $ext;
  431. }
  432. /**
  433. * 获取文件名
  434. * @return string
  435. */
  436. private function getFileName () {
  437. return substr($this->filePath, strrpos($this->filePath, '/') + 1);
  438. }
  439. /**
  440. * 获取文件完整路径
  441. * @return string
  442. */
  443. private function getFilePath()
  444. {
  445. $fullname = $this->fullName;
  446. $rootPath = $_SERVER['DOCUMENT_ROOT'];
  447. if (substr($fullname, 0, 1) != '/') {
  448. $fullname = '/' . $fullname;
  449. }
  450. return $rootPath . $fullname;
  451. }
  452. /**
  453. * 文件类型检测
  454. * @return bool
  455. */
  456. private function checkType()
  457. {
  458. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  459. }
  460. /**
  461. * 文件大小检测
  462. * @return bool
  463. */
  464. private function checkSize()
  465. {
  466. return $this->fileSize <= ($this->config["maxSize"]);
  467. }
  468. /**
  469. * 获取当前上传成功文件的各项信息
  470. * @return array
  471. */
  472. public function getFileInfo()
  473. {
  474. return array(
  475. "state" => $this->stateInfo,
  476. "url" => $this->fullName,
  477. "title" => $this->fileName,
  478. "original" => $this->oriName,
  479. "type" => $this->fileType,
  480. "size" => $this->fileSize
  481. );
  482. }
  483. }