搜尋
首頁後端開發php教程YII如何使用kindeditor擴展

YII如何使用kindeditor擴展

Jan 02, 2018 pm 01:08 PM
kindeditor使用擴充

YII如何使用kindeditor扩展?本文主要介绍了YII视图整合kindeditor扩展的方法,较为详细的分析了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.&#39;keSource&#39;;
    if(isset(Yii::app()->params->uploadPath)){
      return Yii::getPathOfAlias(&#39;webroot&#39;).str_replace(
                &#39;/&#39;,DIRECTORY_SEPARATOR,
                Yii::app()->params->
                uploadPath);
    }
    return Yii::app()->getAssetmanager()
        ->getPublishedPath($dir).DIRECTORY_SEPARATOR.&#39;upload&#39;;
  }
  public static function getUploadUrl(){
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.&#39;keSource&#39;;
    if(isset(Yii::app()->params->uploadPath)){
      return Yii::app()->baseUrl.Yii::app()->params->uploadPath;
    }
    return Yii::app()->getAssetManager()->publish($dir).&#39;/upload&#39;;
  }
  public function init(){
    if($this->name===null)
      throw new CException(Yii::t(&#39;zii&#39;,&#39;The id property cannot be empty.&#39;));
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.&#39;keSource&#39;;
    $this->baseUrl=Yii::app()->getAssetManager()->publish($dir);
    $cs=Yii::app()->getClientScript();
    $cs->registerCssFile($this->baseUrl.&#39;/themes/default/default.css&#39;);
    if(YII_DEBUG) $cs->registerScriptFile($this->baseUrl.&#39;/kindeditor.js&#39;);
    else $cs->registerScriptFile($this->baseUrl.&#39;/kindeditor-min.js&#39;);
  }
  public function run(){
    $cs=Yii::app()->getClientScript();
    $textAreaOptions=$this->gettextareaOptions();
    $textAreaOptions[&#39;name&#39;]=CHtml::resolveName($this->model,$this->name);
    $this->id=$textAreaOptions[&#39;id&#39;]=CHtml::getIdByName($textAreaOptions[&#39;name&#39;]);
    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(&#39;#$this->id&#39;,
$properties_string
  );
});
EOF;
    $cs->registerScript(&#39;KE&#39;.$this->name,$js,CClientScript::POS_HEAD);
  }
  public function gettextareaOptions(){
    //允许获取的属性
    $allowParams=array(&#39;rows&#39;,&#39;cols&#39;,&#39;style&#39;);
    //准备返回的属性数组
    $params=array();
    foreach($allowParams as $key){
      if(isset($this->textareaOptions[$key]))
        $params[$key]=$this->textareaOptions[$key];
    }
    $params[&#39;name&#39;]=$params[&#39;id&#39;]=$this->name;
    return $params;
  }
  public function getKeProperties(){
    $properties_key=array(
      &#39;width&#39;,
      &#39;height&#39;,
      &#39;minWidth&#39;,
      &#39;minHeight&#39;,
      &#39;items&#39;,
      &#39;noDisableItems&#39;,
      &#39;filterMode&#39;,
      &#39;htmlTags&#39;,
      &#39;wellFormatMode&#39;,
      &#39;resizeType&#39;,
      &#39;themeType&#39;,
      &#39;langType&#39;,
      &#39;designMode&#39;,
      &#39;fullscreenMode&#39;,
      &#39;basePath&#39;,
      &#39;themesPath&#39;,
      &#39;pluginsPath&#39;,
      &#39;langPath&#39;,
      &#39;minChangeSize&#39;,
      &#39;urlType&#39;,
      &#39;newlineTag&#39;,
      &#39;pasteType&#39;,
      &#39;dialogAlignType&#39;,
      &#39;shadowMode&#39;,
      &#39;useContextmenu&#39;,
      &#39;syncType&#39;,
      &#39;indentChar&#39;,
      &#39;cssPath&#39;,
      &#39;cssData&#39;,
      &#39;bodyClass&#39;,
      &#39;colorTable&#39;,
      &#39;afterCreate&#39;,
      &#39;afterChange&#39;,
      &#39;afterTab&#39;,
      &#39;afterFocus&#39;,
      &#39;afterBlur&#39;,
      &#39;afterUpload&#39;,
      &#39;uploadJson&#39;,
      &#39;fileManagerJson&#39;,
      &#39;allowPreviewEmoticons&#39;,
      &#39;allowImageUpload&#39;,
      &#39;allowFlashUpload&#39;,
      &#39;allowMediaUpload&#39;,
      &#39;allowFileUpload&#39;,
      &#39;allowFileManager&#39;,
      &#39;fontSizeTable&#39;,
      &#39;imageTabIndex&#39;,
      &#39;formatUploadUrl&#39;,
      &#39;fullscreenShortcut&#39;,
      &#39;extraFileUploadParams&#39;,
    );
    //准备返回的属性数组
    $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(&#39;ext.KEditor.KEditor&#39;);
    $root_path=KEditor::getUploadPath().&#39;/&#39;;
    $root_url=KEditor::getUploadUrl().&#39;/&#39;;
    //图片扩展名
    $ext_arr = array(&#39;gif&#39;, &#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;, &#39;bmp&#39;);
    //目录名
    $dir_name = empty($_GET[&#39;dir&#39;]) ? &#39;&#39; : trim($_GET[&#39;dir&#39;]);
    if (!in_array($dir_name, array(&#39;&#39;, &#39;image&#39;, &#39;flash&#39;, &#39;media&#39;, &#39;file&#39;))) {
      echo "Invalid Directory name.";
      exit;
    }
    if ($dir_name !== &#39;&#39;) {
      $root_path .= $dir_name . "/";
      $root_url .= $dir_name . "/";
      if (!file_exists($root_path)) {
        mkdir($root_path);
      }
    }
    //根据path参数,设置各路径和URL
    if (empty($_GET[&#39;path&#39;])) {
      $current_path = realpath($root_path) . &#39;/&#39;;
      $current_url = $root_url;
      $current_dir_path = &#39;&#39;;
      $moveup_dir_path = &#39;&#39;;
    } else {
      $current_path = realpath($root_path) . &#39;/&#39; . $_GET[&#39;path&#39;];
      $current_url = $root_url . $_GET[&#39;path&#39;];
      $current_dir_path = $_GET[&#39;path&#39;];
      $moveup_dir_path = preg_replace(&#39;/(.*?)[^\/]+\/$/&#39;, &#39;$1&#39;, $current_dir_path);
    }
    echo realpath($root_path);
    //排序形式,name or size or type
    $order = empty($_GET[&#39;order&#39;]) ? &#39;name&#39; : strtolower($_GET[&#39;order&#39;]);
    //不允许使用..移动到上一级目录
    if (preg_match(&#39;/\.\./&#39;, $current_path)) {
      echo &#39;Access is not allowed.&#39;;
      exit;
    }
    //最后一个字符不是/
    if (!preg_match(&#39;/\/$/&#39;, $current_path)) {
      echo &#39;Parameter is not valid.&#39;;
      exit;
    }
    //目录不存在或不是目录
    if (!file_exists($current_path) || !is_dir($current_path)) {
      echo &#39;Directory does not exist.&#39;;
      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][&#39;is_dir&#39;] = true; //是否文件夹
        $file_list[$i][&#39;has_file&#39;] = (count(scandir($file->getPath())) > 2); //文件夹是否包含文件
        $file_list[$i][&#39;filesize&#39;] = 0; //文件大小
        $file_list[$i][&#39;is_photo&#39;] = false; //是否图片
        $file_list[$i][&#39;filetype&#39;] = &#39;&#39;; //文件类别,用扩展名判断
      }else{
        $file_list[$i][&#39;is_dir&#39;] = false;
        $file_list[$i][&#39;has_file&#39;] = false;
        $file_list[$i][&#39;filesize&#39;] = $file->getSize();
        $file_list[$i][&#39;dir_path&#39;] = &#39;&#39;;
        $file_ext = $file->getExtension();
        $file_list[$i][&#39;is_photo&#39;] = in_array($file_ext, $ext_arr);
        $file_list[$i][&#39;filetype&#39;] = $file_ext;
      }
      $file_list[$i][&#39;filename&#39;] = $file->getFilename(); //文件名,包含扩展名
      $file_list[$i][&#39;datetime&#39;] = date(&#39;Y-m-d H:i:s&#39;, $file->getMTime());
      $i++;
    }
    usort($file_list, array($this,&#39;cmp_func&#39;));
    $result = array();
    //相对于根目录的上一级目录
    $result[&#39;moveup_dir_path&#39;] = $moveup_dir_path;
    //相对于根目录的当前目录
    $result[&#39;current_dir_path&#39;] = $current_dir_path;
    //当前目录的URL
    $result[&#39;current_url&#39;] = $current_url;
    //文件数
    $result[&#39;total_count&#39;] = count($file_list);
    //文件列表数组
    $result[&#39;file_list&#39;] = $file_list;
    //输出JSON字符串
    header(&#39;Content-type: application/json; charset=UTF-8&#39;);
    echo CJSON::encode($result);
    exit;
  }
  //排序
  public function cmp_func($a, $b) {
    global $order;
    if ($a[&#39;is_dir&#39;] && !$b[&#39;is_dir&#39;]) {
      return -1;
    } else if (!$a[&#39;is_dir&#39;] && $b[&#39;is_dir&#39;]) {
      return 1;
    } else {
      if ($order == &#39;size&#39;) {
        if ($a[&#39;filesize&#39;] > $b[&#39;filesize&#39;]) {
          return 1;
        } else if ($a[&#39;filesize&#39;] < $b[&#39;filesize&#39;]) {
          return -1;
        } else {
          return 0;
        }
      } else if ($order == &#39;type&#39;) {
        return strcmp($a[&#39;filetype&#39;], $b[&#39;filetype&#39;]);
      } else {
        return strcmp($a[&#39;filename&#39;], $b[&#39;filename&#39;]);
      }
    }
  }
}
?>

KEditorUpload代码

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

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

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

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

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

在视图里面使用

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

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

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

相关推荐:

Yii2的语言包设置

Yii2中的代码自动加载机制

Yii2实现rbac权限控制

以上是YII如何使用kindeditor擴展的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP和Python:解釋了不同的範例PHP和Python:解釋了不同的範例Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP和Python:深入了解他們的歷史PHP和Python:深入了解他們的歷史Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

在PHP和Python之間進行選擇:指南在PHP和Python之間進行選擇:指南Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP和框架:現代化語言PHP和框架:現代化語言Apr 18, 2025 am 12:14 AM

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHP的影響:網絡開發及以後PHP的影響:網絡開發及以後Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP如何處理對象克隆(克隆關鍵字)和__clone魔法方法?PHP如何處理對象克隆(克隆關鍵字)和__clone魔法方法?Apr 17, 2025 am 12:24 AM

PHP中使用clone關鍵字創建對象副本,並通過\_\_clone魔法方法定制克隆行為。 1.使用clone關鍵字進行淺拷貝,克隆對象的屬性但不克隆對象屬性內的對象。 2.通過\_\_clone方法可以深拷貝嵌套對象,避免淺拷貝問題。 3.注意避免克隆中的循環引用和性能問題,優化克隆操作以提高效率。

PHP與Python:用例和應用程序PHP與Python:用例和應用程序Apr 17, 2025 am 12:23 AM

PHP適用於Web開發和內容管理系統,Python適合數據科學、機器學習和自動化腳本。 1.PHP在構建快速、可擴展的網站和應用程序方面表現出色,常用於WordPress等CMS。 2.Python在數據科學和機器學習領域表現卓越,擁有豐富的庫如NumPy和TensorFlow。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版