_php example of the method of consolidating kindeditor extension in Yii view

Source: Internet
Author: User

The example in this article describes the approach to consolidating kindeditor extensions for the Yii view. Share to everyone for your reference, specific as follows:

I prefer to use the version on the kindeditor,yii older, so I have a whole new extension
First create the Keditor folder under Protected\extensions to put the file, Kesource place kindeditor source file, then build three classes Keditor, Keditormanage and Keditorupload, Keditor is the extended primary file, Keditormanage is used to browse Server files, Keditorupload is used to sample the upload files,

Keditor Code

<?php class Keditor extends cwidget{/* TextArea the properties of the input box to guarantee the style of the text box when the JS call Ke fails.
  * * Public $textareaOptions =array ();
   /* Editor Property set.
  * * Public $properties =array ();
   * * TextArea the name of the input box must be set.
  * Data type: String */public $name;
  * * TextArea ID, can be null/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 '; The 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 '; The 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::P os_head);
    The Public Function gettextareaoptions () {//Allow property to be fetched $allowParams =array (' Rows ', ' cols ', ' style ');
    The property array to be returned $params =array (); foreach ($allowParams as $key) {if (Isset ($this->textareaoptions[$key]) $params [$key]= $this-&GT;TEXTAREAOP
    tions[$key];
    $params [' name ']= $params [' id ']= $this->name;
  return $params; The Public Function getkeproperties () {$properties _key=array (' width ', ' height ', ' minwidth ', ') ' MinHeight ', ' Items ', ' nodisableitems ', ' filtermode ', ' htmltags ', ' Wellformatmode ', ' re Sizetype ', ' 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 ', ' fil Emanagerjson ', ' allowpreviewemoticons ', ' allowimageupload ', ' allowflashupload ', ' allowmediaupload ' , ' allowfileupload ', ' Allowfilemanager ', ' fontsizetable ', ' imagetabindex ', ' Formatuploadurl '
    , ' fullscreenshortcut ', ' extrafileuploadparams ',);
    The property array to be returned $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 (' ext.
    Keditor.keditor '); $root _path=keditor::getuploadpath (). '
    /'; $root _url=keditor::getuploadurl (). '
    /';
    Image 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); }///According to the path parameter, set each path and 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 ('/(. *?)
    [^\/]+\/$/', ' $ ', $current _dir_path);
    Echo Realpath ($root _path); Sort form, name or size or type $order = Empty ($_get[' order ')?
    ' Name ': Strtolower ($_get[' order '); Not allowed to use.
      Move to the previous level of directory if (Preg_match ('/\.\./', $current _path)) {echo ' Access is not allowed. ';
    Exit
      ///The last character is not/if (!preg_match ('/\/$/', $current _path)) {echo ' Parameter are not valid. ';
    Exit }//directory does not exist or is not a directory if (!file_exists ($current _path) | | |!is_dir ($current _path)) {echo ' directory does not exist. '
      ;
    Exit
    ///Traverse directory to get 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;/whether the folder $file _list[$i] [' has_file '] = (count (Scandi R ($file->getpath ())) > 2); Whether the folder contains files $file _list[$i][' filesize '] = 0; File size $file _list[$i] [' is_photo '] = false; Whether the picture $file _list[$i] [' filetype '] = ';
        File category, using 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 ();
      filename, containing the 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 root directory $result [' moveup_dir_path '] = $moveup _dir_path;
    The current directory relative to 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 ']): ' F
    Ile ';
      $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 ' => ' directory name is incorrect.)
      '));
    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 (' Error ' =>1, ' message ' => ' upload file size exceeds the limit.)
        '));
      Exit }//new filename $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 ' => ') upload file extension is not allowed extension Name. \ n only allow ". 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 the config/main.php file, set the location where the uploaded files are stored

' Params ' =>array (
    //This are used in Contacts page
    ' adminemail ' => ' webmaster@example.com ',
    ' Uploadpath ' => '/upload ',//Add this sentence, upload for the name of the file folder, define it yourself, here is the upload folder in the root directory

Set up action to receive files and browse Server files

The Public Function actions ()
{return
  array (
    ////) Add the following two sentences under the actions, add
    ' upload ' without the actions >array (' class ' => ' Application.extensions.KEditor.KEditorUpload '),
    ' Managejson ' =>array (' class ' = > ' application.extensions.KEditor.KEditorManage ')
  ;
}

Use in view

 <?php $this->widget (' ext.
    Keditor.keditor ', Array (' model ' => $model,//Incoming form model ' name ' => ' content ',//Set name ' Properties ' =>array ( Set the action ' Uploadjson ' => '/admin/default/upload ' to receive file uploads,//Set the action for browsing server files, both of which are configured above in/admin/default ' fi Lemanagerjson ' => '/admin/default/managejson ', ' Newlinetag ' => ' br ', ' Allowfilemanager ' =>true,///before adding JS: To
        Mark these are JS code ' 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 is used to set the size and style of the textarea, only rows, cols, and style are supported
Properties of each and JS set Kindeditor is the same, the above settings and the following JS set is consistent, Kindeditor original items can be set

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 ');
  }
});

For more information on YII-related content, readers who are interested in this site can view the topics: Introduction to the YII framework and summary of common skills, the summary of PHP's excellent development framework, the Smarty Template Primer tutorial, and the summary of PHP Operations Office documentation (including Word,excel, ACCESS,PPT), "Introduction to PHP object-oriented programming", "PHP string (String) Usage Summary", "Php+mysql Database Operations Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design based on the YII framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.