YII-视图- kindeditor扩展

比较喜欢用kindeditor,YII上的版本比较旧,所以自己重新整了个扩展

先在protected\extensions下创建KEditor文件夹用来放文件,keSource里放kindeditor的源文件,然后建三个类KEditor、KEditorManage和KEditorUpload,KEditor是扩展的主文件,KEditorManage是用来浏览服务器文件的,KEditorUpload是用来示例接收上传文件的,

KEditor代码

[html]  view plain copy
  1. <?php  
  2. class KEditor extends CWidget{  
  3.     /*  
  4.      * TEXTAREA输入框的属性,保证js调用KE失败时,文本框的样式。  
  5.      */  
  6.     public $textareaOptions=array();  
  7.     /*  
  8.      * 编辑器属性集。  
  9.      */  
  10.     public $properties=array();  
  11.     /*  
  12.      * TEXTAREA输入框的name,必须设置。  
  13.      * 数据类型:String  
  14.      */  
  15.     public $name;  
  16.     /*  
  17.      * TEXTAREA的id,可为空  
  18.      */  
  19.     public $id;  
  20.       
  21.     public $model;  
  22.       
  23.     public $baseUrl;  
  24.       
  25.     public static function getUploadPath(){  
  26.         $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';  
  27.         if(isset(Yii::app()->params->uploadPath)){  
  28.             return Yii::getPathOfAlias('webroot').str_replace(  
  29.                                 '/',DIRECTORY_SEPARATOR,  
  30.                                 Yii::app()->params->  
  31.                                 uploadPath);  
  32.         }  
  33.         return Yii::app()->getAssetmanager()  
  34.                 ->getPublishedPath($dir).DIRECTORY_SEPARATOR.'upload';  
  35.     }  
  36.       
  37.     public static function getUploadUrl(){  
  38.         $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';  
  39.         if(isset(Yii::app()->params->uploadPath)){  
  40.             return Yii::app()->baseUrl.Yii::app()->params->uploadPath;  
  41.         }  
  42.         return Yii::app()->getAssetManager()->publish($dir).'/upload';  
  43.     }  
  44.       
  45.     public function init(){  
  46.         if($this->name===null)  
  47.             throw new CException(Yii::t('zii','The id property cannot be empty.'));  
  48.               
  49.         $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';  
  50.           
  51.         $this->baseUrl=Yii::app()->getAssetManager()->publish($dir);  
  52.         $cs=Yii::app()->getClientScript();  
  53.         $cs->registerCssFile($this->baseUrl.'/themes/default/default.css');  
  54.         if(YII_DEBUG) $cs->registerScriptFile($this->baseUrl.'/kindeditor.js');  
  55.         else $cs->registerScriptFile($this->baseUrl.'/kindeditor-min.js');  
  56.     }  
  57.       
  58.     public function run(){  
  59.         $cs=Yii::app()->getClientScript();  
  60.         $textAreaOptions=$this->gettextareaOptions();  
  61.         $textAreaOptions['name']=CHtml::resolveName($this->model,$this->name);  
  62.         $this->id=$textAreaOptions['id']=CHtml::getIdByName($textAreaOptions['name']);  
  63.         echo CHtml::activeTextArea($this->model,$this->name,$textAreaOptions);  
  64.           
  65.         $properties_string = CJavaScript::encode($this->getKeProperties());  
  66.   
  67.         $js=<<<EOF  
  68. KindEditor.ready(function(K) {  
  69.     var editor_$this->id = K.create('#$this->id',   
  70. $properties_string  
  71.     );  
  72. });  
  73. EOF;  
  74.         $cs->registerScript('KE'.$this->name,$js,CClientScript::POS_HEAD);  
  75.     }  
  76.       
  77.     public function gettextareaOptions(){  
  78.         //允许获取的属性  
  79.         $allowParams=array('rows','cols','style');  
  80.         //准备返回的属性数组  
  81.         $params=array();  
  82.         foreach($allowParams as $key){  
  83.             if(isset($this->textareaOptions[$key]))  
  84.                 $params[$key]=$this->textareaOptions[$key];  
  85.         }  
  86.         $params['name']=$params['id']=$this->name;  
  87.         return $params;  
  88.     }  
  89.       
  90.     public function getKeProperties(){  
  91.         $properties_key=array(  
  92.             'width',  
  93.             'height',  
  94.             'minWidth',  
  95.             'minHeight',  
  96.             'items',  
  97.             'noDisableItems',  
  98.             'filterMode',  
  99.             'htmlTags',  
  100.             'wellFormatMode',  
  101.             'resizeType',  
  102.             'themeType',  
  103.             'langType',  
  104.             'designMode',  
  105.             'fullscreenMode',  
  106.             'basePath',  
  107.             'themesPath',  
  108.             'pluginsPath',  
  109.             'langPath',  
  110.             'minChangeSize',  
  111.             'urlType',  
  112.             'newlineTag',  
  113.             'pasteType',  
  114.             'dialogAlignType',  
  115.             'shadowMode',  
  116.             'useContextmenu',  
  117.             'syncType',  
  118.             'indentChar',  
  119.             'cssPath',  
  120.             'cssData',  
  121.             'bodyClass',  
  122.             'colorTable',  
  123.             'afterCreate',  
  124.             'afterChange',  
  125.             'afterTab',  
  126.             'afterFocus',  
  127.             'afterBlur',  
  128.             'afterUpload',  
  129.             'uploadJson',  
  130.             'fileManagerJson',  
  131.             'allowPreviewEmoticons',  
  132.             'allowImageUpload',  
  133.             'allowFlashUpload',  
  134.             'allowMediaUpload',  
  135.             'allowFileUpload',  
  136.             'allowFileManager',  
  137.             'fontSizeTable',  
  138.             'imageTabIndex',  
  139.             'formatUploadUrl',  
  140.             'fullscreenShortcut',  
  141.             'extraFileUploadParams',  
  142.         );  
  143.           
  144.         //准备返回的属性数组  
  145.         $params=array();  
  146.         foreach($properties_key as $key){  
  147.             if(isset($this->properties[$key]))  
  148.                 $params[$key]=$this->properties[$key];  
  149.         }  
  150.         return $params;  
  151.     }  
  152. }  

