]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TinyMCE/TinyMCEPlugin.php
Localisation updates from http://translatewiki.net.
[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)
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)
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(&$versions)
80     {
81         $versions[] = array('name' => 'TinyMCE',
82             'version' => STATUSNET_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      * Strip HTML to plaintext string
109      *
110      * @param string $html HTML
111      * @return string plaintext, single line
112      */
113     private function stripHtml($html)
114     {
115         return str_replace("\n", " ", html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8'));
116     }
117
118     /**
119      * Hook for new-notice form processing to take our HTML goodies;
120      * won't affect API posting etc.
121      *
122      * @param NewNoticeAction $action
123      * @param User $user
124      * @param string $content
125      * @param array $options
126      * @return boolean hook return
127      */
128     function onStartSaveNewNoticeWeb($action, $user, &$content, &$options)
129     {
130         if ($action->arg('richedit') && $this->isAllowedRichEdit()) {
131             $html = $this->sanitizeHtml($content);
132             $options['rendered'] = $html;
133             $content = $this->stripHtml($html);
134         }
135         return true;
136     }
137
138     /**
139      * Hook for new-notice form processing to process file upload appending...
140      *
141      * @param NewNoticeAction $action
142      * @param MediaFile $media
143      * @param string $content
144      * @param array $options
145      * @return boolean hook return
146      */
147     function onStartSaveNewNoticeAppendAttachment($action, $media, &$content, &$options)
148     {
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();
152
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);
159                     }
160                 }
161                 $options['rendered'] = $this->saveHtml($dom);
162             }
163
164             // The regular code will append the short URL to the plaintext content.
165             // Carry on and let it through...
166         }
167         return true;
168     }
169
170     /**
171      * Format the attachment placeholder img with the final version.
172      *
173      * @param DOMElement $img
174      * @param MediaFile $media
175      */
176     private function formatAttachment($img, $media)
177     {
178         $parent = $img->parentNode;
179         $dom = $img->ownerDocument;
180
181         $link = $dom->createElement('a');
182         $link->setAttribute('href', $media->fileurl);
183         $link->setAttribute('title', File::url($media->filename));
184
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);
190         } else {
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);
198         }
199     }
200
201     /**
202      * Is this media file a type we can display inline?
203      *
204      * @param MediaFile $media
205      * @return boolean
206      */
207     private function isEmbeddable($media)
208     {
209         $showable = array('image/png',
210                           'image/gif',
211                           'image/jpeg');
212         return in_array($media->mimetype, $showable);
213     }
214
215     /**
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).
219      *
220      * @param DOMElement $img
221      * @param MediaFile $media
222      */
223     private function insertImage($img, $media)
224     {
225         $img->setAttribute('src', $media->fileRecord->url);
226
227         $holderWidth = intval($img->getAttribute('width'));
228         $holderHeight = intval($img->getAttribute('height'));
229
230         $path = File::path($media->filename);
231         $imgInfo = getimagesize($path);
232
233         if ($imgInfo) {
234             $origWidth = $imgInfo[0];
235             $origHeight = $imgInfo[1];
236
237             list($width, $height) = $this->sizeBox(
238                     $origWidth, $origHeight,
239                     $holderWidth, $holderHeight);
240
241             $img->setAttribute('width', $width);
242             $img->setAttribute('height', $height);
243         }
244     }
245
246     /**
247      *
248      * @param int $origWidth
249      * @param int $origHeight
250      * @param int $holderWidth
251      * @param int $holderHeight
252      * @return array($width, $height)
253      */
254     private function sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight)
255     {
256         $holderAspect = $holderWidth / $holderHeight;
257         $origAspect = $origWidth / $origHeight;
258         if ($origAspect >= 1.0) {
259             // wide image
260             if ($origWidth > $holderWidth) {
261                 return array($holderWidth, intval($holderWidth / $origAspect));
262             } else {
263                 return array($origWidth, $origHeight);
264             }
265         } else {
266             if ($origHeight > $holderHeight) {
267                 return array(intval($holderWidth * $origAspect), $holderHeight);
268             } else {
269                 return array($origWidth, $origHeight);
270             }
271         }
272     }
273
274     private function saveHtml($dom)
275     {
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);
280         return $stripped;
281     }
282
283     function _inlineScript()
284     {
285         $path = common_path('plugins/TinyMCE/js/tiny_mce.js');
286         $placeholder = common_path('plugins/TinyMCE/icons/placeholder.png');
287
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
293         (function() {
294         var origInit = SN.Init.NoticeFormSetup;
295         SN.Init.NoticeFormSetup = function(form) {
296             origInit(form);
297             var noticeForm = form;
298             var textarea = form.find('.notice_data-text');
299             if (textarea.length == 0) return;
300             textarea.tinymce({
301                 script_url : '{$path}',
302                 // General options
303                 theme : "advanced",
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">');
313
314                     form.find('.submit:first').click(function() {
315                         tinymce.triggerSave();
316                     });
317
318                     var origCounter = SN.U.CharacterCount;
319                     SN.U.CharacterCount = function(form) {
320                         var text = $(ed.getDoc()).text();
321                         return text.length;
322                     };
323                     ed.onKeyUp.add(function (ed, e) {
324                         SN.U.Counter(noticeForm);
325                     });
326
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);
331                     });
332                 }
333             });
334         };
335         })();
336 END_OF_SCRIPT;
337
338         return $scr;
339     }
340
341     /**
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.
345      *
346      * @fixme make that more sanely configurable :)
347      *
348      * @return boolean
349      */
350     private function isAllowedRichEdit()
351     {
352         if ($this->restricted) {
353             $user = common_current_user();
354             return !empty($user) && $user->hasRole('richedit');
355         } else {
356             return true;
357         }
358     }
359 }