SoFunction
Updated on 2025-03-01

Methods for integrating the kindeditor extension of YII view

This article describes the method of integrating the kindeditor extension of YII views. Share it for your reference, as follows:

I prefer to use kindeditor. The version on YII is older, so I re-enrolled the extension myself
First create the KEditor folder under protected\extensions to place the file, put the source file of the kindeditor in keSource, and then create three classes KEditor, KEditorManage and KEditorUpload. KEditor is the main file of the extension, KEditorManage is used to browse server files, and KEditorUpload is used to sample the receiving and uploaded files.

KEditor code

<?php
class KEditor extends CWidget{
  /*
    * TEXTAREA input box attributes ensure that the text box style fails when js calls KE.
    */
  public $textareaOptions=array();
  /*
    * Editor property set.
    */
  public $properties=array();
  /*
    * The name of the TEXTAREA input box must be set.
    * Data type: String
    */
  public $name;
  /*
    * TEXTAREA id, can be empty
    */
  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()->::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/');
    if(YII_DEBUG) $cs->registerScriptFile($this->baseUrl.'/');
    else $cs->registerScriptFile($this->baseUrl.'/');
  }
  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
(function(K) {
  var editor_$this->id = ('#$this->id',
$properties_string
  );
});
EOF;
    $cs->registerScript('KE'.$this->name,$js,CClientScript::POS_HEAD);
  }
  public function gettextareaOptions(){
    //Attributes allowed    $allowParams=array('rows','cols','style');
    //Prepare the returned attribute array    $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',
    );
    //Prepare the returned attribute array    $params=array();
    foreach($properties_key as $key){
      if(isset($this->properties[$key]))
        $params[$key]=$this->properties[$key];
    }
    return $params;
  }
}

KEditorManage Code

<?php
class KEditorManage extends CAction{
  public function run(){
    Yii::import('');
    $root_path=KEditor::getUploadPath().'/';
    $root_url=KEditor::getUploadUrl().'/';
    //Picture extension    $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
    //Directory name    $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);
      }
    }
    //Set each path and URL according to the path parameter    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);
    //Sorting form, name or size or type    $order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
    //Not allowed to use..Move to the previous directory    if (preg_match('/\.\./', $current_path)) {
      echo 'Access is not allowed.';
      exit;
    }
    //The last character is not/    if (!preg_match('/\/$/', $current_path)) {
      echo 'Parameter is not valid.';
      exit;
    }
    //The directory does not exist or is not a directory    if (!file_exists($current_path) || !is_dir($current_path)) {
      echo 'Directory does not exist.';
      exit;
    }
    //Travel the directory to obtain file information    $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; //Is it a folder        $file_list[$i]['has_file'] = (count(scandir($file->getPath())) > 2); //Does the folder contain files?        $file_list[$i]['filesize'] = 0; //File size        $file_list[$i]['is_photo'] = false; //Is it a picture        $file_list[$i]['filetype'] = ''; //File category, use extension to judge      }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 name, including extension      $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file->getMTime());
      $i++;
    }
    usort($file_list, array($this,'cmp_func'));
    $result = array();
    //Relative to the previous directory of the root directory    $result['moveup_dir_path'] = $moveup_dir_path;
    //Relative to the current directory of the root directory    $result['current_dir_path'] = $current_dir_path;
    //The URL of the current directory    $result['current_url'] = $current_url;
    //Number of files    $result['total_count'] = count($file_list);
    //File list array    $result['file_list'] = $file_list;
    //Output JSON string    header('Content-type: application/json; charset=UTF-8');
    echo CJSON::encode($result);
    exit;
  }
  //Sort  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 code

<?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'=>'The directory name is incorrect.  '));
      exit;
    }
    $originalurl='';
    $filename='';
    $date=date('Ymd');
    $id=0;
    $max_size=2097152; //2MBs
    $upload_image=CUploadedFile::getInstanceByName('imgFile');
    Yii::import('');
    $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'=>'Upload file size exceeds the limit.  '));
        exit;
      }
      //New file name      $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'=>"Uploading file extensions is not allowed.\nOnly allowed".implode(',',$ext_arr[$dir]).'Format.  '));
        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'=>'Unknown Error'));
    }
  }
}

Configure config/file and set the upload file storage location

'params'=>array(
    // this is used in contact page
    'adminEmail'=>'webmaster@',
    'uploadPath'=>'/upload', //Add this sentence, upload is the name of the file folder, define it yourself. Here is the upload folder placed in the root directory

Set the action to receive files and browse server files

public function actions()
{
  return array(
    //Add the following two sentences in the return array under actions. If there are no actions, add them yourself    'upload'=>array('class'=>''),
    'manageJson'=>array('class'=>''),
  );
}

Use in the view

<?php $this->widget('',array(
  'model'=>$model, //Passing in form model  'name'=>'content', //Set name  'properties'=>array(
    //Set the action to receive file upload    'uploadJson'=>'/admin/default/upload',
    //Set the action of browsing server files. These two are configured above in /admin/default    'fileManagerJson'=>'/admin/default/manageJson',
    'newlineTag'=>'br',
    'allowFileManager'=>true,
    //Add js before passing the value: to mark these are js code    'afterCreate'=>"js:function() {
        K('#ChapterForm_all_len').val(());
        K('#ChapterForm_word_len').val(('text'));
      }",
    'afterChange'=>"js:function() {
        K('#ChapterForm_all_len').val(());
        K('#ChapterForm_word_len').val(('text'));
      }",
  ),
  'textareaOptions'=>array(
    'style'=>'width:98%;height:400px;',
  )
));
?>

TextareaOptions is used to set the size and style of textarea, and only supports rows, cols and style
The items in properties are the same as those in JS setting the kindeditor. The settings above are the same as those in JS setting below. Some items in the kindeditor can be set

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

For more information about Yii, readers who are interested in this site can view the topic:Yii framework introduction and common techniques summary》、《Summary of excellent development framework for php》、《Basic tutorial on getting started with smarty templates》、《Summary of php operation office documentation skills (including word, excel, access, ppt)》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.