]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TinyMCE/TinyMCEPlugin.php
work in progress: tinymce image attachments
[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)));
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                 $html = $dom->saveHTML();
152                 $options['rendered'] = $html;
153             }
154
155             // The regular code will append the short URL to the plaintext content.
156             // Carry on and let it through...
157         }
158         return true;
159     }
160
161     /**
162      * Format the attachment placeholder img with the final version.
163      * 
164      * @param DOMElement $img
165      * @param MediaFile $media 
166      */
167     private function formatAttachment($img, $media)
168     {
169         $dom = $img->ownerDocument;
170         $link = $dom->createElement('a');
171         $link->setAttribute('href', $media->fileurl);
172
173         if ($this->isEmbeddable($media)) {
174             common_log(LOG_INFO, 'QQQQQ');
175             // Fix the the <img> attributes and wrap the link around it...
176             $this->insertImage($img, $media);
177             common_log(LOG_INFO, 'QQQQQ A!');
178             try {
179                 $dom->replaceChild($link, $img); //it dies in here?!
180             } catch (Exception $wtf) {
181                 common_log(LOG_ERR, 'QQQ WTF? ' . $wtf->getMessage());
182             }
183             common_log(LOG_INFO, 'QQQQQ B!');
184             $link->appendChild($img);
185             common_log(LOG_INFO, 'QQQQQ C!');
186         } else {
187             common_log(LOG_INFO, 'QQQQQ X');
188             // Not an image? Replace it with a text link.
189             $text = $dom->createTextNode($media->shortUrl());
190             $link->appendChild($text);
191             $dom->replaceChild($link, $img);
192         }
193     }
194
195     /**
196      * Is this media file a type we can display inline?
197      *
198      * @param MediaFile $media
199      * @return boolean
200      */
201     private function isEmbeddable($media)
202     {
203         $showable = array('image/png',
204                           'image/gif',
205                           'image/jpeg');
206         return in_array($media->mimetype, $showable);
207     }
208
209     /**
210      * Rewrite and resize a placeholder image element to match the uploaded
211      * file. If the holder is smaller than the file, the file is scaled to fit
212      * with correct aspect ratio (but will be loaded at full resolution).
213      *
214      * @param DOMElement $img
215      * @param MediaFile $media
216      */
217     private function insertImage($img, $media)
218     {
219         $img->setAttribute('src', $media->fileRecord->url);
220
221         $holderWidth = intval($img->getAttribute('width'));
222         $holderHeight = intval($img->getAttribute('height'));
223
224         $path = File::path($media->filename);
225         $imgInfo = getimagesize($path);
226
227         if ($imgInfo) {
228             $origWidth = $imgInfo[0];
229             $origHeight = $imgInfo[1];
230
231             list($width, $height) = $this->sizeBox(
232                     $origWidth, $origHeight,
233                     $holderWidth, $holderHeight);
234
235             $img->setAttribute('width', $width);
236             $img->setAttribute('height', $height);
237         }
238     }
239
240     /**
241      *
242      * @param int $origWidth
243      * @param int $origHeight
244      * @param int $holderWidth
245      * @param int $holderHeight
246      * @return array($width, $height)
247      */
248     private function sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight)
249     {
250         $holderAspect = $holderWidth / $holderHeight;
251         $origAspect = $origWidth / $origHeight;
252         if ($origAspect >= 1.0) {
253             // wide image
254             if ($origWidth > $holderWidth) {
255                 return array($holderWidth, intval($holderWidth / $origAspect));
256             } else {
257                 return array($origWidth, $origHeight);
258             }
259         } else {
260             if ($origHeight > $holderHeight) {
261                 return array(intval($holderWidth * $origAspect), $holderHeight);
262             } else {
263                 return array($origWidth, $origHeight);
264             }
265         }
266     }
267
268     function _inlineScript()
269     {
270         $path = common_path('plugins/TinyMCE/js/tiny_mce.js');
271         $placeholder = common_path('plugins/TinyMCE/icons/placeholder.png');
272
273         // Note: the normal on-submit triggering to save data from
274         // the HTML editor into the textarea doesn't play well with
275         // our AJAX form submission. Manually moving it to trigger
276         // on our send button click.
277         $scr = <<<END_OF_SCRIPT
278         $().ready(function() {
279             $('textarea#notice_data-text').tinymce({
280                 script_url : '{$path}',
281                 // General options
282                 theme : "advanced",
283                 plugins : "paste,fullscreen,autoresize,inlinepopups,tabfocus,linkautodetect",
284                 theme_advanced_buttons1 : "bold,italic,strikethrough,|,undo,redo,|,link,unlink,image,|,fullscreen",
285                 theme_advanced_buttons2 : "",
286                 theme_advanced_buttons3 : "",
287                 add_form_submit_trigger : false,
288                 theme_advanced_resizing : true,
289                 tabfocus_elements: ":prev,:next"
290             });
291             $('#form_notice').append('<input type="hidden" name="richedit" value="1">');
292             $('#notice_action-submit').click(function() {
293                 if (typeof tinymce != "undefined") {
294                     tinymce.triggerSave();
295                 }
296             });
297             $('#'+SN.C.S.NoticeDataAttach).change(function() {
298                 /*
299                 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">&#215;</button></div>';
300                 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
301                 if (NDAS.length > 0) {
302                     NDAS.replaceWith(S);
303                 }
304                 */
305                 //alert('yay');
306                 var img = '<img src="{$placeholder}" class="placeholder" width="320" height="240">';
307                 var html = tinyMCE.activeEditor.getContent();
308                 tinyMCE.activeEditor.setContent(html + img);
309             });
310         });
311 END_OF_SCRIPT;
312
313         return $scr;
314     }
315
316 }
317