YII视图整合kindeditor扩展的方法


Posted in PHP onJuly 13, 2016

本文实例讲述了YII视图整合kindeditor扩展的方法。分享给大家供大家参考,具体如下:

比较喜欢用kindeditor,YII上的版本比较旧,所以自己重新整了个扩展
先在protected\extensions下创建KEditor文件夹用来放文件,keSource里放kindeditor的源文件,然后建三个类KEditor、KEditorManage和KEditorUpload,KEditor是扩展的主文件,KEditorManage是用来浏览服务器文件的,KEditorUpload是用来示例接收上传文件的,

KEditor代码

<?php
class KEditor extends CWidget{
  /*
   * TEXTAREA输入框的属性,保证js调用KE失败时,文本框的样式。
   */
  public $textareaOptions=array();
  /*
   * 编辑器属性集。
   */
  public $properties=array();
  /*
   * TEXTAREA输入框的name,必须设置。
   * 数据类型:String
   */
  public $name;
  /*
   * TEXTAREA的id,可为空
   */
  public $id;
  public $model;
  public $baseUrl;
  public static function getUploadPath(){
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
    if(isset(Yii::app()->params->uploadPath)){
      return Yii::getPathOfAlias('webroot').str_replace(
                '/',DIRECTORY_SEPARATOR,
                Yii::app()->params->
                uploadPath);
    }
    return Yii::app()->getAssetmanager()
        ->getPublishedPath($dir).DIRECTORY_SEPARATOR.'upload';
  }
  public static function getUploadUrl(){
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
    if(isset(Yii::app()->params->uploadPath)){
      return Yii::app()->baseUrl.Yii::app()->params->uploadPath;
    }
    return Yii::app()->getAssetManager()->publish($dir).'/upload';
  }
  public function init(){
    if($this->name===null)
      throw new CException(Yii::t('zii','The id property cannot be empty.'));
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
    $this->baseUrl=Yii::app()->getAssetManager()->publish($dir);
    $cs=Yii::app()->getClientScript();
    $cs->registerCssFile($this->baseUrl.'/themes/default/default.css');
    if(YII_DEBUG) $cs->registerScriptFile($this->baseUrl.'/kindeditor.js');
    else $cs->registerScriptFile($this->baseUrl.'/kindeditor-min.js');
  }
  public function run(){
    $cs=Yii::app()->getClientScript();
    $textAreaOptions=$this->gettextareaOptions();
    $textAreaOptions['name']=CHtml::resolveName($this->model,$this->name);
    $this->id=$textAreaOptions['id']=CHtml::getIdByName($textAreaOptions['name']);
    echo CHtml::activeTextArea($this->model,$this->name,$textAreaOptions);
    $properties_string = CJavaScript::encode($this->getKeProperties());
    $js=<<<EOF
KindEditor.ready(function(K) {
  var editor_$this->id = K.create('#$this->id',
$properties_string
  );
});
EOF;
    $cs->registerScript('KE'.$this->name,$js,CClientScript::POS_HEAD);
  }
  public function gettextareaOptions(){
    //允许获取的属性
    $allowParams=array('rows','cols','style');
    //准备返回的属性数组
    $params=array();
    foreach($allowParams as $key){
      if(isset($this->textareaOptions[$key]))
        $params[$key]=$this->textareaOptions[$key];
    }
    $params['name']=$params['id']=$this->name;
    return $params;
  }
  public function getKeProperties(){
    $properties_key=array(
      'width',
      'height',
      'minWidth',
      'minHeight',
      'items',
      'noDisableItems',
      'filterMode',
      'htmlTags',
      'wellFormatMode',
      'resizeType',
      'themeType',
      'langType',
      'designMode',
      'fullscreenMode',
      'basePath',
      'themesPath',
      'pluginsPath',
      'langPath',
      'minChangeSize',
      'urlType',
      'newlineTag',
      'pasteType',
      'dialogAlignType',
      'shadowMode',
      'useContextmenu',
      'syncType',
      'indentChar',
      'cssPath',
      'cssData',
      'bodyClass',
      'colorTable',
      'afterCreate',
      'afterChange',
      'afterTab',
      'afterFocus',
      'afterBlur',
      'afterUpload',
      'uploadJson',
      'fileManagerJson',
      'allowPreviewEmoticons',
      'allowImageUpload',
      'allowFlashUpload',
      'allowMediaUpload',
      'allowFileUpload',
      'allowFileManager',
      'fontSizeTable',
      'imageTabIndex',
      'formatUploadUrl',
      'fullscreenShortcut',
      'extraFileUploadParams',
    );
    //准备返回的属性数组
    $params=array();
    foreach($properties_key as $key){
      if(isset($this->properties[$key]))
        $params[$key]=$this->properties[$key];
    }
    return $params;
  }
}

