How can you integrate a custom file browser/uploader with CKEditor?
Start by registering your custom browser/uploader when you instantiate CKEditor. You can designate different URLs for an image browser vs. a general file browser.
<script type="text/javascript">
CKEDITOR.replace('content', {
filebrowserBrowseUrl : '/browser/browse/type/all',
filebrowserUploadUrl : '/browser/upload/type/all',
filebrowserImageBrowseUrl : '/browser/browse/type/image',
filebrowserImageUploadUrl : '/browser/upload/type/image',
filebrowserWindowWidth : 800,
filebrowserWindowHeight : 500
});
</script>
Your custom code will receive a GET parameter called CKEditorFuncNum. Save it - that's your callback function. Let's say you put it into $callback
.
When someone selects a file, run this JavaScript to inform CKEditor which file was selected:
window.opener.CKEDITOR.tools.callFunction(<?php echo $callback; ?>,url)
Where "url" is the URL of the file they picked. An optional third parameter can be text that you want displayed in a standard alert dialog, such as "illegal file" or something. Set url to an empty string if the third parameter is an error message.
CKEditor's "upload" tab will submit a file in the field "upload" - in PHP, that goes to $_FILES['upload']. What CKEditor wants your server to output is a complete JavaScript block:
$output = '<html><body><script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$url.'","'.$msg.'");</script></body></html>';
echo $output;
Again, you need to give it that callback parameter, the URL of the file, and optionally a message. If the message is an empty string, nothing will display; if the message is an error, then url should be an empty string.
The official CKEditor documentation is incomplete on all this, but if you follow the above it'll work like a champ.
I just went through the learning process myself. I figured it out, but I agree the documentation is written in a way that was sorta intimidating to me. The big "aha" moment for me was understanding that for browsing, all CKeditor does is open a new window and provide a few parameters in the url. It allows you to add additional parameters but be advised you will need to use encodeURIComponent() on your values.
I call the browser and the uploader with
CKEDITOR.replace( 'body',
{
filebrowserBrowseUrl: 'browse.php?type=Images&dir=' +
encodeURIComponent('content/images'),
filebrowserUploadUrl: 'upload.php?type=Files&dir=' +
encodeURIComponent('content/images')
}
For the browser, in the open window (browse.php) you use php & js to supply a list of choices and then upon your supplied onclick handler, you call a CKeditor function with two arguments, the url/path to the selected image and CKEditorFuncNum supplied by CKeditor in the url:
function myOnclickHandler(){
//..
window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, pathToImage);
window.close();
}
Simarly, the uploader simply calls the url you supply, e.g., upload.php, and again supplies $_GET['CKEditorFuncNum']. The target is an iframe so, after you save the file from $_FILES you pass your feedback to CKeditor as thus:
$funcNum = $_GET['CKEditorFuncNum'];
exit("<script>window.parent.CKEDITOR.tools.callFunction($funcNum, '$filePath', '$errorMessage');</script>");
Below is a simple to understand custom browser script. While it does not allow users to navigate around in the server, it does allow you to indicate which directory to pull image files from when calling the browser.
It's all rather basic coding so it should work in all relatively modern browsers.
CKeditor merely opens a new window with the url provided
/*
in CKeditor **use encodeURIComponent()** to add dir param to the filebrowserBrowseUrl property
Replace content/images with directory where your images are housed.
*/
CKEDITOR.replace( 'editor1', {
filebrowserBrowseUrl: '**browse.php**?type=Images&dir=' + encodeURIComponent('content/images'),
filebrowserUploadUrl: 'upload.php?type=Files&dir=' + encodeURIComponent('content/images')
});
// ========= complete code below for browse.php
<?php
header("Content-Type: text/html; charset=utf-8\n");
header("Cache-Control: no-cache, must-revalidate\n");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
// e-z params
$dim = 150; /* image displays proportionally within this square dimension ) */
$cols = 4; /* thumbnails per row */
$thumIndicator = '_th'; /* e.g., *image123_th.jpg*) -> if not using thumbNails then use empty string */
?>
<!DOCTYPE html>
<html>
<head>
<title>browse file</title>
<meta charset="utf-8">
<style>
html,
body {padding:0; margin:0; background:black; }
table {width:100%; border-spacing:15px; }
td {text-align:center; padding:5px; background:#181818; }
img {border:5px solid #303030; padding:0; verticle-align: middle;}
img:hover { border-color:blue; cursor:pointer; }
</style>
</head>
<body>
<table>
<?php
$dir = $_GET['dir'];
$dir = rtrim($dir, '/'); // the script will add the ending slash when appropriate
$files = scandir($dir);
$images = array();
foreach($files as $file){
// filter for thumbNail image files (use an empty string for $thumIndicator if not using thumbnails )
if( !preg_match('/'. $thumIndicator .'\.(jpg|jpeg|png|gif)$/i', $file) )
continue;
$thumbSrc = $dir . '/' . $file;
$fileBaseName = str_replace('_th.','.',$file);
$image_info = getimagesize($thumbSrc);
$_w = $image_info[0];
$_h = $image_info[1];
if( $_w > $_h ) { // $a is the longer side and $b is the shorter side
$a = $_w;
$b = $_h;
} else {
$a = $_h;
$b = $_w;
}
$pct = $b / $a; // the shorter sides relationship to the longer side
if( $a > $dim )
$a = $dim; // limit the longer side to the dimension specified
$b = (int)($a * $pct); // calculate the shorter side
$width = $_w > $_h ? $a : $b;
$height = $_w > $_h ? $b : $a;
// produce an image tag
$str = sprintf('<img src="%s" width="%d" height="%d" title="%s" alt="">',
$thumbSrc,
$width,
$height,
$fileBaseName
);
// save image tags in an array
$images[] = str_replace("'", "\\'", $str); // an unescaped apostrophe would break js
}
$numRows = floor( count($images) / $cols );
// if there are any images left over then add another row
if( count($images) % $cols != 0 )
$numRows++;
// produce the correct number of table rows with empty cells
for($i=0; $i<$numRows; $i++)
echo "\t<tr>" . implode('', array_fill(0, $cols, '<td></td>')) . "</tr>\n\n";
?>
</table>
<script>
// make a js array from the php array
images = [
<?php
foreach( $images as $v)
echo sprintf("\t'%s',\n", $v);
?>];
tbl = document.getElementsByTagName('table')[0];
td = tbl.getElementsByTagName('td');
// fill the empty table cells with data
for(var i=0; i < images.length; i++)
td[i].innerHTML = images[i];
// event handler to place clicked image into CKeditor
tbl.onclick =
function(e) {
var tgt = e.target || event.srcElement,
url;
if( tgt.nodeName != 'IMG' )
return;
url = '<?php echo $dir;?>' + '/' + tgt.title;
this.onclick = null;
window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, url);
window.close();
}
</script>
</body>
</html>
I have posted one small tutorial about integrating the FileBrowser available in old FCKEditor into CKEditor.
http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/
It contains step by step instructions for doing so and its pretty simple. I hope anybody in search of this will find this tutorial helpful.