thinkphp5整合最新ueditor,支持图片加水印

8 篇文章 0 订阅
7 篇文章 0 订阅

UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码...


thinkphp5 TPshop项目开发中用到了富文本编辑器,选择有很多,不过资料手册文档最齐全的当然属百度的ueditor,可是发现TPshop2.05版之前使用的是ueditor1.26老版本,在上传图片时需要依赖flash,而很多新版本浏览器开始禁用flash,那么问题来了,ueditor需要升级才能兼容。

编辑器效果

简单贴一段主要核心代码,有不妥的地方可以多多交流
  1. <html>
  2. <load href="__ROOT__/public/plugins/Ueditor/ueditor.config.js"/>
  3. <load href="__ROOT__/public/plugins/Ueditor/ueditor.all.min.js"/>
  4. <script type="text/javascript" charset="utf-8" src="__ROOT__/public/plugins/Ueditor/lang/zh-cn/zh-cn.js"></script>
  5. <script src="__ROOT__/public/static/js/layer/laydate/laydate.js"></script>
  6. <body>
  7.  <textarea class="span12 ckeditor" id="post_content" name="content" title="">{$info.content}</textarea>  
  8. <script type="text/javascript">
  9.     var url="{:url('Ueditor/index',array('savePath'=>'article'))}";
  10.     var ue = UE.getEditor('post_content',{
  11.         serverUrl :url,
  12.         zIndex: 999,
  13.         initialFrameWidth: "80%", //初化宽度
  14.         initialFrameHeight: 300, //初化高度            
  15.         focus: false, //初始化时,是否让编辑器获得焦点true或false
  16.         maximumWords: 99999, removeFormatAttributes: 'class,style,lang,width,height,align,hspace,valign',//允许的最大字符数 'fullscreen',
  17.         pasteplain:false, //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴
  18.         autoHeightEnabled: true
  19.     });
  20. </script>    
  21. </body>
  22. </html>
