]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/newnotice.php
Update Polish translations from Raven's bug tracker submission:
[quix0rs-gnu-social.git] / actions / newnotice.php
1 <?php
2 /**
3  * StatusNet, 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   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @author    Zach Copley <zach@status.net>
26  * @author    Sarven Capadisli <csarven@status.net>
27  * @copyright 2008-2009 StatusNet, Inc.
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  * @link      http://status.net/
30  */
31
32 if (!defined('STATUSNET') && !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  StatusNet
43  * @author   Evan Prodromou <evan@status.net>
44  * @author   Zach Copley <zach@status.net>
45  * @author   Sarven Capadisli <csarven@status.net>
46  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47  * @link     http://status.net/
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 getUploadedFileType() {
117         require_once 'MIME/Type.php';
118
119         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
120         $cmd = common_config('attachments', 'filecommand');
121
122         $filetype = MIME_Type::autoDetect($_FILES['attach']['tmp_name']);
123         if (in_array($filetype, common_config('attachments', 'supported'))) {
124             return $filetype;
125         }
126         $media = MIME_Type::getMedia($filetype);
127         if ('application' !== $media) {
128             $hint = sprintf(_(' Try using another %s format.'), $media);
129         } else {
130             $hint = '';
131         }
132         $this->clientError(sprintf(
133                                    _('%s is not a supported filetype on this server.'), $filetype) . $hint);
134     }
135
136     function isRespectsQuota($user) {
137         $file = new File;
138         $ret = $file->isRespectsQuota($user,$_FILES['attach']['size']);
139         if (true === $ret) return true;
140         $this->clientError($ret);
141     }
142
143     /**
144      * Save a new notice, based on arguments
145      *
146      * If successful, will show the notice, or return an Ajax-y result.
147      * If not, it will show an error message -- possibly Ajax-y.
148      *
149      * Also, if the notice input looks like a command, it will run the
150      * command and show the results -- again, possibly ajaxy.
151      *
152      * @return void
153      */
154
155     function saveNewNotice()
156     {
157         $user = common_current_user();
158         assert($user); // XXX: maybe an error instead...
159         $content = $this->trimmed('status_textarea');
160
161         if (!$content) {
162             $this->clientError(_('No content!'));
163         } else {
164             $content_shortened = common_shorten_links($content);
165             if (mb_strlen($content_shortened) > 140) {
166                 $this->clientError(_('That\'s too long. '.
167                                      'Max notice size is 140 chars.'));
168             }
169         }
170
171         $inter = new CommandInterpreter();
172
173         $cmd = $inter->handle_command($user, $content_shortened);
174
175         if ($cmd) {
176             if ($this->boolean('ajax')) {
177                 $cmd->execute(new AjaxWebChannel($this));
178             } else {
179                 $cmd->execute(new WebChannel($this));
180             }
181             return;
182         }
183
184         $replyto = $this->trimmed('inreplyto');
185         #If an ID of 0 is wrongly passed here, it will cause a database error,
186         #so override it...
187         if ($replyto == 0) {
188             $replyto = 'false';
189         }
190
191         if (isset($_FILES['attach']['error'])) {
192             switch ($_FILES['attach']['error']) {
193              case UPLOAD_ERR_NO_FILE:
194                 // no file uploaded, nothing to do
195                 break;
196
197              case UPLOAD_ERR_OK:
198                 $mimetype = $this->getUploadedFileType();
199                 if (!$this->isRespectsQuota($user)) {
200                     die('clientError() should trigger an exception before reaching here.');
201                 }
202                 break;
203
204              case UPLOAD_ERR_INI_SIZE:
205                 $this->clientError(_('The uploaded file exceeds the upload_max_filesize directive in php.ini.'));
206
207              case UPLOAD_ERR_FORM_SIZE:
208                 $this->clientError(_('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'));
209
210              case UPLOAD_ERR_PARTIAL:
211                 $this->clientError(_('The uploaded file was only partially uploaded.'));
212
213              case  UPLOAD_ERR_NO_TMP_DIR:
214                 $this->clientError(_('Missing a temporary folder.'));
215
216              case UPLOAD_ERR_CANT_WRITE:
217                 $this->clientError(_('Failed to write file to disk.'));
218
219              case UPLOAD_ERR_EXTENSION:
220                 $this->clientError(_('File upload stopped by extension.'));
221
222              default:
223                 die('Should never reach here.');
224             }
225         }
226
227         if (isset($mimetype)) {
228             $filename = $this->saveFile($mimetype);
229             if (empty($filename)) {
230                 $this->clientError(_('Couldn\'t save file.'));
231             }
232
233             $fileRecord = $this->storeFile($filename, $mimetype);
234
235             $fileurl = common_local_url('attachment',
236                                         array('attachment' => $fileRecord->id));
237
238             // not sure this is necessary -- Zach
239             $this->maybeAddRedir($fileRecord->id, $fileurl);
240
241             $short_fileurl = common_shorten_url($fileurl);
242             if (!$short_fileurl) {
243                 // todo -- Consider forcing default shortener if none selected?
244                 $short_fileurl = $fileurl;
245             }
246             $content_shortened .= ' ' . $short_fileurl;
247
248             if (mb_strlen($content_shortened) > 140) {
249                 $this->deleteFile($filename);
250                 $this->clientError(_('Max notice size is 140 chars, including attachment URL.'));
251             }
252
253             // Also, not sure this is necessary -- Zach
254             $this->maybeAddRedir($fileRecord->id, $short_fileurl);
255         }
256
257         $notice = Notice::saveNew($user->id, $content_shortened, 'web', 1,
258                                   ($replyto == 'false') ? null : $replyto);
259
260         if (is_string($notice)) {
261             if (isset($filename)) {
262                 $this->deleteFile($filename);
263             }
264             $this->clientError($notice);
265         }
266
267         if (isset($mimetype)) {
268             $this->attachFile($notice, $fileRecord);
269         }
270
271         common_broadcast_notice($notice);
272
273         if ($this->boolean('ajax')) {
274             $this->startHTML('text/xml;charset=utf-8');
275             $this->elementStart('head');
276             $this->element('title', null, _('Notice posted'));
277             $this->elementEnd('head');
278             $this->elementStart('body');
279             $this->showNotice($notice);
280             $this->elementEnd('body');
281             $this->elementEnd('html');
282         } else {
283             $returnto = $this->trimmed('returnto');
284
285             if ($returnto) {
286                 $url = common_local_url($returnto,
287                                         array('nickname' => $user->nickname));
288             } else {
289                 $url = common_local_url('shownotice',
290                                         array('notice' => $notice->id));
291             }
292             common_redirect($url, 303);
293         }
294     }
295
296     function saveFile($mimetype) {
297
298         $cur = common_current_user();
299
300         if (empty($cur)) {
301             $this->serverError(_('Somehow lost the login in saveFile'));
302         }
303
304         $basename = basename($_FILES['attach']['name']);
305
306         $filename = File::filename($cur->getProfile(), $basename, $mimetype);
307
308         $filepath = File::path($filename);
309
310         if (move_uploaded_file($_FILES['attach']['tmp_name'], $filepath)) {
311             return $filename;
312         } else {
313             $this->clientError(_('File could not be moved to destination directory.'));
314         }
315     }
316
317     function deleteFile($filename)
318     {
319         $filepath = File::path($filename);
320         @unlink($filepath);
321     }
322
323     function storeFile($filename, $mimetype) {
324
325         $file = new File;
326         $file->filename = $filename;
327
328         $file->url = File::url($filename);
329
330         $filepath = File::path($filename);
331
332         $file->size = filesize($filepath);
333         $file->date = time();
334         $file->mimetype = $mimetype;
335
336         $file_id = $file->insert();
337
338         if (!$file_id) {
339             common_log_db_error($file, "INSERT", __FILE__);
340             $this->clientError(_('There was a database error while saving your file. Please try again.'));
341         }
342
343         return $file;
344     }
345
346     function rememberFile($file, $short)
347     {
348         $this->maybeAddRedir($file->id, $short);
349     }
350
351     function maybeAddRedir($file_id, $url)
352     {
353         $file_redir = File_redirection::staticGet('url', $url);
354
355         if (empty($file_redir)) {
356             $file_redir = new File_redirection;
357             $file_redir->url = $url;
358             $file_redir->file_id = $file_id;
359
360             $result = $file_redir->insert();
361
362             if (!$result) {
363                 common_log_db_error($file_redir, "INSERT", __FILE__);
364                 $this->clientError(_('There was a database error while saving your file. Please try again.'));
365             }
366         }
367     }
368
369     function attachFile($notice, $filerec)
370     {
371         File_to_post::processNew($filerec->id, $notice->id);
372
373         $this->maybeAddRedir($filerec->id,
374                              common_local_url('file', array('notice' => $notice->id)));
375     }
376
377     /**
378      * Show an Ajax-y error message
379      *
380      * Goes back to the browser, where it's shown in a popup.
381      *
382      * @param string $msg Message to show
383      *
384      * @return void
385      */
386
387     function ajaxErrorMsg($msg)
388     {
389         $this->startHTML('text/xml;charset=utf-8', true);
390         $this->elementStart('head');
391         $this->element('title', null, _('Ajax Error'));
392         $this->elementEnd('head');
393         $this->elementStart('body');
394         $this->element('p', array('id' => 'error'), $msg);
395         $this->elementEnd('body');
396         $this->elementEnd('html');
397     }
398
399     /**
400      * Formerly page output
401      *
402      * This used to be the whole page output; now that's been largely
403      * subsumed by showPage. So this just stores an error message, if
404      * it was passed, and calls showPage.
405      *
406      * Note that since we started doing Ajax output, this page is rarely
407      * seen.
408      *
409      * @param string $msg An error message, if any
410      *
411      * @return void
412      */
413
414     function showForm($msg=null)
415     {
416         if ($msg && $this->boolean('ajax')) {
417             $this->ajaxErrorMsg($msg);
418             return;
419         }
420
421         $this->msg = $msg;
422         $this->showPage();
423     }
424
425     /**
426      * Overload for replies or bad results
427      *
428      * We show content in the notice form if there were replies or results.
429      *
430      * @return void
431      */
432
433     function showNoticeForm()
434     {
435         $content = $this->trimmed('status_textarea');
436         if (!$content) {
437             $replyto = $this->trimmed('replyto');
438             $inreplyto = $this->trimmed('inreplyto');
439             $profile = Profile::staticGet('nickname', $replyto);
440             if ($profile) {
441                 $content = '@' . $profile->nickname . ' ';
442             }
443         }
444
445         $notice_form = new NoticeForm($this, '', $content, null, $inreplyto);
446         $notice_form->show();
447     }
448
449     /**
450      * Show an error message
451      *
452      * Shows an error message if there is one.
453      *
454      * @return void
455      *
456      * @todo maybe show some instructions?
457      */
458
459     function showPageNotice()
460     {
461         if ($this->msg) {
462             $this->element('p', array('id' => 'error'), $this->msg);
463         }
464     }
465
466     /**
467      * Output a notice
468      *
469      * Used to generate the notice code for Ajax results.
470      *
471      * @param Notice $notice Notice that was saved
472      *
473      * @return void
474      */
475
476     function showNotice($notice)
477     {
478         $nli = new NoticeListItem($notice, $this);
479         $nli->show();
480     }
481 }
482