b7264d74fede26df0900eadd33924d07f24c24b0.svn-base 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. /**
  3. * Created by JetBrains PhpStorm.
  4. * User: taoqili
  5. * Date: 12-7-18
  6. * Time: 上午11: 32
  7. * UEditor编辑器通用上传类
  8. */
  9. class LocalDriver
  10. {
  11. private $fileField; //文件域名
  12. private $file; //文件上传对象
  13. private $base64; //文件上传对象
  14. private $config; //配置信息
  15. private $oriName; //原始文件名
  16. private $fileName; //新文件名
  17. private $fullName; //完整文件名,即从当前配置目录开始的URL
  18. private $filePath; //完整文件名,即从当前配置目录开始的URL
  19. private $fileSize; //文件大小
  20. private $fileType; //文件类型
  21. private $stateInfo; //上传状态信息,
  22. private $rootPath;
  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. );
  46. /**
  47. * 构造函数
  48. * @param string $fileField 表单名称
  49. * @param array $config 配置项
  50. * @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  51. */
  52. public function __construct($fileField, $config, $type = "upload")
  53. {
  54. $this->fileField = $fileField;
  55. $this->config = $config;
  56. $this->type = $type;
  57. // widuu
  58. $this->rootPath = $config['rootPath'];
  59. if ($type == "remote") {
  60. $this->saveRemote();
  61. } else if($type == "base64") {
  62. $this->upBase64();
  63. } else {
  64. $this->upFile();
  65. }
  66. $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
  67. }
  68. /**
  69. * 上传文件的主处理方法
  70. * @return mixed
  71. */
  72. private function upFile()
  73. {
  74. $file = $this->file = $_FILES[$this->fileField];
  75. if (!$file) {
  76. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  77. return;
  78. }
  79. if ($this->file['error']) {
  80. $this->stateInfo = $this->getStateInfo($file['error']);
  81. return;
  82. } else if (!file_exists($file['tmp_name'])) {
  83. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  84. return;
  85. } else if (!is_uploaded_file($file['tmp_name'])) {
  86. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  87. return;
  88. }
  89. $this->oriName = $file['name'];
  90. $this->fileSize = $file['size'];
  91. $this->fileType = $this->getFileExt();
  92. $this->fullName = $this->getFullName();
  93. $this->filePath = $this->getFilePath();
  94. $this->fileName = $this->getFileName();
  95. $dirname = dirname($this->filePath);
  96. //检查文件大小是否超出限制
  97. if (!$this->checkSize()) {
  98. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  99. return;
  100. }
  101. //检查是否不允许的文件格式
  102. if (!$this->checkType()) {
  103. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  104. return;
  105. }
  106. //创建目录失败
  107. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  108. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  109. return;
  110. } else if (!is_writeable($dirname)) {
  111. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  112. return;
  113. }
  114. //移动文件
  115. if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  116. $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  117. } else { //移动成功
  118. $this->stateInfo = $this->stateMap[0];
  119. }
  120. $isimg = extension_loaded('gd') && preg_match("/\.(jpg|jpeg|gif|png)/i", $this->filePath, $m) && file_exists($this->filePath) && function_exists('imagecreatefrom'.($m[1] == 'jpg' ? 'jpeg' : $m[1]));
  121. if ($isimg) {
  122. $configsys = include('../../../config/extra/sys.php');
  123. //添加水印操作
  124. if ($configsys['image_watermark']) {
  125. include "../../../app/extend/Image/image/Exception.php";
  126. include "../../../app/extend/Image/image/gif/Decoder.php";
  127. include "../../../app/extend/Image/image/gif/Encoder.php";
  128. include "../../../app/extend/Image/image/gif/Gif.php";
  129. include "../../../app/extend/Image/Image.php";
  130. $image = \Image\Image::open($this->filePath);
  131. if ($configsys['image_watermark'] == 1) {
  132. $font = "../../..".$configsys['image_watermark_text_font'];
  133. if (is_file($font)) {
  134. $image->text($configsys['image_watermark_text'], $font, $configsys['image_watermark_text_size'], "#".$configsys['image_watermark_text_color'],$configsys['image_watermark_pos'],0,$configsys['image_watermark_text_angle'])
  135. ->save($this->filePath);
  136. }
  137. }else{
  138. if (!strpos($configsys['image_watermark_pic'], 'http')) {
  139. $configsys['image_watermark_pic'] = "../../..".$configsys['image_watermark_pic'];
  140. }
  141. if (is_file($configsys['image_watermark_pic'])) {
  142. $image->water($configsys['image_watermark_pic'], $configsys['image_watermark_pos'], $configsys['image_watermark_pic_opacity'])
  143. ->save($this->filePath);
  144. }
  145. }
  146. }
  147. }
  148. }
  149. /**
  150. * 处理base64编码的图片上传
  151. * @return mixed
  152. */
  153. private function upBase64()
  154. {
  155. $base64Data = $_POST[$this->fileField];
  156. $img = base64_decode($base64Data);
  157. $this->oriName = $this->config['oriName'];
  158. $this->fileSize = strlen($img);
  159. $this->fileType = $this->getFileExt();
  160. $this->fullName = $this->getFullName();
  161. $this->filePath = $this->getFilePath();
  162. $this->fileName = $this->getFileName();
  163. $dirname = dirname($this->filePath);
  164. //检查文件大小是否超出限制
  165. if (!$this->checkSize()) {
  166. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  167. return;
  168. }
  169. //创建目录失败
  170. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  171. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  172. return;
  173. } else if (!is_writeable($dirname)) {
  174. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  175. return;
  176. }
  177. //移动文件
  178. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  179. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  180. } else { //移动成功
  181. $this->stateInfo = $this->stateMap[0];
  182. }
  183. }
  184. /**
  185. * 拉取远程图片
  186. * @return mixed
  187. */
  188. private function saveRemote()
  189. {
  190. $imgUrl = htmlspecialchars($this->fileField);
  191. $imgUrl = str_replace("&amp;", "&", $imgUrl);
  192. //http开头验证
  193. if (strpos($imgUrl, "http") !== 0) {
  194. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  195. return;
  196. }
  197. preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
  198. $host_with_protocol = count($matches) > 1 ? $matches[1] : '';
  199. // 判断是否是合法 url
  200. if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
  201. $this->stateInfo = $this->getStateInfo("INVALID_URL");
  202. return;
  203. }
  204. preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
  205. $host_without_protocol = count($matches) > 1 ? $matches[1] : '';
  206. // 此时提取出来的可能是 ip 也有可能是域名,先获取 ip
  207. $ip = gethostbyname($host_without_protocol);
  208. // 判断是否是私有 ip
  209. if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
  210. $this->stateInfo = $this->getStateInfo("INVALID_IP");
  211. return;
  212. }
  213. //获取请求头并检测死链
  214. $heads = get_headers($imgUrl, 1);
  215. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  216. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  217. return;
  218. }
  219. //格式验证(扩展名验证和Content-Type验证)
  220. $fileType = strtolower(strrchr($imgUrl, '.'));
  221. if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
  222. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  223. return;
  224. }
  225. //打开输出缓冲区并获取远程图片
  226. ob_start();
  227. $context = stream_context_create(
  228. array('http' => array(
  229. 'follow_location' => false // don't follow redirects
  230. ))
  231. );
  232. readfile($imgUrl, false, $context);
  233. $img = ob_get_contents();
  234. ob_end_clean();
  235. preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
  236. $this->oriName = $m ? $m[1]:"";
  237. $this->fileSize = strlen($img);
  238. $this->fileType = $this->getFileExt();
  239. $this->fullName = $this->getFullName();
  240. $this->filePath = $this->getFilePath();
  241. $this->fileName = $this->getFileName();
  242. $dirname = dirname($this->filePath);
  243. $mainfilepath = str_replace(DS."statics".DS."ueditor".DS."php".DS."vendor".DS."driver".DS."LocalDriver.class.php", '', __FILE__);
  244. //检查文件大小是否超出限制
  245. if (!$this->checkSize()) {
  246. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  247. return;
  248. }
  249. $this->filePath = $mainfilepath.$this->filePath;
  250. $dirname = $mainfilepath.$dirname;
  251. //创建目录失败
  252. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  253. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  254. return;
  255. } else if (!is_writeable($dirname)) {
  256. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  257. return;
  258. }
  259. //移动文件
  260. $fileget = file_put_contents($this->filePath, $img);
  261. $fileexists = file_exists($this->filePath);
  262. if (!($fileget && $fileexists)) { //移动失败
  263. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  264. } else { //移动成功
  265. $this->stateInfo = $this->stateMap[0];
  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. * @return string
  280. */
  281. private function getFileExt()
  282. {
  283. return strtolower(strrchr($this->oriName, '.'));
  284. }
  285. /**
  286. * 重命名文件
  287. * @return string
  288. */
  289. private function getFullName()
  290. {
  291. //替换日期事件
  292. $t = time();
  293. $d = explode('-', date("Y-y-m-d-H-i-s"));
  294. $format = $this->config["pathFormat"];
  295. $format = str_replace("{yyyy}", $d[0], $format);
  296. $format = str_replace("{yy}", $d[1], $format);
  297. $format = str_replace("{mm}", $d[2], $format);
  298. $format = str_replace("{dd}", $d[3], $format);
  299. $format = str_replace("{hh}", $d[4], $format);
  300. $format = str_replace("{ii}", $d[5], $format);
  301. $format = str_replace("{ss}", $d[6], $format);
  302. $format = str_replace("{time}", $t, $format);
  303. //过滤文件名的非法自负,并替换文件名
  304. $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
  305. $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
  306. $format = str_replace("{filename}", $oriName, $format);
  307. //替换随机字符串
  308. $randNum = rand(1, 10000000000) . rand(1, 10000000000);
  309. if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
  310. $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
  311. }
  312. $ext = $this->getFileExt();
  313. return $format . $ext;
  314. }
  315. /**
  316. * 获取文件名
  317. * @return string
  318. */
  319. private function getFileName () {
  320. return substr($this->filePath, strrpos($this->filePath, '/') + 1);
  321. }
  322. /**
  323. * 获取文件完整路径
  324. * @return string
  325. */
  326. public function getFilePath()
  327. {
  328. $fullname = $this->fullName;
  329. $rootPath = $this->rootPath;
  330. if (substr($fullname, 0, 1) != '/') {
  331. $fullname = '/' . $fullname;
  332. }
  333. return $rootPath . $fullname;
  334. }
  335. /**
  336. * 文件类型检测
  337. * @return bool
  338. */
  339. private function checkType()
  340. {
  341. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  342. }
  343. /**
  344. * 文件大小检测
  345. * @return bool
  346. */
  347. private function checkSize()
  348. {
  349. return $this->fileSize <= ($this->config["maxSize"]);
  350. }
  351. /**
  352. * 获取当前上传成功文件的各项信息
  353. * @return array
  354. */
  355. public function getFileInfo()
  356. {
  357. return array(
  358. "state" => $this->stateInfo,
  359. "url" => $this->fullName,
  360. "title" => $this->fileName,
  361. "original" => $this->oriName,
  362. "type" => $this->fileType,
  363. "size" => $this->fileSize
  364. );
  365. }
  366. }