3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
6 * Use TinyMCE library to allow rich text editing in the browser
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Affero General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Affero General Public License for more details.
20 * You should have received a copy of the GNU Affero General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 * @author Evan Prodromou <evan@status.net>
26 * @copyright 2010 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28 * @link http://status.net/
30 if (!defined('STATUSNET')) {
31 // This check helps protect against security problems;
32 // your code file can't be executed directly from the web.
37 * Use TinyMCE library to allow rich text editing in the browser
39 * Converts the notice form in browser to a rich-text editor.
41 * FIXME: this plugin DOES NOT load its static files from the configured
42 * plugin server if one exists. There are cross-server permissions errors
43 * if you try to do that (something about window.tinymce).
47 * @author Evan Prodromou <evan@status.net>
48 * @copyright 2010 StatusNet, Inc.
49 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
50 * @link http://status.net/
52 class TinyMCEPlugin extends Plugin
56 // By default, TinyMCE editor will be available to all users.
57 // With restricted on, only users who have been granted the
58 // "richedit" role get it.
59 public $restricted = false;
61 function onEndShowScripts($action)
63 if (common_logged_in() && $this->isAllowedRichEdit()) {
64 $action->script(common_path('plugins/TinyMCE/js/jquery.tinymce.js'));
65 $action->inlineScript($this->_inlineScript());
71 function onEndShowStyles($action)
73 if ($this->isAllowedRichEdit()) {
74 $action->style('span#notice_data-text_container, span#notice_data-text_parent { float: left }');
79 function onPluginVersion(array &$versions)
81 $versions[] = array('name' => 'TinyMCE',
82 'version' => GNUSOCIAL_VERSION,
83 'author' => 'Evan Prodromou',
84 'homepage' => 'http://status.net/wiki/Plugin:TinyMCE',
86 // TRANS: Plugin description.
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 * Hook for new-notice form processing to take our HTML goodies;
109 * won't affect API posting etc.
111 * @param NewNoticeAction $action
113 * @param string $content
114 * @param array $options
115 * @return boolean hook return
117 function onStartSaveNewNoticeWeb($action, $user, &$content, &$options)
119 if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
120 $html = $this->sanitizeHtml($content);
121 $options['rendered'] = $html;
122 $content = common_strip_html($html);
128 * Hook for new-notice form processing to process file upload appending...
130 * @param NewNoticeAction $action
131 * @param MediaFile $media
132 * @param string $content
133 * @param array $options
134 * @return boolean hook return
136 function onStartSaveNewNoticeAppendAttachment($action, $media, &$content, &$options)
138 if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
139 // See if we've got a placeholder inline image; if so, fill it!
140 $dom = new DOMDocument();
142 if ($dom->loadHTML($options['rendered'])) {
143 $imgs = $dom->getElementsByTagName('img');
144 foreach ($imgs as $img) {
145 if (preg_match('/(^| )placeholder( |$)/', $img->getAttribute('class'))) {
146 // Create a link to the attachment page...
147 $this->formatAttachment($img, $media);
150 $options['rendered'] = $this->saveHtml($dom);
153 // The regular code will append the short URL to the plaintext content.
154 // Carry on and let it through...
160 * Format the attachment placeholder img with the final version.
162 * @param DOMElement $img
163 * @param MediaFile $media
165 private function formatAttachment($img, $media)
167 $parent = $img->parentNode;
168 $dom = $img->ownerDocument;
170 $link = $dom->createElement('a');
171 $link->setAttribute('href', $media->fileurl);
172 $link->setAttribute('title', File::url($media->filename));
174 if ($this->isEmbeddable($media)) {
175 // Fix the the <img> attributes and wrap the link around it...
176 $this->insertImage($img, $media);
177 $parent->replaceChild($link, $img); //it dies in here?!
178 $link->appendChild($img);
180 // Not an image? Replace it with a text link.
181 $link->setAttribute('rel', 'external');
182 $link->setAttribute('class', 'attachment');
183 $link->setAttribute('id', 'attachment-' . $media->fileRecord->id);
184 $text = $dom->createTextNode($media->shortUrl());
185 $link->appendChild($text);
186 $parent->replaceChild($link, $img);
191 * Is this media file a type we can display inline?
193 * @param MediaFile $media
196 private function isEmbeddable($media)
198 $showable = array('image/png',
201 return in_array($media->mimetype, $showable);
205 * Rewrite and resize a placeholder image element to match the uploaded
206 * file. If the holder is smaller than the file, the file is scaled to fit
207 * with correct aspect ratio (but will be loaded at full resolution).
209 * @param DOMElement $img
210 * @param MediaFile $media
212 private function insertImage($img, $media)
214 $img->setAttribute('src', $media->fileRecord->url);
216 $holderWidth = intval($img->getAttribute('width'));
217 $holderHeight = intval($img->getAttribute('height'));
219 $path = File::path($media->filename);
220 $imgInfo = getimagesize($path);
223 $origWidth = $imgInfo[0];
224 $origHeight = $imgInfo[1];
226 list($width, $height) = $this->sizeBox(
227 $origWidth, $origHeight,
228 $holderWidth, $holderHeight);
230 $img->setAttribute('width', $width);
231 $img->setAttribute('height', $height);
237 * @param int $origWidth
238 * @param int $origHeight
239 * @param int $holderWidth
240 * @param int $holderHeight
241 * @return array($width, $height)
243 private function sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight)
245 $holderAspect = $holderWidth / $holderHeight;
246 $origAspect = $origWidth / $origHeight;
247 if ($origAspect >= 1.0) {
249 if ($origWidth > $holderWidth) {
250 return array($holderWidth, intval($holderWidth / $origAspect));
252 return array($origWidth, $origHeight);
255 if ($origHeight > $holderHeight) {
256 return array(intval($holderWidth * $origAspect), $holderHeight);
258 return array($origWidth, $origHeight);
263 private function saveHtml($dom)
265 $html = $dom->saveHTML();
266 // hack to remove surrounding crap added to the dom
267 // all we wanted was a fragment
268 $stripped = preg_replace('/^.*<body[^>]*>(.*)<\/body.*$/is', '$1', $html);
272 function _inlineScript()
274 $path = common_path('plugins/TinyMCE/js/tiny_mce.js');
275 $placeholder = common_path('plugins/TinyMCE/icons/placeholder.png');
277 // Note: the normal on-submit triggering to save data from
278 // the HTML editor into the textarea doesn't play well with
279 // our AJAX form submission. Manually moving it to trigger
280 // on our send button click.
281 $scr = <<<END_OF_SCRIPT
283 var origInit = SN.Init.NoticeFormSetup;
284 SN.Init.NoticeFormSetup = function(form) {
286 var noticeForm = form;
287 var textarea = form.find('.notice_data-text');
288 if (textarea.length == 0) return;
290 script_url : '{$path}',
293 plugins : "paste,fullscreen,autoresize,inlinepopups,tabfocus,linkautodetect",
294 theme_advanced_buttons1 : "bold,italic,strikethrough,|,undo,redo,|,link,unlink,image,|,fullscreen",
295 theme_advanced_buttons2 : "",
296 theme_advanced_buttons3 : "",
297 add_form_submit_trigger : false,
298 theme_advanced_resizing : true,
299 tabfocus_elements: ":prev,:next",
300 setup: function(ed) {
301 noticeForm.append('<input type="hidden" name="richedit" value="1">');
303 form.find('.submit:first').click(function() {
304 tinymce.triggerSave();
307 var origCounter = SN.U.CharacterCount;
308 SN.U.CharacterCount = function(form) {
309 var text = $(ed.getDoc()).text();
312 ed.onKeyUp.add(function (ed, e) {
313 SN.U.Counter(noticeForm);
316 form.find('input[type=file]').change(function() {
317 var img = '<img src="{$placeholder}" class="placeholder" width="320" height="240">';
318 var html = tinyMCE.activeEditor.getContent();
319 ed.setContent(html + img);
331 * Does the current user have permission to use the rich-text editor?
332 * Always true unless the plugin's "restricted" setting is on, in which
333 * case it's limited to users with the "richedit" role.
335 * @fixme make that more sanely configurable :)
339 private function isAllowedRichEdit()
341 if ($this->restricted) {
342 $user = common_current_user();
343 return !empty($user) && $user->hasRole('richedit');