KEditorManage代码

[html]  view plain copy
  1. <?php  
  2. class KEditorManage extends CAction{  
  3.   
  4.     public function run(){  
  5.         Yii::import('ext.KEditor.KEditor');  
  6.         $root_path=KEditor::getUploadPath().'/';  
  7.         $root_url=KEditor::getUploadUrl().'/';  
  8.           
  9.         //图片扩展名  
  10.         $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');  
  11.           
  12.         //目录名  
  13.         $dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);  
  14.         if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {  
  15.             echo "Invalid Directory name.";  
  16.             exit;  
  17.         }  
  18.         if ($dir_name !== '') {  
  19.             $root_path .= $dir_name . "/";  
  20.             $root_url .= $dir_name . "/";  
  21.             if (!file_exists($root_path)) {  
  22.                 mkdir($root_path);  
  23.             }  
  24.         }  
  25.           
  26.         //根据path参数,设置各路径和URL  
  27.         if (empty($_GET['path'])) {  
  28.             $current_path = realpath($root_path) . '/';  
  29.             $current_url = $root_url;  
  30.             $current_dir_path = '';  
  31.             $moveup_dir_path = '';  
  32.         } else {  
  33.             $current_path = realpath($root_path) . '/' . $_GET['path'];  
  34.             $current_url = $root_url . $_GET['path'];  
  35.             $current_dir_path = $_GET['path'];  
  36.             $moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);  
  37.         }  
  38.         echo realpath($root_path);  
  39.         //排序形式,name or size or type  
  40.         $order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);  
  41.           
  42.         //不允许使用..移动到上一级目录  
  43.         if (preg_match('/\.\./', $current_path)) {  
  44.             echo 'Access is not allowed.';  
  45.             exit;  
  46.         }  
  47.         //最后一个字符不是/  
  48.         if (!preg_match('/\/$/', $current_path)) {  
  49.             echo 'Parameter is not valid.';  
  50.             exit;  
  51.         }  
  52.         //目录不存在或不是目录  
  53.         if (!file_exists($current_path) || !is_dir($current_path)) {  
  54.             echo 'Directory does not exist.';  
  55.             exit;  
  56.         }  
  57.           
  58.         //遍历目录取得文件信息  
  59.         $file_list = array();  
  60.           
  61.         $handle = new DirectoryIterator($current_path);  
  62.         $i=0;  
  63.         foreach($handle as $file){  
  64.             if($file->isDot()) continue;  
  65.             if($file->isDir()){  
  66.                 $file_list[$i]['is_dir'] = true; //是否文件夹  
  67.                 $file_list[$i]['has_file'] = (count(scandir($file->getPath())) > 2); //文件夹是否包含文件  
  68.                 $file_list[$i]['filesize'] = 0; //文件大小  
  69.                 $file_list[$i]['is_photo'] = false; //是否图片  
  70.                 $file_list[$i]['filetype'] = ''; //文件类别,用扩展名判断  
  71.             }else{  
  72.                 $file_list[$i]['is_dir'] = false;  
  73.                 $file_list[$i]['has_file'] = false;  
  74.                 $file_list[$i]['filesize'] = $file->getSize();  
  75.                 $file_list[$i]['dir_path'] = '';  
  76.                 $file_ext = $file->getExtension();  
  77.                 $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);  
  78.                 $file_list[$i]['filetype'] = $file_ext;  
  79.             }  
  80.             $file_list[$i]['filename'] = $file->getFilename(); //文件名,包含扩展名  
  81.             $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file->getMTime());  
  82.             $i++;  
  83.         }  
  84.           
  85.         usort($file_list, array($this,'cmp_func'));  
  86.   
  87.         $result = array();  
  88.         //相对于根目录的上一级目录  
  89.         $result['moveup_dir_path'] = $moveup_dir_path;  
  90.         //相对于根目录的当前目录  
  91.         $result['current_dir_path'] = $current_dir_path;  
  92.         //当前目录的URL  
  93.         $result['current_url'] = $current_url;  
  94.         //文件数  
  95.         $result['total_count'] = count($file_list);  
  96.         //文件列表数组  
  97.         $result['file_list'] = $file_list;  
  98.           
  99.         //输出JSON字符串  
  100.         header('Content-type: application/json; charset=UTF-8');  
  101.         echo CJSON::encode($result);  
  102.         exit;  
  103.     }  
  104.       
  105.     //排序  
  106.     public function cmp_func($a, $b) {  
  107.         global $order;  
  108.         if ($a['is_dir'] && !$b['is_dir']) {  
  109.             return -1;  
  110.         } else if (!$a['is_dir'] && $b['is_dir']) {  
  111.             return 1;  
  112.         } else {  
  113.             if ($order == 'size') {  
  114.                 if ($a['filesize'] > $b['filesize']) {  
  115.                     return 1;  
  116.                 } else if ($a['filesize'] < $b['filesize']) {  
  117.                     return -1;  
  118.                 } else {  
  119.                     return 0;  
  120.                 }  
  121.             } else if ($order == 'type') {  
  122.                 return strcmp($a['filetype'], $b['filetype']);  
  123.             } else {  
  124.                 return strcmp($a['filename'], $b['filename']);  
  125.             }  
  126.         }  
  127.     }  
  128. }  
  129. ?>  
