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.
42 * FIXME: this plugin DOES NOT load its static files from the configured
43 * plugin server if one exists. There are cross-server permissions errors
44 * if you try to do that (something about window.tinymce).
48 * @author Evan Prodromou <evan@status.net>
49 * @copyright 2010 StatusNet, Inc.
50 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
51 * @link http://status.net/
53 class TinyMCEPlugin extends Plugin
57 // By default, TinyMCE editor will be available to all users.
58 // With restricted on, only users who have been granted the
59 // "richedit" role get it.
60 public $restricted = false;
62 function onEndShowScripts($action)
64 if (common_logged_in() && $this->isAllowedRichEdit()) {
65 $action->script(common_path('plugins/TinyMCE/js/jquery.tinymce.js'));
66 $action->inlineScript($this->_inlineScript());
72 function onEndShowStyles($action)
74 if ($this->isAllowedRichEdit()) {
75 $action->style('span#notice_data-text_container, span#notice_data-text_parent { float: left }');
80 function onPluginVersion(&$versions)
82 $versions[] = array('name' => 'TinyMCE',
83 'version' => STATUSNET_VERSION,
84 'author' => 'Evan Prodromou',
85 'homepage' => 'http://status.net/wiki/Plugin:TinyMCE',
87 _m('Use TinyMCE library to allow rich text editing in the browser.'));
92 * Sanitize HTML input and strip out potentially dangerous bits.
94 * @param string $raw HTML
97 private function sanitizeHtml($raw)
99 require_once INSTALLDIR . '/extlib/htmLawed/htmLawed.php';
101 $config = array('safe' => 1,
102 'deny_attribute' => 'id,style,on*');
104 return htmLawed($raw, $config);
108 * Strip HTML to plaintext string
110 * @param string $html HTML
111 * @return string plaintext, single line
113 private function stripHtml($html)
115 return str_replace("\n", " ", html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8'));
119 * Hook for new-notice form processing to take our HTML goodies;
120 * won't affect API posting etc.
122 * @param NewNoticeAction $action
124 * @param string $content
125 * @param array $options
126 * @return boolean hook return
128 function onStartSaveNewNoticeWeb($action, $user, &$content, &$options)
130 if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
131 $html = $this->sanitizeHtml($content);
132 $options['rendered'] = $html;
133 $content = $this->stripHtml($html);
139 * Hook for new-notice form processing to process file upload appending...
141 * @param NewNoticeAction $action
142 * @param MediaFile $media
143 * @param string $content
144 * @param array $options
145 * @return boolean hook return
147 function onStartSaveNewNoticeAppendAttachment($action, $media, &$content, &$options)
149 if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
150 // See if we've got a placeholder inline image; if so, fill it!
151 $dom = new DOMDocument();
153 if ($dom->loadHTML($options['rendered'])) {
154 $imgs = $dom->getElementsByTagName('img');
155 foreach ($imgs as $img) {
156 if (preg_match('/(^| )placeholder( |$)/', $img->getAttribute('class'))) {
157 // Create a link to the attachment page...
158 $this->formatAttachment($img, $media);
161 $options['rendered'] = $this->saveHtml($dom);
164 // The regular code will append the short URL to the plaintext content.
165 // Carry on and let it through...
171 * Format the attachment placeholder img with the final version.
173 * @param DOMElement $img
174 * @param MediaFile $media
176 private function formatAttachment($img, $media)
178 $parent = $img->parentNode;
179 $dom = $img->ownerDocument;
181 $link = $dom->createElement('a');
182 $link->setAttribute('href', $media->fileurl);
183 $link->setAttribute('title', File::url($media->filename));
185 if ($this->isEmbeddable($media)) {
186 // Fix the the <img> attributes and wrap the link around it...
187 $this->insertImage($img, $media);
188 $parent->replaceChild($link, $img); //it dies in here?!
189 $link->appendChild($img);
191 // Not an image? Replace it with a text link.
192 $link->setAttribute('rel', 'external');
193 $link->setAttribute('class', 'attachment');
194 $link->setAttribute('id', 'attachment-' . $media->fileRecord->id);
195 $text = $dom->createTextNode($media->shortUrl());
196 $link->appendChild($text);
197 $parent->replaceChild($link, $img);
202 * Is this media file a type we can display inline?
204 * @param MediaFile $media
207 private function isEmbeddable($media)
209 $showable = array('image/png',
212 return in_array($media->mimetype, $showable);
216 * Rewrite and resize a placeholder image element to match the uploaded
217 * file. If the holder is smaller than the file, the file is scaled to fit
218 * with correct aspect ratio (but will be loaded at full resolution).
220 * @param DOMElement $img
221 * @param MediaFile $media
223 private function insertImage($img, $media)
225 $img->setAttribute('src', $media->fileRecord->url);
227 $holderWidth = intval($img->getAttribute('width'));
228 $holderHeight = intval($img->getAttribute('height'));
230 $path = File::path($media->filename);
231 $imgInfo = getimagesize($path);
234 $origWidth = $imgInfo[0];
235 $origHeight = $imgInfo[1];
237 list($width, $height) = $this->sizeBox(
238 $origWidth, $origHeight,
239 $holderWidth, $holderHeight);
241 $img->setAttribute('width', $width);
242 $img->setAttribute('height', $height);
248 * @param int $origWidth
249 * @param int $origHeight
250 * @param int $holderWidth
251 * @param int $holderHeight
252 * @return array($width, $height)
254 private function sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight)
256 $holderAspect = $holderWidth / $holderHeight;
257 $origAspect = $origWidth / $origHeight;
258 if ($origAspect >= 1.0) {
260 if ($origWidth > $holderWidth) {
261 return array($holderWidth, intval($holderWidth / $origAspect));
263 return array($origWidth, $origHeight);
266 if ($origHeight > $holderHeight) {
267 return array(intval($holderWidth * $origAspect), $holderHeight);
269 return array($origWidth, $origHeight);
274 private function saveHtml($dom)
276 $html = $dom->saveHTML();
277 // hack to remove surrounding crap added to the dom
278 // all we wanted was a fragment
279 $stripped = preg_replace('/^.*<body[^>]*>(.*)<\/body.*$/is', '$1', $html);
283 function _inlineScript()
285 $path = common_path('plugins/TinyMCE/js/tiny_mce.js');
286 $placeholder = common_path('plugins/TinyMCE/icons/placeholder.png');
288 // Note: the normal on-submit triggering to save data from
289 // the HTML editor into the textarea doesn't play well with
290 // our AJAX form submission. Manually moving it to trigger
291 // on our send button click.
292 $scr = <<<END_OF_SCRIPT
294 var origInit = SN.Init.NoticeFormSetup;
295 SN.Init.NoticeFormSetup = function(form) {
297 var noticeForm = form;
298 var textarea = form.find('.notice_data-text');
299 if (textarea.length == 0) return;
301 script_url : '{$path}',
304 plugins : "paste,fullscreen,autoresize,inlinepopups,tabfocus,linkautodetect",
305 theme_advanced_buttons1 : "bold,italic,strikethrough,|,undo,redo,|,link,unlink,image,|,fullscreen",
306 theme_advanced_buttons2 : "",
307 theme_advanced_buttons3 : "",
308 add_form_submit_trigger : false,
309 theme_advanced_resizing : true,
310 tabfocus_elements: ":prev,:next",
311 setup: function(ed) {
312 noticeForm.append('<input type="hidden" name="richedit" value="1">');
314 form.find('.submit:first').click(function() {
315 tinymce.triggerSave();
318 var origCounter = SN.U.CharacterCount;
319 SN.U.CharacterCount = function(form) {
320 var text = $(ed.getDoc()).text();
323 ed.onKeyUp.add(function (ed, e) {
324 SN.U.Counter(noticeForm);
327 form.find('input[type=file]').change(function() {
328 var img = '<img src="{$placeholder}" class="placeholder" width="320" height="240">';
329 var html = tinyMCE.activeEditor.getContent();
330 ed.setContent(html + img);
342 * Does the current user have permission to use the rich-text editor?
343 * Always true unless the plugin's "restricted" setting is on, in which
344 * case it's limited to users with the "richedit" role.
346 * @fixme make that more sanely configurable :)
350 private function isAllowedRichEdit()
352 if ($this->restricted) {
353 $user = common_current_user();
354 return !empty($user) && $user->hasRole('richedit');