KEditorManage代码

<?php
class KEditorManage extends CAction{
  public function run(){
    Yii::import('ext.KEditor.KEditor');
    $root_path=KEditor::getUploadPath().'/';
    $root_url=KEditor::getUploadUrl().'/';
    //图片扩展名
    $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
    //目录名
    $dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
    if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
      echo "Invalid Directory name.";
      exit;
    }
    if ($dir_name !== '') {
      $root_path .= $dir_name . "/";
      $root_url .= $dir_name . "/";
      if (!file_exists($root_path)) {
        mkdir($root_path);
      }
    }
    //根据path参数,设置各路径和URL
    if (empty($_GET['path'])) {
      $current_path = realpath($root_path) . '/';
      $current_url = $root_url;
      $current_dir_path = '';
      $moveup_dir_path = '';
    } else {
      $current_path = realpath($root_path) . '/' . $_GET['path'];
      $current_url = $root_url . $_GET['path'];
      $current_dir_path = $_GET['path'];
      $moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
    }
    echo realpath($root_path);
    //排序形式,name or size or type
    $order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
    //不允许使用..移动到上一级目录
    if (preg_match('/\.\./', $current_path)) {
      echo 'Access is not allowed.';
      exit;
    }
    //最后一个字符不是/
    if (!preg_match('/\/$/', $current_path)) {
      echo 'Parameter is not valid.';
      exit;
    }
    //目录不存在或不是目录
    if (!file_exists($current_path) || !is_dir($current_path)) {
      echo 'Directory does not exist.';
      exit;
    }
    //遍历目录取得文件信息
    $file_list = array();
    $handle = new DirectoryIterator($current_path);
    $i=0;
    foreach($handle as $file){
      if($file->isDot()) continue;
      if($file->isDir()){
        $file_list[$i]['is_dir'] = true; //是否文件夹
        $file_list[$i]['has_file'] = (count(scandir($file->getPath())) > 2); //文件夹是否包含文件
        $file_list[$i]['filesize'] = 0; //文件大小
        $file_list[$i]['is_photo'] = false; //是否图片
        $file_list[$i]['filetype'] = ''; //文件类别,用扩展名判断
      }else{
        $file_list[$i]['is_dir'] = false;
        $file_list[$i]['has_file'] = false;
        $file_list[$i]['filesize'] = $file->getSize();
        $file_list[$i]['dir_path'] = '';
        $file_ext = $file->getExtension();
        $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
        $file_list[$i]['filetype'] = $file_ext;
      }
      $file_list[$i]['filename'] = $file->getFilename(); //文件名,包含扩展名
      $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file->getMTime());
      $i++;
    }
    usort($file_list, array($this,'cmp_func'));
    $result = array();
    //相对于根目录的上一级目录
    $result['moveup_dir_path'] = $moveup_dir_path;
    //相对于根目录的当前目录
    $result['current_dir_path'] = $current_dir_path;
    //当前目录的URL
    $result['current_url'] = $current_url;
    //文件数
    $result['total_count'] = count($file_list);
    //文件列表数组
    $result['file_list'] = $file_list;
    //输出JSON字符串
    header('Content-type: application/json; charset=UTF-8');
    echo CJSON::encode($result);
    exit;
  }
  //排序
  public function cmp_func($a, $b) {
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
      return -1;
    } else if (!$a['is_dir'] && $b['is_dir']) {
      return 1;
    } else {
      if ($order == 'size') {
        if ($a['filesize'] > $b['filesize']) {
          return 1;
        } else if ($a['filesize'] < $b['filesize']) {
          return -1;
        } else {
          return 0;
        }
      } else if ($order == 'type') {
        return strcmp($a['filetype'], $b['filetype']);
      } else {
        return strcmp($a['filename'], $b['filename']);
      }
    }
  }
}
?>