KEditorUpload 代码
[html]  view plain copy
  1. <?php  
  2. class KEditorUpload extends CAction{  
  3.       
  4.     public function run(){  
  5.         $dir=isset($_GET['dir'])?trim($_GET['dir']):'file';  
  6.         $ext_arr = array(  
  7.             'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),  
  8.             'flash' => array('swf', 'flv'),  
  9.             'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),  
  10.             'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),  
  11.         );  
  12.         if(empty($ext_arr[$dir])){  
  13.             echo CJSON::encode(array('error'=>1,'message'=>'目录名不正确。'));  
  14.             exit;  
  15.         }  
  16.         $originalurl='';  
  17.         $filename='';  
  18.         $date=date('Ymd');  
  19.         $id=0;  
  20.         $max_size=2097152; //2MBs  
  21.           
  22.         $upload_image=CUploadedFile::getInstanceByName('imgFile');  
  23.           
  24.         Yii::import('ext.KEditor.KEditor');  
  25.         $upload_dir=KEditor::getUploadPath().'/'.$dir;  
  26.         if(!file_exists($upload_dir)) mkdir($upload_dir);  
  27.         $upload_dir=$upload_dir.'/'.$date;  
  28.         if(!file_exists($upload_dir)) mkdir($upload_dir);  
  29.           
  30.         $upload_url=KEditor::getUploadUrl().'/'.$dir.'/'.$date;  
  31.           
  32.         if(is_object($upload_image) && get_class($upload_image)==='CUploadedFile'){  
  33.             if($upload_image->size > $max_size){  
  34.                 echo CJSON::encode(array('error'=>1,'message'=>'上传文件大小超过限制。'));  
  35.                 exit;  
  36.             }  
  37.             //新文件名  
  38.             $filename=date("YmdHis").'_'.rand(10000, 99999);  
  39.             $ext=$upload_image->extensionName;  
  40.             if(in_array($ext, $ext_arr[$dir]) === false){  
  41.                 echo CJSON::encode(array('error'=>1,'message'=>"上传文件扩展名是不允许的扩展名。\n只允许".implode(',',$ext_arr[$dir]).'格式。'));  
  42.                 exit;  
  43.             }  
  44.             $uploadfile=$upload_dir.'/'.$filename.'.'.$ext;  
  45.             $originalurl=$upload_url.'/'.$filename.'.'.$ext;  
  46.               
  47.             $upload_image->saveAs($uploadfile);  
  48.             echo CJSON::encode(array('error'=>0,'url'=>$originalurl));  
  49.         }else{  
  50.             echo CJSON::encode(array('error'=>1,'message'=>'未知错误'));  
  51.         }  
  52.     }  
  53. }  
