Uploader.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. <?php
  2. error_reporting(E_ERROR);
  3. /**
  4. * Created by JetBrains PhpStorm.
  5. * User: taoqili
  6. * Date: 12-7-18
  7. * Time: 上午11: 32
  8. * UEditor编辑器通用上传类
  9. */
  10. class Uploader
  11. {
  12. private $fileField; //文件域名
  13. private $file; //文件上传对象
  14. private $base64; //文件上传对象
  15. private $config; //配置信息
  16. private $oriName; //原始文件名
  17. private $fileName; //新文件名
  18. private $fullName; //完整文件名,即从当前配置目录开始的URL
  19. private $filePath; //完整文件名,即从当前配置目录开始的URL
  20. private $fileSize; //文件大小
  21. private $fileType; //文件类型
  22. private $stateInfo; //上传状态信息,
  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. );
  44. /**
  45. * 构造函数
  46. * @param string $fileField 表单名称
  47. * @param array $config 配置项
  48. * @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  49. */
  50. public function __construct($fileField, $config, $type = "upload")
  51. {
  52. $this->fileField = $fileField;
  53. $this->config = $config;
  54. $this->type = $type;
  55. if ($type == "remote") {
  56. $this->saveRemote();
  57. } else if($type == "base64") {
  58. $this->upBase64();
  59. } else {
  60. $this->upFile();
  61. }
  62. $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
  63. }
  64. /**
  65. * 上传文件的主处理方法
  66. * @return mixed
  67. */
  68. private function upFile()
  69. {
  70. $file = $this->file = $_FILES[$this->fileField];
  71. if (!$file) {
  72. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  73. return;
  74. }
  75. if ($this->file['error']) {
  76. $this->stateInfo = $this->getStateInfo($file['error']);
  77. return;
  78. } else if (!file_exists($file['tmp_name'])) {
  79. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  80. return;
  81. } else if (!is_uploaded_file($file['tmp_name'])) {
  82. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  83. return;
  84. }
  85. $this->oriName = $file['name'];
  86. $this->fileSize = $file['size'];
  87. $this->fileType = $this->getFileExt();
  88. $this->fullName = $this->getFullName();
  89. $this->filePath = $this->getFilePath();
  90. $this->fileName = $this->getFileName();
  91. $dirname = dirname($this->filePath);
  92. //检查文件大小是否超出限制
  93. if (!$this->checkSize()) {
  94. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  95. return;
  96. }
  97. //检查是否不允许的文件格式
  98. if (!$this->checkType()) {
  99. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  100. return;
  101. }
  102. //创建目录失败
  103. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  104. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  105. return;
  106. } else if (!is_writeable($dirname)) {
  107. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  108. return;
  109. }
  110. //移动文件
  111. if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  112. $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  113. } else { //移动成功
  114. $this->stateInfo = $this->stateMap[0];
  115. $this->watermark($this->filePath,$this->filePath);
  116. }
  117. }
  118. /**
  119. * 处理base64编码的图片上传
  120. * @return mixed
  121. */
  122. private function upBase64()
  123. {
  124. $base64Data = $_POST[$this->fileField];
  125. $img = base64_decode($base64Data);
  126. $this->oriName = $this->config['oriName'];
  127. $this->fileSize = strlen($img);
  128. $this->fileType = $this->getFileExt();
  129. $this->fullName = $this->getFullName();
  130. $this->filePath = $this->getFilePath();
  131. $this->fileName = $this->getFileName();
  132. $dirname = dirname($this->filePath);
  133. //检查文件大小是否超出限制
  134. if (!$this->checkSize()) {
  135. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  136. return;
  137. }
  138. //创建目录失败
  139. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  140. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  141. return;
  142. } else if (!is_writeable($dirname)) {
  143. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  144. return;
  145. }
  146. //移动文件
  147. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  148. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  149. } else { //移动成功
  150. $this->stateInfo = $this->stateMap[0];
  151. $this->watermark($this->filePath,$this->filePath);
  152. }
  153. }
  154. /**
  155. * 拉取远程图片
  156. * @return mixed
  157. */
  158. private function saveRemote()
  159. {
  160. $imgUrl = htmlspecialchars($this->fileField);
  161. $imgUrl = str_replace("&amp;", "&", $imgUrl);
  162. //http开头验证
  163. if (strpos($imgUrl, "http") !== 0) {
  164. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  165. return;
  166. }
  167. //获取请求头并检测死链
  168. $heads = get_headers($imgUrl, 1);
  169. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  170. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  171. return;
  172. }
  173. //格式验证(扩展名验证和Content-Type验证)
  174. $fileType = strtolower(strrchr($imgUrl, '.'));
  175. if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
  176. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  177. return;
  178. }
  179. //打开输出缓冲区并获取远程图片
  180. ob_start();
  181. $context = stream_context_create(
  182. array('http' => array(
  183. 'follow_location' => false // don't follow redirects
  184. ))
  185. );
  186. readfile($imgUrl, false, $context);
  187. $img = ob_get_contents();
  188. ob_end_clean();
  189. preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
  190. $this->oriName = $m ? $m[1]:"";
  191. $this->fileSize = strlen($img);
  192. $this->fileType = $this->getFileExt();
  193. $this->fullName = $this->getFullName();
  194. $this->filePath = $this->getFilePath();
  195. $this->fileName = $this->getFileName();
  196. $dirname = dirname($this->filePath);
  197. //检查文件大小是否超出限制
  198. if (!$this->checkSize()) {
  199. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  200. return;
  201. }
  202. //创建目录失败
  203. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  204. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  205. return;
  206. } else if (!is_writeable($dirname)) {
  207. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  208. return;
  209. }
  210. //移动文件
  211. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  212. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  213. } else { //移动成功
  214. $this->stateInfo = $this->stateMap[0];
  215. $this->watermark($this->filePath,$this->filePath);
  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. if($this->fileType){
  263. $ext = $this->fileType;
  264. } else {
  265. $ext = $this->getFileExt();
  266. }
  267. return $format . $ext;
  268. }
  269. /**
  270. * 获取文件名
  271. * @return string
  272. */
  273. private function getFileName () {
  274. return substr($this->filePath, strrpos($this->filePath, '/') + 1);
  275. }
  276. /**
  277. * 获取文件完整路径
  278. * @return string
  279. */
  280. private function getFilePath()
  281. {
  282. $fullname = $this->fullName;
  283. $rootPath = $_SERVER['DOCUMENT_ROOT'];
  284. if (substr($fullname, 0, 1) != '/') {
  285. $fullname = '/' . $fullname;
  286. }
  287. return $rootPath . $fullname;
  288. }
  289. /**
  290. * 文件类型检测
  291. * @return bool
  292. */
  293. private function checkType()
  294. {
  295. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  296. }
  297. /**
  298. * 文件大小检测
  299. * @return bool
  300. */
  301. private function checkSize()
  302. {
  303. return $this->fileSize <= ($this->config["maxSize"]);
  304. }
  305. /**
  306. * 获取当前上传成功文件的各项信息
  307. * @return array
  308. */
  309. public function getFileInfo()
  310. {
  311. return array(
  312. "state" => $this->stateInfo,
  313. "url" => $this->fullName,
  314. "title" => $this->fileName,
  315. "original" => $this->oriName,
  316. "type" => $this->fileType,
  317. "size" => $this->fileSize
  318. );
  319. }
  320. //图片加水印
  321. public function watermark($source, $target = '', $w_pos = '', $w_img = '', $w_text = 'prfmun',$w_font = 8, $w_color = '#ff0000') {
  322. $configs = include "../../../../caches/configs/system.php";
  323. $uploaders_configs = include "../../../../caches/caches_commons/caches_data/sitelist.cache.php";
  324. $siteid = $this->config["siteid"] ? $this->config["siteid"] : 1;
  325. $uploaders_configs = json_decode($uploaders_configs[$siteid]["setting"],true);
  326. $this->w_img = "../../../../".str_replace("//","/",$uploaders_configs["watermark_img"]);
  327. $this->w_pos = $uploaders_configs["watermark_pos"];
  328. $this->w_minwidth = $uploaders_configs["watermark_minwidth"];
  329. $this->w_minheight = $uploaders_configs["watermark_minheight"];
  330. $this->w_quality = $uploaders_configs["watermark_quality"];
  331. $this->w_pct = $uploaders_configs["watermark_pct"];
  332. $this->watermark_enable = $uploaders_configs["watermark_enable"];
  333. $w_pos = $w_pos ? $w_pos : $this->w_pos;
  334. $w_img = $w_img ? $w_img : $this->w_img;
  335. if(!$this->watermark_enable || !$this->check($source)) return false;
  336. if(!$target) $target = $source;
  337. //$w_img = PHPCMS_PATH.$w_img;
  338. //define('WWW_PATH', dirname(dirname(dirname(__FILE__)));
  339. $source_info = getimagesize($source);
  340. $source_w = $source_info[0];
  341. $source_h = $source_info[1];
  342. if($source_w < $this->w_minwidth || $source_h < $this->w_minheight) return false;
  343. switch($source_info[2]) {
  344. case 1 :
  345. $source_img = imagecreatefromgif($source);
  346. break;
  347. case 2 :
  348. $source_img = imagecreatefromjpeg($source);
  349. break;
  350. case 3 :
  351. $source_img = imagecreatefrompng($source);
  352. break;
  353. default :
  354. return false;
  355. }
  356. if(!empty($w_img) && file_exists($w_img)) {
  357. $ifwaterimage = 1;
  358. $water_info = getimagesize($w_img);
  359. $width = $water_info[0];
  360. $height = $water_info[1];
  361. switch($water_info[2]) {
  362. case 1 :
  363. $water_img = imagecreatefromgif($w_img);
  364. break;
  365. case 2 :
  366. $water_img = imagecreatefromjpeg($w_img);
  367. break;
  368. case 3 :
  369. $water_img = imagecreatefrompng($w_img);
  370. break;
  371. default :
  372. return;
  373. }
  374. } else {
  375. $ifwaterimage = 0;
  376. $temp = imagettfbbox(ceil($w_font*2.5), 0, PC_PATH.'libs/data/font/elephant.ttf', $w_text);
  377. $width = $temp[2] - $temp[6];
  378. $height = $temp[3] - $temp[7];
  379. unset($temp);
  380. }
  381. switch($w_pos) {
  382. case 1:
  383. $wx = 5;
  384. $wy = 5;
  385. break;
  386. case 2:
  387. $wx = ($source_w - $width) / 2;
  388. $wy = 0;
  389. break;
  390. case 3:
  391. $wx = $source_w - $width;
  392. $wy = 0;
  393. break;
  394. case 4:
  395. $wx = 0;
  396. $wy = ($source_h - $height) / 2;
  397. break;
  398. case 5:
  399. $wx = ($source_w - $width) / 2;
  400. $wy = ($source_h - $height) / 2;
  401. break;
  402. case 6:
  403. $wx = $source_w - $width;
  404. $wy = ($source_h - $height) / 2;
  405. break;
  406. case 7:
  407. $wx = 0;
  408. $wy = $source_h - $height;
  409. break;
  410. case 8:
  411. $wx = ($source_w - $width) / 2;
  412. $wy = $source_h - $height;
  413. break;
  414. case 9:
  415. $wx = $source_w - $width;
  416. $wy = $source_h - $height;
  417. break;
  418. case 10:
  419. $wx = rand(0,($source_w - $width));
  420. $wy = rand(0,($source_h - $height));
  421. break;
  422. default:
  423. $wx = rand(0,($source_w - $width));
  424. $wy = rand(0,($source_h - $height));
  425. break;
  426. }
  427. if($ifwaterimage) {
  428. if($water_info[2] == 3) {
  429. imagecopy($source_img, $water_img, $wx, $wy, 0, 0, $width, $height);
  430. } else {
  431. imagecopymerge($source_img, $water_img, $wx, $wy, 0, 0, $width, $height, $this->w_pct);
  432. }
  433. } else {
  434. if(!empty($w_color) && (strlen($w_color)==7)) {
  435. $r = hexdec(substr($w_color,1,2));
  436. $g = hexdec(substr($w_color,3,2));
  437. $b = hexdec(substr($w_color,5));
  438. } else {
  439. return;
  440. }
  441. imagestring($source_img,$w_font,$wx,$wy,$w_text,imagecolorallocate($source_img,$r,$g,$b));
  442. }
  443. switch($source_info[2]) {
  444. case 1 :
  445. imagegif($source_img, $target);
  446. break;
  447. case 2 :
  448. imagejpeg($source_img, $target, $this->w_quality);
  449. break;
  450. case 3 :
  451. imagepng($source_img, $target);
  452. break;
  453. default :
  454. return;
  455. }
  456. if(isset($water_info)) {
  457. unset($water_info);
  458. }
  459. if(isset($water_img)) {
  460. imagedestroy($water_img);
  461. }
  462. unset($source_info);
  463. imagedestroy($source_img);
  464. return true;
  465. }
  466. public function check($image) {
  467. return extension_loaded('gd') && preg_match("/\.(jpg|jpeg|gif|png)/i", $image, $m) && file_exists($image) && function_exists('imagecreatefrom'.($m[1] == 'jpg' ? 'jpeg' : $m[1]));
  468. }
  469. }