]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TinyMCE/TinyMCEPlugin.php
Fix for ticket 2756 - Calls to OAuth endpoints are redirected to the
[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
52     var $html;
53
54     function onEndShowScripts($action)
55     {
56         if (common_logged_in ()) {
57             $action->script(common_path('plugins/TinyMCE/js/jquery.tinymce.js'));
58             $action->inlineScript($this->_inlineScript());
59         }
60
61         return true;
62     }
63
64     function onEndShowStyles($action)
65     {
66         $action->style('span#notice_data-text_container, span#notice_data-text_parent { float: left }');
67         return true;
68     }
69
70     function onPluginVersion(&$versions)
71     {
72         $versions[] = array('name' => 'TinyMCE',
73             'version' => STATUSNET_VERSION,
74             'author' => 'Evan Prodromou',
75             'homepage' => 'http://status.net/wiki/Plugin:TinyMCE',
76             'rawdescription' =>
77             _m('Use TinyMCE library to allow rich text editing in the browser'));
78         return true;
79     }
80
81     /**
82      * Sanitize HTML input and strip out potentially dangerous bits.
83      *
84      * @param string $raw HTML
85      * @return string HTML
86      */
87     private function sanitizeHtml($raw)
88     {
89         require_once INSTALLDIR . '/extlib/htmLawed/htmLawed.php';
90
91         $config = array('safe' => 1,
92             'deny_attribute' => 'id,style,on*');
93
94         return htmLawed($raw, $config);
95     }
96
97     /**
98      * Strip HTML to plaintext string
99      *
100      * @param string $html HTML
101      * @return string plaintext, single line
102      */
103     private function stripHtml($html)
104     {
105         return str_replace("\n", " ", html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8'));
106     }
107
108     /**
109      * Hook for new-notice form processing to take our HTML goodies;
110      * won't affect API posting etc.
111      * 
112      * @param NewNoticeAction $action
113      * @param User $user
114      * @param string $content
115      * @param array $options
116      * @return boolean hook return
117      */
118     function onStartSaveNewNoticeWeb($action, $user, &$content, &$options)
119     {
120         if ($action->arg('richedit')) {
121             $html = $this->sanitizeHtml($content);
122             $options['rendered'] = $html;
123             $content = $this->stripHtml($html);
124         }
125         return true;
126     }
127
128     /**
129      * Hook for new-notice form processing to process file upload appending...
130      *
131      * @param NewNoticeAction $action
132      * @param MediaFile $media
133      * @param string $content
134      * @param array $options
135      * @return boolean hook return
136      */
137     function onStartSaveNewNoticeAppendAttachment($action, $media, &$content, &$options)
138     {
139         if ($action->arg('richedit')) {
140             // See if we've got a placeholder inline image; if so, fill it!
141             $dom = new DOMDocument();
142
143             if ($dom->loadHTML($options['rendered'])) {
144                 $imgs = $dom->getElementsByTagName('img');
145                 foreach ($imgs as $img) {
146                     if (preg_match('/(^| )placeholder( |$)/', $img->getAttribute('class'))) {
147                         // Create a link to the attachment page...
148                         $this->formatAttachment($img, $media);
149                     }
150                 }
151                 $options['rendered'] = $this->saveHtml($dom);
152             }
153
154             // The regular code will append the short URL to the plaintext content.
155             // Carry on and let it through...
156         }
157         return true;
158     }
159
160     /**
161      * Format the attachment placeholder img with the final version.
162      * 
163      * @param DOMElement $img
164      * @param MediaFile $media 
165      */
166     private function formatAttachment($img, $media)
167     {
168         $parent = $img->parentNode;
169         $dom = $img->ownerDocument;
170
171         $link = $dom->createElement('a');
172         $link->setAttribute('href', $media->fileurl);
173         $link->setAttribute('title', File::url($media->filename));
174
175         if ($this->isEmbeddable($media)) {
176             // Fix the the <img> attributes and wrap the link around it...
177             $this->insertImage($img, $media);
178             $parent->replaceChild($link, $img); //it dies in here?!
179             $link->appendChild($img);
180         } else {
181             // Not an image? Replace it with a text link.
182             $link->setAttribute('rel', 'external');
183             $link->setAttribute('class', 'attachment');
184             $link->setAttribute('id', 'attachment-' . $media->fileRecord->id);
185             $text = $dom->createTextNode($media->shortUrl());
186             $link->appendChild($text);
187             $parent->replaceChild($link, $img);
188         }
189     }
190
191     /**
192      * Is this media file a type we can display inline?
193      *
194      * @param MediaFile $media
195      * @return boolean
196      */
197     private function isEmbeddable($media)
198     {
199         $showable = array('image/png',
200                           'image/gif',
201                           'image/jpeg');
202         return in_array($media->mimetype, $showable);
203     }
204
205     /**
206      * Rewrite and resize a placeholder image element to match the uploaded
207      * file. If the holder is smaller than the file, the file is scaled to fit
208      * with correct aspect ratio (but will be loaded at full resolution).
209      *
210      * @param DOMElement $img
211      * @param MediaFile $media
212      */
213     private function insertImage($img, $media)
214     {
215         $img->setAttribute('src', $media->fileRecord->url);
216
217         $holderWidth = intval($img->getAttribute('width'));
218         $holderHeight = intval($img->getAttribute('height'));
219
220         $path = File::path($media->filename);
221         $imgInfo = getimagesize($path);
222
223         if ($imgInfo) {
224             $origWidth = $imgInfo[0];
225             $origHeight = $imgInfo[1];
226
227             list($width, $height) = $this->sizeBox(
228                     $origWidth, $origHeight,
229                     $holderWidth, $holderHeight);
230
231             $img->setAttribute('width', $width);
232             $img->setAttribute('height', $height);
233         }
234     }
235
236     /**
237      *
238      * @param int $origWidth
239      * @param int $origHeight
240      * @param int $holderWidth
241      * @param int $holderHeight
242      * @return array($width, $height)
243      */
244     private function sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight)
245     {
246         $holderAspect = $holderWidth / $holderHeight;
247         $origAspect = $origWidth / $origHeight;
248         if ($origAspect >= 1.0) {
249             // wide image
250             if ($origWidth > $holderWidth) {
251                 return array($holderWidth, intval($holderWidth / $origAspect));
252             } else {
253                 return array($origWidth, $origHeight);
254             }
255         } else {
256             if ($origHeight > $holderHeight) {
257                 return array(intval($holderWidth * $origAspect), $holderHeight);
258             } else {
259                 return array($origWidth, $origHeight);
260             }
261         }
262     }
263
264     private function saveHtml($dom)
265     {
266         $html = $dom->saveHTML();
267         // hack to remove surrounding crap added to the dom
268         // all we wanted was a fragment
269         $stripped = preg_replace('/^.*<body[^>]*>(.*)<\/body.*$/is', '$1', $html);
270         return $stripped;
271     }
272
273     function _inlineScript()
274     {
275         $path = common_path('plugins/TinyMCE/js/tiny_mce.js');
276         $placeholder = common_path('plugins/TinyMCE/icons/placeholder.png');
277
278         // Note: the normal on-submit triggering to save data from
279         // the HTML editor into the textarea doesn't play well with
280         // our AJAX form submission. Manually moving it to trigger
281         // on our send button click.
282         $scr = <<<END_OF_SCRIPT
283         $().ready(function() {
284             var noticeForm = $('#form_notice');
285             $('textarea#notice_data-text').tinymce({
286                 script_url : '{$path}',
287                 // General options
288                 theme : "advanced",
289                 plugins : "paste,fullscreen,autoresize,inlinepopups,tabfocus,linkautodetect",
290                 theme_advanced_buttons1 : "bold,italic,strikethrough,|,undo,redo,|,link,unlink,image,|,fullscreen",
291                 theme_advanced_buttons2 : "",
292                 theme_advanced_buttons3 : "",
293                 add_form_submit_trigger : false,
294                 theme_advanced_resizing : true,
295                 tabfocus_elements: ":prev,:next",
296                 setup: function(ed) {
297                     noticeForm.append('<input type="hidden" name="richedit" value="1">');
298
299                     $('#notice_action-submit').click(function() {
300                         tinymce.triggerSave();
301                     });
302
303                     var origCounter = SN.U.CharacterCount;
304                     SN.U.CharacterCount = function(form) {
305                         var text = $(ed.getDoc()).text();
306                         return text.length;
307                     };
308                     ed.onKeyUp.add(function (ed, e) {
309                         SN.U.Counter(noticeForm);
310                     });
311
312                     $('#'+SN.C.S.NoticeDataAttach).change(function() {
313                         var img = '<img src="{$placeholder}" class="placeholder" width="320" height="240">';
314                         var html = tinyMCE.activeEditor.getContent();
315                         ed.setContent(html + img);
316                     });
317                 }
318             });
319         });
320 END_OF_SCRIPT;
321
322         return $scr;
323     }
324
325 }