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