]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TinyMCE/TinyMCEPlugin.php
Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / plugins / TinyMCE / TinyMCEPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * Use TinyMCE library to allow rich text editing in the browser
7  *
8  * PHP version 5
9  *
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.
14  *
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.
19  *
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/>.
22  *
23  * @category  WYSIWYG
24  * @package   StatusNet
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/
29  */
30 if (!defined('STATUSNET')) {
31     // This check helps protect against security problems;
32     // your code file can't be executed directly from the web.
33     exit(1);
34 }
35
36 /**
37  * Use TinyMCE library to allow rich text editing in the browser
38  *
39  * Converts the notice form in browser to a rich-text editor.
40  *
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).
44  *
45  * @category  WYSIWYG
46  * @package   StatusNet
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/
51  */
52 class TinyMCEPlugin extends Plugin
53 {
54     var $html;
55
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;
60
61     function onEndShowScripts(Action $action)
62     {
63         if (common_logged_in() && $this->isAllowedRichEdit()) {
64             $action->script(common_path('plugins/TinyMCE/js/jquery.tinymce.js'));
65             $action->inlineScript($this->_inlineScript());
66         }
67
68         return true;
69     }
70
71     function onEndShowStyles(Action $action)
72     {
73         if ($this->isAllowedRichEdit()) {
74             $action->style('span#notice_data-text_container, span#notice_data-text_parent { float: left }');
75         }
76         return true;
77     }
78
79     function onPluginVersion(array &$versions)
80     {
81         $versions[] = array('name' => 'TinyMCE',
82             'version' => GNUSOCIAL_VERSION,
83             'author' => 'Evan Prodromou',
84             'homepage' => 'http://status.net/wiki/Plugin:TinyMCE',
85             'rawdescription' =>
86             // TRANS: Plugin description.
87             _m('Use TinyMCE library to allow rich text editing in the browser.'));
88         return true;
89     }
90
91     /**
92      * Sanitize HTML input and strip out potentially dangerous bits.
93      *
94      * @param string $raw HTML
95      * @return string HTML
96      */
97     private function sanitizeHtml($raw)
98     {
99         require_once INSTALLDIR . '/extlib/htmLawed/htmLawed.php';
100
101         $config = array('safe' => 1,
102             'deny_attribute' => 'id,style,on*');
103
104         return htmLawed($raw, $config);
105     }
106
107     /**
108      * Hook for new-notice form processing to take our HTML goodies;
109      * won't affect API posting etc.
110      *
111      * @param NewNoticeAction $action
112      * @param User $user
113      * @param string $content
114      * @param array $options
115      * @return boolean hook return
116      */
117     function onStartSaveNewNoticeWeb($action, $user, &$content, &$options)
118     {
119         if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
120             $html = $this->sanitizeHtml($content);
121             $options['rendered'] = $html;
122             $content = common_strip_html($html);
123         }
124         return true;
125     }
126
127     /**
128      * Hook for new-notice form processing to process file upload appending...
129      *
130      * @param NewNoticeAction $action
131      * @param MediaFile $media
132      * @param string $content
133      * @param array $options
134      * @return boolean hook return
135      */
136     function onStartSaveNewNoticeAppendAttachment($action, $media, &$content, &$options)
137     {
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();
141
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);
148                     }
149                 }
150                 $options['rendered'] = $this->saveHtml($dom);
151             }
152
153             // The regular code will append the short URL to the plaintext content.
154             // Carry on and let it through...
155         }
156         return true;
157     }
158
159     /**
160      * Format the attachment placeholder img with the final version.
161      *
162      * @param DOMElement $img
163      * @param MediaFile $media
164      */
165     private function formatAttachment($img, $media)
166     {
167         $parent = $img->parentNode;
168         $dom = $img->ownerDocument;
169
170         $link = $dom->createElement('a');
171         $link->setAttribute('href', $media->fileurl);
172         $link->setAttribute('title', File::url($media->filename));
173
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);
179         } else {
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);
187         }
188     }
189
190     /**
191      * Is this media file a type we can display inline?
192      *
193      * @param MediaFile $media
194      * @return boolean
195      */
196     private function isEmbeddable($media)
197     {
198         $showable = array('image/png',
199                           'image/gif',
200                           'image/jpeg');
201         return in_array($media->mimetype, $showable);
202     }
203
204     /**
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).
208      *
209      * @param DOMElement $img
210      * @param MediaFile $media
211      */
212     private function insertImage($img, $media)
213     {
214         $img->setAttribute('src', $media->fileRecord->url);
215
216         $holderWidth = intval($img->getAttribute('width'));
217         $holderHeight = intval($img->getAttribute('height'));
218
219         $path = File::path($media->filename);
220         $imgInfo = getimagesize($path);
221
222         if ($imgInfo) {
223             $origWidth = $imgInfo[0];
224             $origHeight = $imgInfo[1];
225
226             list($width, $height) = $this->sizeBox(
227                     $origWidth, $origHeight,
228                     $holderWidth, $holderHeight);
229
230             $img->setAttribute('width', $width);
231             $img->setAttribute('height', $height);
232         }
233     }
234
235     /**
236      *
237      * @param int $origWidth
238      * @param int $origHeight
239      * @param int $holderWidth
240      * @param int $holderHeight
241      * @return array($width, $height)
242      */
243     private function sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight)
244     {
245         $holderAspect = $holderWidth / $holderHeight;
246         $origAspect = $origWidth / $origHeight;
247         if ($origAspect >= 1.0) {
248             // wide image
249             if ($origWidth > $holderWidth) {
250                 return array($holderWidth, intval($holderWidth / $origAspect));
251             } else {
252                 return array($origWidth, $origHeight);
253             }
254         } else {
255             if ($origHeight > $holderHeight) {
256                 return array(intval($holderWidth * $origAspect), $holderHeight);
257             } else {
258                 return array($origWidth, $origHeight);
259             }
260         }
261     }
262
263     private function saveHtml($dom)
264     {
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);
269         return $stripped;
270     }
271
272     function _inlineScript()
273     {
274         $path = common_path('plugins/TinyMCE/js/tiny_mce.js');
275         $placeholder = common_path('plugins/TinyMCE/icons/placeholder.png');
276
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
282         (function() {
283         var origInit = SN.Init.NoticeFormSetup;
284         SN.Init.NoticeFormSetup = function(form) {
285             origInit(form);
286             var noticeForm = form;
287             var textarea = form.find('.notice_data-text');
288             if (textarea.length == 0) return;
289             textarea.tinymce({
290                 script_url : '{$path}',
291                 // General options
292                 theme : "advanced",
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">');
302
303                     form.find('.submit:first').click(function() {
304                         tinymce.triggerSave();
305                     });
306
307                     var origCounter = SN.U.CharacterCount;
308                     SN.U.CharacterCount = function(form) {
309                         var text = $(ed.getDoc()).text();
310                         return text.length;
311                     };
312                     ed.onKeyUp.add(function (ed, e) {
313                         SN.U.Counter(noticeForm);
314                     });
315
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);
320                     });
321                 }
322             });
323         };
324         })();
325 END_OF_SCRIPT;
326
327         return $scr;
328     }
329
330     /**
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.
334      *
335      * @fixme make that more sanely configurable :)
336      *
337      * @return boolean
338      */
339     private function isAllowedRichEdit()
340     {
341         if ($this->restricted) {
342             $user = common_current_user();
343             return !empty($user) && $user->hasRole('richedit');
344         } else {
345             return true;
346         }
347     }
348 }