]> 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 /**
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  * 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).
45  *
46  * @category  WYSIWYG
47  * @package   StatusNet
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/
52  */
53 class TinyMCEPlugin extends Plugin
54 {
55     var $html;
56
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;
61
62     function onEndShowScripts($action)
63     {
64         if (common_logged_in() && $this->isAllowedRichEdit()) {
65             $action->script(common_path('plugins/TinyMCE/js/jquery.tinymce.js'));
66             $action->inlineScript($this->_inlineScript());
67         }
68
69         return true;
70     }
71
72     function onEndShowStyles($action)
73     {
74         if ($this->isAllowedRichEdit()) {
75             $action->style('span#notice_data-text_container, span#notice_data-text_parent { float: left }');
76         }
77         return true;
78     }
79
80     function onPluginVersion(&$versions)
81     {
82         $versions[] = array('name' => 'TinyMCE',
83             'version' => STATUSNET_VERSION,
84             'author' => 'Evan Prodromou',
85             'homepage' => 'http://status.net/wiki/Plugin:TinyMCE',
86             'rawdescription' =>
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 }