配置config/main.php文件,设置上传文件存放位置


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

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

[html]  view plain copy
  1. public function actions()  
  2. {  
  3.     return array(  
  4.         //在actions下的return array添加下面两句,没有actions的话自己添加  
  5.         'upload'=>array('class'=>'application.extensions.KEditor.KEditorUpload'),  
  6.         'manageJson'=>array('class'=>'application.extensions.KEditor.KEditorManage'),  
  7.     );  
  8. }  


在视图里面使用

[html]  view plain copy
  1. <?php $this->widget('ext.KEditor.KEditor',array(  
  2.             'model'=>$model,  //传入form model  
  3.             'name'=>'content', //设置name  
  4.             'properties'=>array(  
  5.                 //设置接收文件上传的action  
  6.                 'uploadJson'=>'/admin/default/upload',  
  7.                 //设置浏览服务器文件的action,这两个就是上面配置在/admin/default的  
  8.                 'fileManagerJson'=>'/admin/default/manageJson',  
  9.                 'newlineTag'=>'br',  
  10.                 'allowFileManager'=>true,  
  11.                 //传值前加js:来标记这些是js代码  
  12.                 'afterCreate'=>"js:function() {  
  13.                         K('#ChapterForm_all_len').val(this.count());  
  14.                         K('#ChapterForm_word_len').val(this.count('text'));  
  15.                     }",  
  16.                 'afterChange'=>"js:function() {  
  17.                         K('#ChapterForm_all_len').val(this.count());  
  18.                         K('#ChapterForm_word_len').val(this.count('text'));  
  19.                     }",  
  20.             ),   
  21.             'textareaOptions'=>array(  
  22.                 'style'=>'width:98%;height:400px;',  
  23.             )  
  24.         )); ?>  

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

[html]  view plain copy
  1. var editor1 = K.create('#editor_modelname_name', {  
  2.     uploadJson : "/admin/default/upload",  
  3.     fileManagerJson : "/admin/default/manageJson",  
  4.     newlineTag : "br",  
  5.     allowFileManager : true,  
  6.     afterCreate : function() {  
  7.         K('#ChapterForm_all_len').html(this.count());  
  8.         K('#ChapterForm_word_len').html(this.count('text'));  
  9.     },  
  10.     afterChange : function() {  
  11.         K('#ChapterForm_all_len').html(this.count());  
  12.         K('#ChapterForm_word_len').html(this.count('text'));  
  13.     }  
  14. });  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值