]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/newnotice.php
Added configurable options for attachments: supported mimetypes and quotas for uploads.
[quix0rs-gnu-social.git] / actions / newnotice.php
1 <?php
2 /**
3  * Laconica, the distributed open-source microblogging tool
4  *
5  * Handler for posting new notices
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Personal
23  * @package   Laconica
24  * @author    Evan Prodromou <evan@controlyourself.ca>
25  * @author    Zach Copley <zach@controlyourself.ca>
26  * @author    Sarven Capadisli <csarven@controlyourself.ca>
27  * @copyright 2008-2009 Control Yourself, Inc.
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  * @link      http://laconi.ca/
30  */
31
32 if (!defined('LACONICA')) {
33     exit(1);
34 }
35
36 require_once INSTALLDIR.'/lib/noticelist.php';
37
38 /**
39  * Action for posting new notices
40  *
41  * @category Personal
42  * @package  Laconica
43  * @author   Evan Prodromou <evan@controlyourself.ca>
44  * @author   Zach Copley <zach@controlyourself.ca>
45  * @author   Sarven Capadisli <csarven@controlyourself.ca>
46  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47  * @link     http://laconi.ca/
48  */
49
50 class NewnoticeAction extends Action
51 {
52     /**
53      * Error message, if any
54      */
55
56     var $msg = null;
57
58     /**
59      * Title of the page
60      *
61      * Note that this usually doesn't get called unless something went wrong
62      *
63      * @return string page title
64      */
65
66     function title()
67     {
68         return _('New notice');
69     }
70
71     /**
72      * Handle input, produce output
73      *
74      * Switches based on GET or POST method. On GET, shows a form
75      * for posting a notice. On POST, saves the results of that form.
76      *
77      * Results may be a full page, or just a single notice list item,
78      * depending on whether AJAX was requested.
79      *
80      * @param array $args $_REQUEST contents
81      *
82      * @return void
83      */
84
85     function handle($args)
86     {
87         if (!common_logged_in()) {
88             $this->clientError(_('Not logged in.'));
89         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
90             // check for this before token since all POST and FILES data
91             // is losts when size is exceeded
92             if (empty($_POST) && $_SERVER['CONTENT_LENGTH']) {
93                 $this->clientError(sprintf(_('The server was unable to handle ' .
94                     'that much POST data (%s bytes) due to its current configuration.'),
95                     $_SERVER['CONTENT_LENGTH']));
96             }
97             parent::handle($args);
98
99             // CSRF protection
100             $token = $this->trimmed('token');
101             if (!$token || $token != common_session_token()) {
102                 $this->clientError(_('There was a problem with your session token. '.
103                                      'Try again, please.'));
104             }
105             try {
106                 $this->saveNewNotice();
107             } catch (Exception $e) {
108                 $this->showForm($e->getMessage());
109                 return;
110             }
111         } else {
112             $this->showForm();
113         }
114     }
115
116     function isSupportedFileType() {
117         require_once 'MIME/Type.php';
118
119         $filetype = MIME_Type::autoDetect($_FILES['attach']['tmp_name']);
120         if (in_array($filetype, common_config('attachments', 'supported'))) {
121             return true;
122         }
123         $media = MIME_Type::getMedia($filetype);
124         if ('application' !== $media) {
125             $hint = sprintf(_(' Try using another %s format.'), $media);
126         } else {
127             $hint = '';
128         }
129         $this->clientError(sprintf(
130             _('%s is not a supported filetype on this server.'), $filetype) . $hint);
131     }
132
133     function isRespectsQuota($user) {
134         if ($_FILES['attach']['size'] > common_config('attachments', 'file_quota')) {
135             $this->clientError(sprintf(_('No file may be larger than %d bytes ' .
136                 'and the file you sent was %d bytes. Try to upload a smaller version.'),
137                 common_config('attachments', 'file_quota'), $_FILES['attach']['size']));
138         }
139
140         $query = "select sum(size) as total from file join file_to_post on file_to_post.file_id = file.id join notice on file_to_post.post_id = notice.id where profile_id = {$user->id} and file.url like '%/notice/%/file'";
141         $file = new File;
142         $file->query($query);
143         $file->fetch();
144         $total = $file->total + $_FILES['attach']['size'];
145         if ($total > common_config('attachments', 'user_quota')) {
146             $this->clientError(sprintf(_('A file this large would exceed your user quota of %d bytes.'), common_config('attachments', 'user_quota')));
147         }
148
149         $query .= ' month(modified) = month(now()) and year(modified) = year(now())';
150         $file2 = new File;
151         $file2->query($query);
152         $file2->fetch();
153         $total2 = $file2->total + $_FILES['attach']['size'];
154         if ($total2 > common_config('attachments', 'monthly_quota')) {
155             $this->clientError(sprintf(_('A file this large would exceed your monthly quota of %d bytes.'), common_config('attachments', 'monthly_quota')));
156         }
157         return true;
158     }
159
160     function isValidFileAttached($user) {
161         return isset($_FILES['attach']['error'])
162             && ($_FILES['attach']['error'] === UPLOAD_ERR_OK)
163             && $this->isSupportedFileType()
164             && $this->isRespectsQuota($user);
165     }
166
167     /**
168      * Save a new notice, based on arguments
169      *
170      * If successful, will show the notice, or return an Ajax-y result.
171      * If not, it will show an error message -- possibly Ajax-y.
172      *
173      * Also, if the notice input looks like a command, it will run the
174      * command and show the results -- again, possibly ajaxy.
175      *
176      * @return void
177      */
178
179     function saveNewNotice()
180     {
181         $user = common_current_user();
182         assert($user); // XXX: maybe an error instead...
183         $content = $this->trimmed('status_textarea');
184
185         if (!$content) {
186             $this->clientError(_('No content!'));
187         } else {
188             $content_shortened = common_shorten_links($content);
189             if (mb_strlen($content_shortened) > 140) {
190                 $this->clientError(_('That\'s too long. '.
191                                      'Max notice size is 140 chars.'));
192             }
193         }
194
195         $inter = new CommandInterpreter();
196
197         $cmd = $inter->handle_command($user, $content_shortened);
198
199         if ($cmd) {
200             if ($this->boolean('ajax')) {
201                 $cmd->execute(new AjaxWebChannel($this));
202             } else {
203                 $cmd->execute(new WebChannel($this));
204             }
205             return;
206         }
207
208         $replyto = $this->trimmed('inreplyto');
209         #If an ID of 0 is wrongly passed here, it will cause a database error,
210         #so override it...
211         if ($replyto == 0) {
212             $replyto = 'false';
213         }
214
215         switch ($_FILES['attach']['error']) {
216             case UPLOAD_ERR_NO_FILE:
217                 // no file uploaded
218                 // nothing to do
219                 break;
220
221              case UPLOAD_ERR_OK:
222                 // file was uploaded alright
223                 // lets check if we really support its format
224                 // and it doesn't go over quotas
225
226
227                 if (!$this->isValidFileAttached($user)) {
228                     die('clientError() should trigger an exception before reaching here.');
229                 }
230                 break;
231
232             case UPLOAD_ERR_INI_SIZE:
233                 $this->clientError(_('The uploaded file exceeds the upload_max_filesize directive in php.ini.'));
234
235             case UPLOAD_ERR_FORM_SIZE:
236                 $this->clientError(_('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'));
237
238             case UPLOAD_ERR_PARTIAL:
239                 $this->clientError(_('The uploaded file was only partially uploaded.'));
240
241             case  UPLOAD_ERR_NO_TMP_DIR:
242                 $this->clientError(_('Missing a temporary folder.'));
243
244             case UPLOAD_ERR_CANT_WRITE:
245                 $this->clientError(_('Failed to write file to disk.'));
246
247             case UPLOAD_ERR_EXTENSION:
248                 $this->clientError(_('File upload stopped by extension.'));
249
250             default:
251                 die('Should never reach here.');
252         }
253
254         $notice = Notice::saveNew($user->id, $content_shortened, 'web', 1,
255                                   ($replyto == 'false') ? null : $replyto);
256
257         if (is_string($notice)) {
258             $this->clientError($notice);
259         }
260
261         $this->storeFile($notice);
262         $this->saveUrls($notice);
263         common_broadcast_notice($notice);
264
265         if ($this->boolean('ajax')) {
266             $this->startHTML('text/xml;charset=utf-8');
267             $this->elementStart('head');
268             $this->element('title', null, _('Notice posted'));
269             $this->elementEnd('head');
270             $this->elementStart('body');
271             $this->showNotice($notice);
272             $this->elementEnd('body');
273             $this->elementEnd('html');
274         } else {
275             $returnto = $this->trimmed('returnto');
276
277             if ($returnto) {
278                 $url = common_local_url($returnto,
279                                         array('nickname' => $user->nickname));
280             } else {
281                 $url = common_local_url('shownotice',
282                                         array('notice' => $notice->id));
283             }
284             common_redirect($url, 303);
285         }
286     }
287
288     function storeFile($notice) {
289         if (UPLOAD_ERR_NO_FILE === $_FILES['attach']['error']) return;
290         $filename = basename($_FILES['attach']['name']);
291         $destination = "file/{$notice->id}-$filename";
292         if (move_uploaded_file($_FILES['attach']['tmp_name'], INSTALLDIR . "/$destination")) {
293             $file = new File;
294             $file->url = common_local_url('file', array('notice' => $notice->id));
295             $file->size = filesize(INSTALLDIR . "/$destination");
296             $file->date = time();
297             $file->mimetype = $_FILES['attach']['type'];
298             if ($file_id = $file->insert()) {
299                 $file_redir = new File_redirection;
300                 $file_redir->url = common_path($destination);
301                 $file_redir->file_id = $file_id;
302                 $file_redir->insert();
303
304                 $f2p = new File_to_post;
305                 $f2p->file_id = $file_id; 
306                 $f2p->post_id = $notice->id; 
307                 $f2p->insert();
308             } else {
309                 $this->clientError(_('There was a database error while saving your file. Please try again.'));
310             }
311         }
312     }
313
314
315     /** save all urls in the notice to the db
316      *
317      * follow redirects and save all available file information
318      * (mimetype, date, size, oembed, etc.)
319      *
320      * @param class $notice Notice to pull URLs from
321      *
322      * @return void
323      */
324     function saveUrls($notice, $uploaded = null) {
325         common_replace_urls_callback($notice->content, array($this, 'saveUrl'), $notice->id);
326     }
327
328     function saveUrl($data) {
329         list($url, $notice_id) = $data;
330         $zzz = File::processNew($url, $notice_id);
331     }
332
333     /**
334      * Show an Ajax-y error message
335      *
336      * Goes back to the browser, where it's shown in a popup.
337      *
338      * @param string $msg Message to show
339      *
340      * @return void
341      */
342
343     function ajaxErrorMsg($msg)
344     {
345         $this->startHTML('text/xml;charset=utf-8', true);
346         $this->elementStart('head');
347         $this->element('title', null, _('Ajax Error'));
348         $this->elementEnd('head');
349         $this->elementStart('body');
350         $this->element('p', array('id' => 'error'), $msg);
351         $this->elementEnd('body');
352         $this->elementEnd('html');
353     }
354
355     /**
356      * Formerly page output
357      *
358      * This used to be the whole page output; now that's been largely
359      * subsumed by showPage. So this just stores an error message, if
360      * it was passed, and calls showPage.
361      *
362      * Note that since we started doing Ajax output, this page is rarely
363      * seen.
364      *
365      * @param string $msg An error message, if any
366      *
367      * @return void
368      */
369
370     function showForm($msg=null)
371     {
372         if ($msg && $this->boolean('ajax')) {
373             $this->ajaxErrorMsg($msg);
374             return;
375         }
376
377         $this->msg = $msg;
378         $this->showPage();
379     }
380
381     /**
382      * Overload for replies or bad results
383      *
384      * We show content in the notice form if there were replies or results.
385      *
386      * @return void
387      */
388
389     function showNoticeForm()
390     {
391         $content = $this->trimmed('status_textarea');
392         if (!$content) {
393             $replyto = $this->trimmed('replyto');
394             $profile = Profile::staticGet('nickname', $replyto);
395             if ($profile) {
396                 $content = '@' . $profile->nickname . ' ';
397             }
398         }
399
400         $notice_form = new NoticeForm($this, '', $content);
401         $notice_form->show();
402     }
403
404     /**
405      * Show an error message
406      *
407      * Shows an error message if there is one.
408      *
409      * @return void
410      *
411      * @todo maybe show some instructions?
412      */
413
414     function showPageNotice()
415     {
416         if ($this->msg) {
417             $this->element('p', array('id' => 'error'), $this->msg);
418         }
419     }
420
421     /**
422      * Output a notice
423      *
424      * Used to generate the notice code for Ajax results.
425      *
426      * @param Notice $notice Notice that was saved
427      *
428      * @return void
429      */
430
431     function showNotice($notice)
432     {
433         $nli = new NoticeListItem($notice, $this);
434         $nli->show();
435     }
436 }