KEditorUpload代码

<?php
class KEditorUpload extends CAction{
  public function run(){
    $dir=isset($_GET['dir'])?trim($_GET['dir']):'file';
    $ext_arr = array(
      'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
      'flash' => array('swf', 'flv'),
      'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
      'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
    );
    if(empty($ext_arr[$dir])){
      echo CJSON::encode(array('error'=>1,'message'=>'目录名不正确。'));
      exit;
    }
    $originalurl='';
    $filename='';
    $date=date('Ymd');
    $id=0;
    $max_size=2097152; //2MBs
    $upload_image=CUploadedFile::getInstanceByName('imgFile');
    Yii::import('ext.KEditor.KEditor');
    $upload_dir=KEditor::getUploadPath().'/'.$dir;
    if(!file_exists($upload_dir)) mkdir($upload_dir);
    $upload_dir=$upload_dir.'/'.$date;
    if(!file_exists($upload_dir)) mkdir($upload_dir);
    $upload_url=KEditor::getUploadUrl().'/'.$dir.'/'.$date;
    if(is_object($upload_image) && get_class($upload_image)==='CUploadedFile'){
      if($upload_image->size > $max_size){
        echo CJSON::encode(array('error'=>1,'message'=>'上传文件大小超过限制。'));
        exit;
      }
      //新文件名
      $filename=date("YmdHis").'_'.rand(10000, 99999);
      $ext=$upload_image->extensionName;
      if(in_array($ext, $ext_arr[$dir]) === false){
        echo CJSON::encode(array('error'=>1,'message'=>"上传文件扩展名是不允许的扩展名。\n只允许".implode(',',$ext_arr[$dir]).'格式。'));
        exit;
      }
      $uploadfile=$upload_dir.'/'.$filename.'.'.$ext;
      $originalurl=$upload_url.'/'.$filename.'.'.$ext;
      $upload_image->saveAs($uploadfile);
      echo CJSON::encode(array('error'=>0,'url'=>$originalurl));
    }else{
      echo CJSON::encode(array('error'=>1,'message'=>'未知错误'));
    }
  }
}

配置config/main.php文件,设置上传文件存放位置

'params'=>array(
    // this is used in contact page
    'adminEmail'=>'webmaster@example.com',
    'uploadPath'=>'/upload', //添加这句,upload为存放文件文件夹的名字,自己定义,这里是放在根目录的upload文件夹

设置接收文件和浏览服务器文件的action

public function actions()
{
  return array(
    //在actions下的return array添加下面两句,没有actions的话自己添加
    'upload'=>array('class'=>'application.extensions.KEditor.KEditorUpload'),
    'manageJson'=>array('class'=>'application.extensions.KEditor.KEditorManage'),
  );
}

在视图里面使用

<?php $this->widget('ext.KEditor.KEditor',array(
  'model'=>$model, //传入form model
  'name'=>'content', //设置name
  'properties'=>array(
    //设置接收文件上传的action
    'uploadJson'=>'/admin/default/upload',
    //设置浏览服务器文件的action,这两个就是上面配置在/admin/default的
    'fileManagerJson'=>'/admin/default/manageJson',
    'newlineTag'=>'br',
    'allowFileManager'=>true,
    //传值前加js:来标记这些是js代码
    'afterCreate'=>"js:function() {
        K('#ChapterForm_all_len').val(this.count());
        K('#ChapterForm_word_len').val(this.count('text'));
      }",
    'afterChange'=>"js:function() {
        K('#ChapterForm_all_len').val(this.count());
        K('#ChapterForm_word_len').val(this.count('text'));
      }",
  ),
  'textareaOptions'=>array(
    'style'=>'width:98%;height:400px;',
  )
));
?>

textareaOptions用来设置textarea的大小和样式,仅支持rows、cols和style
properties的各项跟js设置kindeditor的是一样的,上面的设置与下面用js设置的是一致,kindeditor原来有的项都可以设置

var editor1 = K.create('#editor_modelname_name', {
  uploadJson : "/admin/default/upload",
  fileManagerJson : "/admin/default/manageJson",
  newlineTag : "br",
  allowFileManager : true,
  afterCreate : function() {
    K('#ChapterForm_all_len').html(this.count());
    K('#ChapterForm_word_len').html(this.count('text'));
  },
  afterChange : function() {
    K('#ChapterForm_all_len').html(this.count());
    K('#ChapterForm_word_len').html(this.count('text'));
  }
});

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

