YII视图整合kindeditor扩展的方法
程序员文章站
2024-04-02 16:23:28
本文实例讲述了yii视图整合kindeditor扩展的方法。分享给大家供大家参考,具体如下:
比较喜欢用kindeditor,yii上的版本比较旧,所以自己重新整了个扩展...
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于yii框架的php程序设计有所帮助。