复制代码
php接收代码
  1. class Ueditor extends Base
  2. {
  3.     private $sub_name = array('date', 'Y/m-d');
  4.     private $savePath = 'temp/';
  5.     public function __construct()
  6.     {
  7.         parent::__construct();
  8.         
  9.         //header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
  10.         //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
  11.         
  12.         date_default_timezone_set("Asia/Shanghai");
  13.         
  14.         $this->savePath = I('savepath','temp').'/';
  15.         
  16.         error_reporting(E_ERROR | E_WARNING);
  17.         
  18.         header("Content-Type: text/html; charset=utf-8");
  19.     }
  20.     
  21.     public function index(){
  22.         
  23.         $CONFIG2 = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("./public/plugins/Ueditor/php/config.json")), true);
  24.         $action = $_GET['action'];
  25.         
  26.         switch ($action) {
  27.             case 'config':
  28.                 $result =  json_encode($CONFIG2);
  29.                 break;
  30.             /* 上传图片 */
  31.             case 'uploadimage':
  32.                 $fieldName = $CONFIG2['imageFieldName'];
  33.                 $result = $this->upFile($fieldName);
  34.                 break;
  35.             /* 上传涂鸦 */
  36.             case 'uploadscrawl':
  37.                 $config = array(
  38.                     "pathFormat" => $CONFIG2['scrawlPathFormat'],
  39.                     "maxSize" => $CONFIG2['scrawlMaxSize'],
  40.                     "allowFiles" => $CONFIG2['scrawlAllowFiles'],
  41.                     "oriName" => "scrawl.png"
  42.                 );
  43.                 $fieldName = $CONFIG2['scrawlFieldName'];
  44.                 $base64 = "base64";
  45.                 $result = $this->upBase64($config,$fieldName);
  46.                 break;
  47.             /* 上传视频 */
  48.             case 'uploadvideo':
  49.                 $fieldName = $CONFIG2['videoFieldName'];
  50.                 $result = $this->upFile($fieldName);
  51.                 break;
  52.             /* 上传文件 */
  53.             case 'uploadfile':
  54.                 $fieldName = $CONFIG2['fileFieldName'];
  55.                 $result = $this->upFile($fieldName);
  56.                 break;
  57.             /* 列出图片 */
  58.             case 'listimage':
  59.                 $allowFiles = $CONFIG2['imageManagerAllowFiles'];
  60.                 $listSize = $CONFIG2['imageManagerListSize'];
  61.                 $path = $CONFIG2['imageManagerListPath'];
  62.                 $get =$_GET;
  63.                 $result =$this->fileList($allowFiles,$listSize,$get);
  64.                 break;
  65.             /* 列出文件 */
  66.             case 'listfile':
  67.                 $allowFiles = $CONFIG2['fileManagerAllowFiles'];
  68.                 $listSize = $CONFIG2['fileManagerListSize'];
  69.                 $path = $CONFIG2['fileManagerListPath'];
  70.                 $get = $_GET;
  71.                 $result = $this->fileList($allowFiles,$listSize,$get);
  72.                 break;
  73.             /* 抓取远程文件 */
  74.             case 'catchimage':
  75.                 $config = array(
  76.                     "pathFormat" => $CONFIG2['catcherPathFormat'],
  77.                     "maxSize" => $CONFIG2['catcherMaxSize'],
  78.                     "allowFiles" => $CONFIG2['catcherAllowFiles'],
  79.                     "oriName" => "remote.png"
  80.                 );
  81.                 $fieldName = $CONFIG2['catcherFieldName'];
  82.                 /* 抓取远程图片 */
  83.                 $list = array();
  84.                 isset($_POST[$fieldName]) ? $source = $_POST[$fieldName] : $source = $_GET[$fieldName];
  85.                 
  86.                 foreach($source as $imgUrl){
  87.                     $info = json_decode($this->saveRemote($config,$imgUrl),true);
  88.                     array_push($list, array(
  89.                         "state" => $info["state"],
  90.                         "url" => $info["url"],
  91.                         "size" => $info["size"],
  92.                         "title" => htmlspecialchars($info["title"]),
  93.                         "original" => htmlspecialchars($info["original"]),
  94.                         "source" => htmlspecialchars($imgUrl)
  95.                     ));
  96.                 }
  97.                 $result = json_encode(array(
  98.                     'state' => count($list) ? 'SUCCESS':'ERROR',
  99.                     'list' => $list
  100.                 ));
  101.                 break;
  102.             default:
  103.                 $result = json_encode(array(
  104.                     'state' => '请求地址出错'
  105.                 ));
  106.                 break;
  107.         }
  108.         /* 输出结果 */
  109.         if(isset($_GET["callback"])){
  110.             if(preg_match("/^[\w_]+$/", $_GET["callback"])){
  111.                 echo htmlspecialchars($_GET["callback"]).'('.$result.')';
  112.             }else{
  113.                 echo json_encode(array(
  114.                     'state' => 'callback参数不合法'
  115.                 ));
  116.             }
  117.         }else{
  118.             echo $result;
  119.         }
  120.     }
  121.     
  122.     //上传文件
  123.     private function upFile($fieldName){
  124.         $file = request()->file($fieldName);
  125.         
  126.         $result = $this->validate(
  127.                 ['file2' => $file],
  128.                 ['file2'=>'image','file2'=>'fileSize:40000000'],
  129.                 ['file2.image' => '上传文件必须为图片','file2.fileSize' => '上传文件过大']
  130.         );
  131.         
  132.         if (true !== $result || empty($file)) {
  133.             $state = "ERROR" . $result;
  134.         }else{
  135.             // 移动到框架应用根目录/public/uploads/ 目录下
  136.             $this->savePath = $this->savePath.date('Y').'/'.date('m-d').'/';
  137.             // 使用自定义的文件保存规则
  138.             $info = $file->rule(function ($file) {
  139.                 return  md5(mt_rand());
  140.             })->move('public/upload/'.$this->savePath);
  141.         }
  142.         
  143.         if($info){
  144.             $data = array(
  145.                 'state' => 'SUCCESS',
  146.                 'url' => '/public/upload/'.$this->savePath.$info->getSaveName(),
  147.                 'title' => $info->getFilename(),
  148.                 'original' => $info->getFilename(),
  149.                 'type' => '.' . $info->getExtension(),
  150.                 'size' => $info->getSize(),
  151.             );
  152.             //图片加水印
  153.             if($this->savePath=='Goods/'){
  154.                 $image = new \Think\Image();
  155.                 $water = tpCache('water');
  156.                 $imgresource = ".".$data['url'];
  157.                 $image->open($imgresource);
  158.                 if($water['is_mark']==1 && $image->width()>$water['mark_width'] && $image->height()>$water['mark_height']){
  159.                     if($water['mark_type'] == 'text'){
  160.                         $image->text($water['mark_txt'],'./hgzb.ttf',20,'#000000',9)->save($imgresource);
  161.                     }else{
  162.                         $image->water(".".$water['mark_img'],9,$water['mark_degree'])->save($imgresource);
  163.                     }
  164.                 }
  165.             }
  166.         }else{
  167.             $data = array('state' => $state.$info->getError());
  168.         }
  169.         return json_encode($data);
  170.     }
  171.     //列出图片
  172.     private function fileList($allowFiles,$listSize,$get){
  173.         $dirname = './public/upload/';
  174.         $allowFiles = substr(str_replace(".","|",join("",$allowFiles)),1);
  175.         /* 获取参数 */
  176.         $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
  177.         $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;
  178.         $end = $start + $size;
  179.         /* 获取文件列表 */
  180.         $path = $dirname;
  181.         $files = $this->getFiles($path,$allowFiles);
  182.         if(!count($files)){
  183.             return json_encode(array(
  184.                 "state" => "no match file",
  185.                 "list" => array(),
  186.                 "start" => $start,
  187.                 "total" => count($files)
  188.             ));
  189.         }
  190.         /* 获取指定范围的列表 */
  191.         $len = count($files);
  192.         for($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
  193.             $list[] = $files[$i];
  194.         }
  195.         /* 返回数据 */
  196.         $result = json_encode(array(
  197.             "state" => "SUCCESS",
  198.             "list" => $list,
  199.             "start" => $start,
  200.             "total" => count($files)
  201.         ));
  202.         return $result;
  203.     }
  204.        /*
  205.      * 遍历获取目录下的指定类型的文件
  206.      * @param $path
  207.      * @param array $files
  208.      * @return array
  209.     */
  210.     private function getFiles($path,$allowFiles,&$files = array()){
  211.         if(!is_dir($path)) return null;
  212.         if(substr($path,strlen($path)-1) != '/') $path .= '/';
  213.         $handle = opendir($path);
  214.             
  215.         while(false !== ($file = readdir($handle))){
  216.             if($file != '.' && $file != '..'){
  217.                 $path2 = $path.$file;
  218.                 if(is_dir($path2)){
  219.                     $this->getFiles($path2,$allowFiles,$files);
  220.                 }else{
  221.                     if(preg_match("/\.(".$allowFiles.")$/i",$file)){
  222.                         $files[] = array(
  223.                             'url' => substr($path2,1),
  224.                             'mtime' => filemtime($path2)
  225.                         );
  226.                     }
  227.                 }
  228.             }
  229.         }        
  230.         return $files;
  231.     }

