Ckeditor – not allow posting of images from the local harddrive

Within the CKEditor you can also add on to the prototypes that allow more control of what is allowed on your website.

Sometimes you do not want to allow the user to copy and paste local files to the CKEditor so this is what I done to remove the file:// from within the img tag within the copy and paste with using the CKEditor htmlDataProcessor group of functions, in this case the ‘toHtml’ function which is called when the user pastes any content into the CKEditor window. All I am doing it using the regular expression to search for the <img src=”file .. and replace with a <mg tag> which when they double click on that it will open the CKEditor’s image browser (which you can include a upload part to it as well 🙂 )

CKEDITOR.htmlDataProcessor.prototype.toHtml = function( data, fixForBody )
    return data.replace(/\<img src=\"file:([^\>])*\>/ig,"<img title=\"Please use the Media/Image uploader because can not show files on your harddrive\" alt=\"Please use the Media/Image uploader because can not show files on your harddrive\"/>");

It was very helpful for me.

Javascript {} []

Someone asked me what is the difference between {} and [] within javascript.

Basically the difference is one is a key => value pair like PHP ‘{}’, and the other is just a pure array of values ‘[]’.

Here is the code.

var simplearray = ["genux","linux"];
var keyvaluearray = {"name" : "genux", "OS" : "linux"};

To access the different values, since the simple array is index by numbers 0 onwards you use the [x] notation, and the key value array you can reference the value by the name of the key like in object orientated way.


Delete object from array within javascript

Someone asked me whilst doing a job how to delete parts of a array within javascript, so just like other object oriented languages, you can have a array of data objects and each one can be accessible and removable. To achieve this with javascript you use the delete method as below.

var myArray = new Array();
myArray[0] = "first value";
myArray[1] = "second value";
// and to delete the second value
delete myArray[1];

Adding floats together with commas and decimal places

Someone contacted me about adding some numbers together with comma’s and dots within there values, here is the email via the contact me page.

“Please I need a javascript code that can enable me add two or more numbers containing dot(.) and/or comma (,) together. For example, 122.34 + 233.56. Or/And 233,239.34 + 323,322.44. Thanks in advance.”

Here is the code that will accomplish the request.

<script type="text/javascript" >
       function load()
               var value1="233,122.34";
               var value2="233.56";
<body onload="load()">

The main part is the parseFloat and replacing the “,” with nothing “” to remove the none float characters via the object replace method.

CKEditor – auto save

A follow on from the previous post CKEditor custom dialog you can auto save the content with sending a AJAX call to another page that will save the content and also give back a updated time of that content saved.

I created a function called autosave(), that will call itself every 20 seconds (20000 milliseconds). This will get the data (getData()) from the CKEditor instance called content and then go some JQuery to do the actual AJAX function which in-turn calls the url autosave.php (can be any backend page that will deal with saving the data) and once the backend page has completed then update the HTML element with the ID of lastsavetime to the new time that is returned from the webpage.

function autosave()
   var t = setTimeout("autosave()", 20000);
  var content = escape(CKEDITOR.instances.content.getData());
   if (content.length > 0)
           type: "POST",
           url: "autosave.php?method=saveCKEditor",
           data : "content="+content,
           cache: false,
           success: function(message)
               $("#lastsavetime").empty().append("Last saved : "+message);
}); ";

CKEditor – custom dialog

The CKEditor is a great WYSIWYG and the best thing is that you are able to customize the interface to have buttons on the toolbars, here is a way that I created a custom button with custom image attached to it.

The editor is created with

var editor = CKEDITOR.replace( 'Content');

So from now on in the variable editor is linked to the CKEditor instance, to setup the plugins to load when the CKEditor is created you call the pluginsLoaded function

 editor.on( 'pluginsLoaded', function( ev )
           if ( !CKEDITOR.dialog.exists( 'statisticsDialog' ) )
                 CKEDITOR.dialog.add( 'statisticsDialog','/statistics.js');
           // Register the command used to open the dialog.
           editor.addCommand( 'statisticsAddCmd', new CKEDITOR.dialogCommand('statisticsDialog' ) );
           editor.ui.addButton( 'Statistics',
                        label : 'Statistic',
                        command : 'statisticsAddCmd',
                        icon : '/statistics_small.png',
                    } );

The first part will check to make sure that there is not dialog already created with the same name, and if not then load the javascript file that is the custom built dialog. The second part is adding the command (the button clicked) to be linked to the custom dialog, and the third part is to add the actual button to the user interface (editor.ui). The addButton function links to the command to bring up the custom dialog.

Here is the custom dialog code that will be called when the user interface button is clicked.

CKEDITOR.dialog.add( 'statisticsDialog', function( editor )
      // Load data asynchronously.
       return {
               title : 'Pick a statistic',
               minWidth : 400,
               minHeight : 200,
               onOk : insertOntoEditor,
               contents : [
                               id : 'tab1',
                               label : 'First Tab',
                               title : 'First Tab',
                               elements :[
                                       {  id : 'graphselect',
                                               type : 'select',
                                               items : [ ["option1", "link to image"] ] ,
} );

The dialog, will load up a screen and have a one drop down box that will allow the user to choose from the options (will you need to insert more options, or dynamic created options if you wanted to) and once the OK button is clicked (onOK) it will call this function below

function insertOntoEditor()
       elem = this.getContentElement('tab1','graphselect');
       value = elem.getValue();
       if (value != -1)
               var writer = new CKEDITOR.htmlWriter();
               var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<img src="http://'+document.domain+elem.getValue()+'"/>' );
               fragment.writeHtml( writer )
               // need to wrap up the graph image insertion into the ckeditor

This will basically insert some code into the CKEditor from the drop down box, the “link to image” you will need to insert a link for the insertion.

CKEditor – Custom upload dialog

The great WYSIWYG editor called CKEditor allows you to do a custom file upload, so that you can handle where the file is stored and also you can do your database extra inserts for example.

To start with you have to tell the CKEditor where to post the file uploaded to custom built page

var editor = CKEDITOR.replace( 'Content',{ filebrowserUploadUrl :'/custom.imageuploader.php'});

Where the custom.imageuploader.php is the actual php page that will deal with the custom page, can be done in any other language if required. In the above code, the ‘Content’ is the textarea to change to a CKEditor WYSIWYG.

Here is a basic php page that you will need to alter to store the $_FILES[“upload”] into the place where you want to store and do any database code to link to the resource that you are uploading, but the bit underneath that you need to have, this will tell the CKEditor what to do after your PHP code has stored the file, the CKEditoFuncName, is required (but passed in) to tell the CKEditor what function to call after the upload has happened, the $wherestorage, is where the actual file is so that the WYSIWYG can show the image and any $message that may help the CKEditor user for any error reports.

// the files are stored within the upload part of the $_FILES 
<script type="text/javascript">
   <?php echo $_REQUEST["CKEditorFuncNum"].",\"".$wherestorage."\",\"".$message."\"";?>