PHP 相关文章推荐
php 分页原理详解
Aug 21 PHP
关于php mvc开发模式的感想
Jun 28 PHP
PHP获取浏览器信息类和客户端地理位置的2个方法
Apr 24 PHP
ThinkPHP3.1之D方法实例详解
Jun 20 PHP
常见php数据文件缓存类汇总
Dec 05 PHP
php实现删除空目录的方法
Mar 16 PHP
php安装swoole扩展的方法
Mar 19 PHP
php截取指定2个字符之间字符串的方法
Apr 15 PHP
Yii使用Captcha验证码的方法
Dec 28 PHP
PHP格式化MYSQL返回float类型的方法
Mar 30 PHP
PHP版单点登陆实现方案的实例
Nov 17 PHP
php curl简单采集图片生成base64编码(并附curl函数参数说明)
Feb 15 PHP
Yii+upload实现AJAX上传图片的方法
Jul 13 #PHP
Yii安装与使用Excel扩展的方法
Jul 13 #PHP
Yii配置与使用memcached缓存的方法
Jul 13 #PHP
Yii使用smsto短信接口的函数demo示例
Jul 13 #PHP
PHP实现自动识别原编码并对字符串进行编码转换的方法
Jul 13 #PHP
PHP中类属性与类静态变量的访问方法示例
Jul 13 #PHP
ucenter中词语过滤原理分析
Jul 13 #PHP
You might like
PHP文件上传原理简单分析
2011/05/29 PHP
php图像处理类实例
2015/07/28 PHP
PHP程序员不应该忽略的3点
2015/10/09 PHP
用php+ajax新建流程(请假、进货、出货等)
2017/06/11 PHP
Yii2第三方类库插件Imagine的安装和使用
2017/07/06 PHP
PHP命名空间与自动加载机制的基础介绍
2019/08/25 PHP
firefox 和 ie 事件处理的细节,研究,再研究 书写同时兼容ie和ff的事件处理代码
2007/04/12 Javascript
safari,opera嵌入iframe页面cookie读取问题解决方法
2010/06/23 Javascript
在多个页面使用同一个HTML片段《续》
2011/03/04 Javascript
jQuery中.live()方法的用法深入解析
2013/12/30 Javascript
对JavaScript中this指针的新理解分享
2015/01/31 Javascript
在JavaScript的jQuery库中操作AJAX的方法讲解
2015/08/15 Javascript
js焦点文字滚动效果代码分享
2015/08/25 Javascript
H5基于iScroll实现下拉刷新和上拉加载更多
2017/07/18 Javascript
async/await优雅的错误处理方法总结
2019/01/30 Javascript
JS获取本地地址及天气的方法实例小结
2019/05/10 Javascript
JavaScript键盘事件响应顺序详解
2019/09/30 Javascript
用Angular实现一个扫雷的游戏示例
2020/05/15 Javascript
[35:34]Liquid vs Winstrike 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
使用Python下的XSLT API进行web开发的简单教程
2015/04/15 Python
Python爬取京东的商品分类与链接
2016/08/26 Python
Python多进程fork()函数详解
2019/02/22 Python
树莓派3 搭建 django 服务器的实例
2019/08/29 Python
Python *args和**kwargs用法实例解析
2020/03/02 Python
pycharm 激活码及使用方式的详细教程
2020/05/12 Python
Python本地及虚拟解释器配置过程解析
2020/10/13 Python
python中使用.py配置文件的方法详解
2020/11/23 Python
APM Monaco中国官网:来自摩纳哥珠宝品牌
2017/12/27 全球购物
HomeAway英国:全球领先的度假租赁在线市场
2020/02/03 全球购物
技校教师求职简历的自我评价
2013/10/20 职场文书
幼儿园小班植树节活动方案
2014/03/04 职场文书
学校总务处领导干部个人对照检查材料思想汇报
2014/10/06 职场文书
保证书格式
2015/01/16 职场文书
2015年大学学生会工作总结
2015/05/13 职场文书
Python基础数据类型tuple元组的概念与用法
2021/08/02 Python
Python Django项目和应用的创建详解
2021/11/27 Python