]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/newnotice.php
Merge branch '0.9.x' of git@gitorious.org:statusnet/mainline into 0.9.x
[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 (Notice::contentTooLong($content_shortened)) {
166                 $this->clientError(sprintf(_('That\'s too long. '.
167                                              'Max notice size is %d chars.'),
168                                            Notice::maxContent()));
169             }
170         }
171
172         $inter = new CommandInterpreter();
173
174         $cmd = $inter->handle_command($user, $content_shortened);
175
176         if ($cmd) {
177             if ($this->boolean('ajax')) {
178                 $cmd->execute(new AjaxWebChannel($this));
179             } else {
180                 $cmd->execute(new WebChannel($this));
181             }
182             return;
183         }
184
185         $replyto = $this->trimmed('inreplyto');
186         #If an ID of 0 is wrongly passed here, it will cause a database error,
187         #so override it...
188         if ($replyto == 0) {
189             $replyto = 'false';
190         }
191
192         if (isset($_FILES['attach']['error'])) {
193             switch ($_FILES['attach']['error']) {
194              case UPLOAD_ERR_NO_FILE:
195                 // no file uploaded, nothing to do
196                 break;
197
198              case UPLOAD_ERR_OK:
199                 $mimetype = $this->getUploadedFileType();
200                 if (!$this->isRespectsQuota($user)) {
201                     die('clientError() should trigger an exception before reaching here.');
202                 }
203                 break;
204
205              case UPLOAD_ERR_INI_SIZE:
206                 $this->clientError(_('The uploaded file exceeds the upload_max_filesize directive in php.ini.'));
207
208              case UPLOAD_ERR_FORM_SIZE:
209                 $this->clientError(_('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'));
210
211              case UPLOAD_ERR_PARTIAL:
212                 $this->clientError(_('The uploaded file was only partially uploaded.'));
213
214              case  UPLOAD_ERR_NO_TMP_DIR:
215                 $this->clientError(_('Missing a temporary folder.'));
216
217              case UPLOAD_ERR_CANT_WRITE:
218                 $this->clientError(_('Failed to write file to disk.'));
219
220              case UPLOAD_ERR_EXTENSION:
221                 $this->clientError(_('File upload stopped by extension.'));
222
223              default:
224                 die('Should never reach here.');
225             }
226         }
227
228         if (isset($mimetype)) {
229             $filename = $this->saveFile($mimetype);
230             if (empty($filename)) {
231                 $this->clientError(_('Couldn\'t save file.'));
232             }
233
234             $fileRecord = $this->storeFile($filename, $mimetype);
235
236             $fileurl = common_local_url('attachment',
237                                         array('attachment' => $fileRecord->id));
238
239             // not sure this is necessary -- Zach
240             $this->maybeAddRedir($fileRecord->id, $fileurl);
241
242             $short_fileurl = common_shorten_url($fileurl);
243             if (!$short_fileurl) {
244                 // todo -- Consider forcing default shortener if none selected?
245                 $short_fileurl = $fileurl;
246             }
247             $content_shortened .= ' ' . $short_fileurl;
248
249             if (Notice::contentTooLong($content_shortened)) {
250                 $this->deleteFile($filename);
251                 $this->clientError(sprintf(_('Max notice size is %d chars, including attachment URL.'),
252                                            Notice::maxContent()));
253             }
254
255             // Also, not sure this is necessary -- Zach
256             $this->maybeAddRedir($fileRecord->id, $short_fileurl);
257         }
258
259         $notice = Notice::saveNew($user->id, $content_shortened, 'web', 1,
260                                   ($replyto == 'false') ? null : $replyto);
261
262         if (isset($mimetype)) {
263             $this->attachFile($notice, $fileRecord);
264         }
265
266         common_broadcast_notice($notice);
267
268         if ($this->boolean('ajax')) {
269             $this->startHTML('text/xml;charset=utf-8');
270             $this->elementStart('head');
271             $this->element('title', null, _('Notice posted'));
272             $this->elementEnd('head');
273             $this->elementStart('body');
274             $this->showNotice($notice);
275             $this->elementEnd('body');
276             $this->elementEnd('html');
277         } else {
278             $returnto = $this->trimmed('returnto');
279
280             if ($returnto) {
281                 $url = common_local_url($returnto,
282                                         array('nickname' => $user->nickname));
283             } else {
284                 $url = common_local_url('shownotice',
285                                         array('notice' => $notice->id));
286             }
287             common_redirect($url, 303);
288         }
289     }
290
291     function saveFile($mimetype) {
292
293         $cur = common_current_user();
294
295         if (empty($cur)) {
296             $this->serverError(_('Somehow lost the login in saveFile'));
297         }
298
299         $basename = basename($_FILES['attach']['name']);
300
301         $filename = File::filename($cur->getProfile(), $basename, $mimetype);
302
303         $filepath = File::path($filename);
304
305         if (move_uploaded_file($_FILES['attach']['tmp_name'], $filepath)) {
306             return $filename;
307         } else {
308             $this->clientError(_('File could not be moved to destination directory.'));
309         }
310     }
311
312     function deleteFile($filename)
313     {
314         $filepath = File::path($filename);
315         @unlink($filepath);
316     }
317
318     function storeFile($filename, $mimetype) {
319
320         $file = new File;
321         $file->filename = $filename;
322
323         $file->url = File::url($filename);
324
325         $filepath = File::path($filename);
326
327         $file->size = filesize($filepath);
328         $file->date = time();
329         $file->mimetype = $mimetype;
330
331         $file_id = $file->insert();
332
333         if (!$file_id) {
334             common_log_db_error($file, "INSERT", __FILE__);
335             $this->clientError(_('There was a database error while saving your file. Please try again.'));
336         }
337
338         return $file;
339     }
340
341     function rememberFile($file, $short)
342     {
343         $this->maybeAddRedir($file->id, $short);
344     }
345
346     function maybeAddRedir($file_id, $url)
347     {
348         $file_redir = File_redirection::staticGet('url', $url);
349
350         if (empty($file_redir)) {
351             $file_redir = new File_redirection;
352             $file_redir->url = $url;
353             $file_redir->file_id = $file_id;
354
355             $result = $file_redir->insert();
356
357             if (!$result) {
358                 common_log_db_error($file_redir, "INSERT", __FILE__);
359                 $this->clientError(_('There was a database error while saving your file. Please try again.'));
360             }
361         }
362     }
363
364     function attachFile($notice, $filerec)
365     {
366         File_to_post::processNew($filerec->id, $notice->id);
367
368         $this->maybeAddRedir($filerec->id,
369                              common_local_url('file', array('notice' => $notice->id)));
370     }
371
372     /**
373      * Show an Ajax-y error message
374      *
375      * Goes back to the browser, where it's shown in a popup.
376      *
377      * @param string $msg Message to show
378      *
379      * @return void
380      */
381
382     function ajaxErrorMsg($msg)
383     {
384         $this->startHTML('text/xml;charset=utf-8', true);
385         $this->elementStart('head');
386         $this->element('title', null, _('Ajax Error'));
387         $this->elementEnd('head');
388         $this->elementStart('body');
389         $this->element('p', array('id' => 'error'), $msg);
390         $this->elementEnd('body');
391         $this->elementEnd('html');
392     }
393
394     /**
395      * Formerly page output
396      *
397      * This used to be the whole page output; now that's been largely
398      * subsumed by showPage. So this just stores an error message, if
399      * it was passed, and calls showPage.
400      *
401      * Note that since we started doing Ajax output, this page is rarely
402      * seen.
403      *
404      * @param string $msg An error message, if any
405      *
406      * @return void
407      */
408
409     function showForm($msg=null)
410     {
411         if ($msg && $this->boolean('ajax')) {
412             $this->ajaxErrorMsg($msg);
413             return;
414         }
415
416         $this->msg = $msg;
417         $this->showPage();
418     }
419
420     /**
421      * Overload for replies or bad results
422      *
423      * We show content in the notice form if there were replies or results.
424      *
425      * @return void
426      */
427
428     function showNoticeForm()
429     {
430         $content = $this->trimmed('status_textarea');
431         if (!$content) {
432             $replyto = $this->trimmed('replyto');
433             $inreplyto = $this->trimmed('inreplyto');
434             $profile = Profile::staticGet('nickname', $replyto);
435             if ($profile) {
436                 $content = '@' . $profile->nickname . ' ';
437             }
438         }
439
440         $notice_form = new NoticeForm($this, '', $content, null, $inreplyto);
441         $notice_form->show();
442     }
443
444     /**
445      * Show an error message
446      *
447      * Shows an error message if there is one.
448      *
449      * @return void
450      *
451      * @todo maybe show some instructions?
452      */
453
454     function showPageNotice()
455     {
456         if ($this->msg) {
457             $this->element('p', array('id' => 'error'), $this->msg);
458         }
459     }
460
461     /**
462      * Output a notice
463      *
464      * Used to generate the notice code for Ajax results.
465      *
466      * @param Notice $notice Notice that was saved
467      *
468      * @return void
469      */
470
471     function showNotice($notice)
472     {
473         $nli = new NoticeListItem($notice, $this);
474         $nli->show();
475     }
476 }
477