复制代码
更多详细代码可以下载TPshop源码查看
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于ThinkPHP框架整合极光推送的示例代码: 1. 安装JPush SDK 使用composer安装JPush SDK: ``` composer require jpush/jpush ``` 2. 配置JPush 在ThinkPHP框架中,可以将JPush的配置信息写入到config目录下的jpush.php文件中,示例代码如下: ```php return [ 'app_key' => 'YOUR_APP_KEY', 'master_secret' => 'YOUR_MASTER_SECRET', ]; ``` 3. 创建JPushService类 在app/service目录下创建JPushService类,该类用于封装极光推送的相关操作。 ```php <?php namespace app\service; use JPush\Client as JPush; class JPushService { protected $jpush; public function __construct() { $config = config('jpush'); $this->jpush = new JPush($config['app_key'], $config['master_secret']); } // 发送通知 public function sendNotification($title, $content, $extras = [], $audience = 'all') { $notification = [ 'title' => $title, 'alert' => $content, ]; $message = [ 'title' => $title, 'msg_content' => $content, 'extras' => $extras, ]; $options = [ 'apns_production' => false, ]; $response = $this->jpush->push() ->setPlatform(['ios', 'android']) ->setAudience($audience) ->setNotification($notification) ->setMessage($message) ->setOptions($options) ->send(); return $response; } } ``` 4. 使用JPushService类发送推送 在控制器中使用JPushService类发送推送,示例代码如下: ```php <?php namespace app\controller; use app\service\JPushService; class PushController { public function send() { $title = '测试推送'; $content = '这是一条测试推送'; $extras = ['key1' => 'value1', 'key2' => 'value2']; $jpushService = new JPushService(); $response = $jpushService->sendNotification($title, $content, $extras); if ($response['http_code'] === 200) { return json(['code' => 0, 'message' => '推送成功']); } else { return json(['code' => -1, 'message' => '推送失败']); } } } ``` 以上就是基于ThinkPHP框架整合极光推送的示例代码。需要注意的是,示例代码中使用了JPush的免费版服务,如果需要使用更高级别的服务,需要进行相应的付费。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值