Who hasn’t faced this issue at least once? There are a lot of great online html editors out there (I really like CKEditor), each one with his solution for file and image upload and management. Often, it’s not free.
Sometime you don’t need a full-blown file manager. Sometime it’s simply better to give the user a limited set of choices, and prevent him from messing with: image resize, link to original version or downloadable file, styling, or using deprecated properties to align inside the surrounding text.
Let’s see how a cakephp rookie and javascript beginner used cake and the new ck editor api to implement this feature.
This is a 3 or 4 parts series (we’ll see) covering:
1) Attached files.
Inject your customized html in ckeditor (while preventing the user from providing broken links and such)
2) Insert images.
Not too many choices and options! Just implement in your image browser the ability to insert a small thumbnail -aligned left or right-, or a medium centered thumbnail. Oh, and with the link to the original image
3) and 4) Webservices. Use some webservice api to implement external media injection (i.e youtube clip, or flickr imageset). Well, it’s easier than it sounds.
– Basic filebrowser
All I want is a simple popup listing saved media/files and a way to insert a link for downloading the selected media- file in the current text inside a ck editor “textarea”. (well, it actually is a javascript object replacing the textarea, but let’s call it this way) .
In my content editing view (that calls the “file browser”) I have something like:
contents.ctp element:
- <?php
- $javascript->link('ckeditor/ckeditor', false); // started this with cakephp 1.2, so I’m still using javascript and ajax helper..
- ?>
-
- [..]
-
- <?php
-
- // [..]
- echo $html->link($html->image('icons_big/attachment.png',
- . __(' Files ', true),
-
- 'javascript:;',
-
-
-
- 'controller' => 'assets',
-
- 'action'=>'filebrowser',
-
- $Type.'Summary' // opener instance
-
- // $Type is the model name (this element is used by different controllers and actions), so this is the rendered form helper field name / id; i.e. NewsSummary, EventSummary, PageWholeContent
-
- )
-
- )."','_blank', 'toolbar=0,scrollbars=1,location=0,status=1,menubar=0,resizable=1,width=800,height=680'); return false;"
- ),
- null
- );
-
- // [..]
-
- ?>
-
- <script type="text/javascript">
-
- var editor = CKEDITOR.replace( "<?php echo $Type ?>Summary" , {customConfig : "/js/ckeditor/alternate_config.js", height : "150px"});
-
- CKEDITOR.add
-
- CKEDITOR.config.contentsCss = '<?php echo $html->webroot('/js/ckeditor/mycontents.css') ?>' ;
-
- </script>
We have our ck editor instance and the link for the popup.
—
The Model
Nothing special here, really. It depends on your needs. I have this Assets model which essentially sets up the configuration for the media and transfer behavior: I’m using David Persson’s Media Plugin (http://github.com/davidpersson/media) v 0.60 with some tweaks.
Any file upload / image resize code will work.
I like to store the file info in the database (and so Media plugin does). It’s not strictly mandatory for this proof of concept, but I’m using it because it’s much more easier (and fast) to use a single db table for searching saved files than scanning a tree in the filesystem.
—
The Controller
Here is a simplified version of the actual controller/action I’m using.
Just for reference here is the controller declaration and some properties. More on the basic settings later
assets_controller.php:
- <?php
-
- class AssetsController extends AppController {
-
- var $name = 'Assets';
-
- var $helpers = array("Html", "Form", "Javascript", "Ajax", "Time", "Text", "Utility", "Media.Medium", "Number");
-
-
- , 'order' => 'Asset.id DESC'
- );
-
- ?>
Here is the action that will handle the popup for searching / uploading / selecting files to embed.
Still nothing special here, just note the $opener_instance parameter: it’s used to identify the editor object calling the popup; it’s possible to have different instances of ck editor on the same page.
In AssetsController.php:
- <?php
-
- /**
- * file browser, renders the (filtered) popup list of files for the current site
- * @param <string> $opener_instance, name of the field / ckeditor instance
- * that will get the injected html for image display.
- * You can use multiple ck editor instances on teh same page
- */
-
- function admin_filebrowser($opener_instance,$type='all') {
-
- $type = $this->params['named']['type'];
-
- if($this->admin_index($type, true)) {
- $this->set('opener_instance', $opener_instance);
- $this->render('admin_filebrowser', 'basic');
- }
-
- }
-
- ?>
The action just passes the needed values to the admin_index function and sets the variables for the view.
Admin_index is our work horse. It’s both a normal action in the usual admin screen, and a function returning the filtered/paginated file records to our popup filebrowser action. (and imagebrowser too, but this is another post).
In assets_controller.php:
- <?php
-
- /**
- * function admin_index
- *
- * displays a filtered (by type, search terms, site) lists of files;
- *
- * used as an action for assets management, or returns data for
- * file/imagebrowser used in ckeditor
- *
- *
- * @param <string> $type - type of media
- * @param <boolean> $return false, it's the normal asset controller action,
- * true, sets data for the popup ckeditor "fielbrowser" and skips
- * admin_index view rendering
- * @return <boolean>
- */
-
- function admin_index($type = null, $return = null) {
-
- $this->Asset->recursive = 0;
-
- // [..]
- // all logic for filtering records
-
- $this->Asset->contain($this->defaultContain);
-
- $assets = $this->paginate(null,$filter);
-
- $assets = Sanitize::clean($assets);
-
- $this->set('assets', $assets);
-
- //[..]
- // if it's called by imagebrowser or filebrowser
-
- if($return) return true;
- // else render index view..
-
- }
- ?>
I’ve stripped out the not relevant parts (the code for preparing filter / pagination). What is left is a simple get that data function. It’s the view where all the magic happens.. well, it’s really simple.
I didn’t even look deeply into the ck editor javascript api or developer guide. To keep it as simple as possible I only needed a function for inserting formatted html into the current ck editor “textarea”.
In admin_filebrowser.ctp:
- <script type="text/javascript">
- <!--
- function InsertHTML(passed)
- {
- //get the correct editor object instance (in my case, i.e. if news controller: NewsSummary or
- //NewsWholeContent, if events controller -> EventsSummary.. etc. )
-
- var oEditor = opener.CKEDITOR.instances.<?php echo $opener_instance ?>;
-
- // Check the active editing mode.
-
- if ( oEditor.mode == 'wysiwyg' )
- {
-
- // Insert the desired HTML.
- oEditor.insertHtml( passed ) ;
-
- }
- else
- alert('<?php echo __('You must be on WYSIWYG mode!', true); ?>') ;
-
- window.close();
- }
- -->
- </script>
That’s the point. Calling this javascript snippet will insert the desired html in the correct ck editor box. Now all we need to do is to generate the correct html (filling the js “passed” parameter for every file).
(Still stripping all the non relevant code –pagination filtering, file data display based on file type, thumbnail or type icon / bells and whistles)
In admin_filebrowser.ctp:
- <table>
- <?php
- foreach ($assets as $asset):
- ?>
- <tr>
- <td>
- </td>
- <td>
- <?php
- // HERE WE ARE
- // generated HTML to be embedded in CKeditor
- $insert = $html->link(
- $html->image('icons_small/attachment.png',
- array('width' => 14, 'height' => 14, 'align' => 'absmiddle',
- 'alt' => __('attached file', true),
- 'title' => __('attached file', true),'border' => 0
- )
- ) . ' ' . __( $asset['Asset']['name'], true),
- array('controller' => 'assets', 'action' => 'show',$asset['Asset']['id'], 'admin' => false),
- array('escape' => false),null,false
- );
-
- //then the javascript lnk that will inject the generated html in ck editor
-
- echo $html->link(
- $html->image('icons/attachment.png', array('alt' => 'allega', 'title' => 'allega', 'border' => 0, 'align' => 'absmiddle')) .
- $html->image('icons/link.png', array('alt' => 'allega', 'title' => 'allega', 'border' => 0, 'align' => 'absmiddle')) .
- __('Embed this file', true),
-
- //'javascript:;',
- 'javascript:InsertHTML(\''. $insert .'\');',
-
- array('escape' => false,
-
- //'onclick' => 'javascript:InsertHTML(\''. $insert .'\');'
- ),
- null, false
- );
- ?>
-
- </td>
- </tr>
- <?php endforeach; ?>
- </table>
That’s it. It’s all we need to inject what we want in the editor. In this case, a link showing the file name and pointing to the show action (an action that uses cakephp media view to display / download the file)
assets_controller .php
- <?php
- function show ($id) {
- $this->view = 'Media';
- $this->Asset->recursive = -1;
-
-
- //ClassRegistry::init('Inflector');
-
-
- $download = false;
-
- if($asset['Asset']['medium_type'] != 'img') $download = true;
-
- 'id' => $asset['Asset']['basename'],
- 'name' => $name,
- 'download' => $download,
- 'path' => 'media' . DS . $asset['Asset']['dirname'] . DS,
- 'cache' => true
- );
-
- $this->set($params);
-
- $this->render();
- }
-
- ?>
On the image is a screenshot of the actual file popup.
(yes, I need a designer, I really do. But I have no money to hire one, and this is not the point of this article. Well, the template of this blog itself is made with artisteer, in 30 minutes. Be kind)
If someone is interested I’ll post the whole relevant code. The app will eventually be released as open source (when it’s ready, cleaned code, and I’ll figure out which license to use).
Stay tuned for the next issues on this series (featuring image, youtube and flickr browser)
And, as always: I’m not a cakephp master – surely there are better ways and cleaner code to do this – suggestions are welcome.