4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2010, StatusNet, Inc.
7 * Use TinyMCE library to allow rich text editing in the browser
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Affero General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Affero General Public License for more details.
21 * You should have received a copy of the GNU Affero General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 * @author Evan Prodromou <evan@status.net>
27 * @copyright 2010 StatusNet, Inc.
28 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
29 * @link http://status.net/
31 if (!defined('STATUSNET')) {
32 // This check helps protect against security problems;
33 // your code file can't be executed directly from the web.
38 * Use TinyMCE library to allow rich text editing in the browser
40 * Converts the notice form in browser to a rich-text editor.
44 * @author Evan Prodromou <evan@status.net>
45 * @copyright 2010 StatusNet, Inc.
46 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
47 * @link http://status.net/
49 class TinyMCEPlugin extends Plugin
53 // By default, TinyMCE editor will be available to all users.
54 // With restricted on, only users who have been granted the
55 // "richedit" role get it.
56 public $restricted = false;
58 function onEndShowScripts($action)
60 if (common_logged_in() && $this->isAllowedRichEdit()) {
61 $action->script(common_path('plugins/TinyMCE/js/jquery.tinymce.js'));
62 $action->inlineScript($this->_inlineScript());
68 function onEndShowStyles($action)
70 if ($this->isAllowedRichEdit()) {
71 $action->style('span#notice_data-text_container, span#notice_data-text_parent { float: left }');
76 function onPluginVersion(&$versions)
78 $versions[] = array('name' => 'TinyMCE',
79 'version' => STATUSNET_VERSION,
80 'author' => 'Evan Prodromou',
81 'homepage' => 'http://status.net/wiki/Plugin:TinyMCE',
83 _m('Use TinyMCE library to allow rich text editing in the browser.'));
88 * Sanitize HTML input and strip out potentially dangerous bits.
90 * @param string $raw HTML
93 private function sanitizeHtml($raw)
95 require_once INSTALLDIR . '/extlib/htmLawed/htmLawed.php';
97 $config = array('safe' => 1,
98 'deny_attribute' => 'id,style,on*');
100 return htmLawed($raw, $config);
104 * Strip HTML to plaintext string
106 * @param string $html HTML
107 * @return string plaintext, single line
109 private function stripHtml($html)
111 return str_replace("\n", " ", html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8'));
115 * Hook for new-notice form processing to take our HTML goodies;
116 * won't affect API posting etc.
118 * @param NewNoticeAction $action
120 * @param string $content
121 * @param array $options
122 * @return boolean hook return
124 function onStartSaveNewNoticeWeb($action, $user, &$content, &$options)
126 if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
127 $html = $this->sanitizeHtml($content);
128 $options['rendered'] = $html;
129 $content = $this->stripHtml($html);
135 * Hook for new-notice form processing to process file upload appending...
137 * @param NewNoticeAction $action
138 * @param MediaFile $media
139 * @param string $content
140 * @param array $options
141 * @return boolean hook return
143 function onStartSaveNewNoticeAppendAttachment($action, $media, &$content, &$options)
145 if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
146 // See if we've got a placeholder inline image; if so, fill it!
147 $dom = new DOMDocument();
149 if ($dom->loadHTML($options['rendered'])) {
150 $imgs = $dom->getElementsByTagName('img');
151 foreach ($imgs as $img) {
152 if (preg_match('/(^| )placeholder( |$)/', $img->getAttribute('class'))) {
153 // Create a link to the attachment page...
154 $this->formatAttachment($img, $media);
157 $options['rendered'] = $this->saveHtml($dom);
160 // The regular code will append the short URL to the plaintext content.
161 // Carry on and let it through...
167 * Format the attachment placeholder img with the final version.
169 * @param DOMElement $img
170 * @param MediaFile $media
172 private function formatAttachment($img, $media)
174 $parent = $img->parentNode;
175 $dom = $img->ownerDocument;
177 $link = $dom->createElement('a');
178 $link->setAttribute('href', $media->fileurl);
179 $link->setAttribute('title', File::url($media->filename));
181 if ($this->isEmbeddable($media)) {
182 // Fix the the <img> attributes and wrap the link around it...
183 $this->insertImage($img, $media);
184 $parent->replaceChild($link, $img); //it dies in here?!
185 $link->appendChild($img);
187 // Not an image? Replace it with a text link.
188 $link->setAttribute('rel', 'external');
189 $link->setAttribute('class', 'attachment');
190 $link->setAttribute('id', 'attachment-' . $media->fileRecord->id);
191 $text = $dom->createTextNode($media->shortUrl());
192 $link->appendChild($text);
193 $parent->replaceChild($link, $img);
198 * Is this media file a type we can display inline?
200 * @param MediaFile $media
203 private function isEmbeddable($media)
205 $showable = array('image/png',
208 return in_array($media->mimetype, $showable);
212 * Rewrite and resize a placeholder image element to match the uploaded
213 * file. If the holder is smaller than the file, the file is scaled to fit
214 * with correct aspect ratio (but will be loaded at full resolution).
216 * @param DOMElement $img
217 * @param MediaFile $media
219 private function insertImage($img, $media)
221 $img->setAttribute('src', $media->fileRecord->url);
223 $holderWidth = intval($img->getAttribute('width'));
224 $holderHeight = intval($img->getAttribute('height'));
226 $path = File::path($media->filename);
227 $imgInfo = getimagesize($path);
230 $origWidth = $imgInfo[0];
231 $origHeight = $imgInfo[1];
233 list($width, $height) = $this->sizeBox(
234 $origWidth, $origHeight,
235 $holderWidth, $holderHeight);
237 $img->setAttribute('width', $width);
238 $img->setAttribute('height', $height);
244 * @param int $origWidth
245 * @param int $origHeight
246 * @param int $holderWidth
247 * @param int $holderHeight
248 * @return array($width, $height)
250 private function sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight)
252 $holderAspect = $holderWidth / $holderHeight;
253 $origAspect = $origWidth / $origHeight;
254 if ($origAspect >= 1.0) {
256 if ($origWidth > $holderWidth) {
257 return array($holderWidth, intval($holderWidth / $origAspect));
259 return array($origWidth, $origHeight);
262 if ($origHeight > $holderHeight) {
263 return array(intval($holderWidth * $origAspect), $holderHeight);
265 return array($origWidth, $origHeight);
270 private function saveHtml($dom)
272 $html = $dom->saveHTML();
273 // hack to remove surrounding crap added to the dom
274 // all we wanted was a fragment
275 $stripped = preg_replace('/^.*<body[^>]*>(.*)<\/body.*$/is', '$1', $html);
279 function _inlineScript()
281 $path = common_path('plugins/TinyMCE/js/tiny_mce.js');
282 $placeholder = common_path('plugins/TinyMCE/icons/placeholder.png');
284 // Note: the normal on-submit triggering to save data from
285 // the HTML editor into the textarea doesn't play well with
286 // our AJAX form submission. Manually moving it to trigger
287 // on our send button click.
288 $scr = <<<END_OF_SCRIPT
289 $().ready(function() {
290 var noticeForm = $('#form_notice');
291 $('textarea#notice_data-text').tinymce({
292 script_url : '{$path}',
295 plugins : "paste,fullscreen,autoresize,inlinepopups,tabfocus,linkautodetect",
296 theme_advanced_buttons1 : "bold,italic,strikethrough,|,undo,redo,|,link,unlink,image,|,fullscreen",
297 theme_advanced_buttons2 : "",
298 theme_advanced_buttons3 : "",
299 add_form_submit_trigger : false,
300 theme_advanced_resizing : true,
301 tabfocus_elements: ":prev,:next",
302 setup: function(ed) {
303 noticeForm.append('<input type="hidden" name="richedit" value="1">');
305 $('#notice_action-submit').click(function() {
306 tinymce.triggerSave();
309 var origCounter = SN.U.CharacterCount;
310 SN.U.CharacterCount = function(form) {
311 var text = $(ed.getDoc()).text();
314 ed.onKeyUp.add(function (ed, e) {
315 SN.U.Counter(noticeForm);
318 $('#'+SN.C.S.NoticeDataAttach).change(function() {
319 var img = '<img src="{$placeholder}" class="placeholder" width="320" height="240">';
320 var html = tinyMCE.activeEditor.getContent();
321 ed.setContent(html + img);
332 * Does the current user have permission to use the rich-text editor?
333 * Always true unless the plugin's "restricted" setting is on, in which
334 * case it's limited to users with the "richedit" role.
336 * @fixme make that more sanely configurable :)
340 private function isAllowedRichEdit()
342 if ($this->restricted) {
343 $user = common_current_user();
344 return !empty($user) && $user->hasRole('richedit');