]> git.mxchange.org Git - friendica.git/blob - mod/item.php
5b40a67de20b9ee2369d6b34414846d491d75652
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * This is the POST destination for most all locally posted
21  * text stuff. This function handles status, wall-to-wall status,
22  * local comments, and remote coments that are posted on this site
23  * (as opposed to being delivered in a feed).
24  * Also processed here are posts and comments coming through the
25  * statusnet/twitter API.
26  *
27  * All of these become an "item" which is our basic unit of
28  * information.
29  */
30
31 use Friendica\App;
32 use Friendica\Content\Text\BBCode;
33 use Friendica\Core\Hook;
34 use Friendica\Core\Logger;
35 use Friendica\Core\Protocol;
36 use Friendica\Core\System;
37 use Friendica\Core\Worker;
38 use Friendica\Database\DBA;
39 use Friendica\DI;
40 use Friendica\Model\Contact;
41 use Friendica\Model\Item;
42 use Friendica\Model\ItemURI;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Network\HTTPException;
46 use Friendica\Protocol\Activity;
47 use Friendica\Util\DateTimeFormat;
48
49 function item_post(App $a) {
50         $uid = DI::userSession()->getLocalUserId();
51
52         if (!DI::userSession()->isAuthenticated() || !$uid) {
53                 throw new HTTPException\ForbiddenException();
54         }
55
56         if (!empty($_REQUEST['dropitems'])) {
57                 $arr_drop = explode(',', $_REQUEST['dropitems']);
58                 foreach ($arr_drop as $item) {
59                         Item::deleteForUser(['id' => $item], $uid);
60                 }
61
62                 $json = ['success' => 1];
63                 System::jsonExit($json);
64         }
65
66         Hook::callAll('post_local_start', $_REQUEST);
67
68         $return_path = $_REQUEST['return'] ?? '';
69         $preview     = intval($_REQUEST['preview'] ?? 0);
70
71         /*
72          * Check for doubly-submitted posts, and reject duplicates
73          * Note that we have to ignore previews, otherwise nothing will post
74          * after it's been previewed
75          */
76         if (!$preview && !empty($_REQUEST['post_id_random'])) {
77                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
78                         Logger::warning('duplicate post');
79                         item_post_return(DI::baseUrl(), $return_path);
80                 } else {
81                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
82                 }
83         }
84
85         $post_id = intval($_REQUEST['post_id'] ?? 0);
86
87         // is this an edited post?
88         if ($post_id > 0) {
89                 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
90         } else {
91                 $orig_post = null;
92         }
93
94         $emailcc = trim($_REQUEST['emailcc']  ?? '');
95
96         $post = ['uid' => $uid];
97
98         $post = DI::contentItem()->initializePost($post);
99
100         $post['edit']       = $orig_post;
101         $post['self']       = true;
102         $post['api_source'] = false;
103         $post['file']       = '';
104         $post['attach']     = '';
105         $post['inform']     = '';
106         $post['postopts']   = '';
107         $post['wall']       = $_REQUEST['wall'] ?? true;
108         $post['post-type']  = $_REQUEST['post_type'] ?? '';
109         $post['title']      = trim($_REQUEST['title'] ?? '');
110         $post['body']       = $_REQUEST['body'] ?? '';
111         $post['location']   = trim($_REQUEST['location'] ?? '');
112         $post['coord']      = trim($_REQUEST['coord'] ?? '');
113         $post['parent']     = intval($_REQUEST['parent'] ?? 0);
114         $post['pubmail']    = $_REQUEST['pubmail_enable'] ?? false;
115         $post['created']    = $_REQUEST['created_at'] ?? DateTimeFormat::utcNow();
116         $post['edited']     = $post['changed'] = $post['commented'] = $post['created'];
117         $post['app']        = '';
118
119         if ($post['parent']) {
120                 if ($post['parent']) {
121                         $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post['parent']]);
122                 }
123
124                 // if this isn't the top-level parent of the conversation, find it
125                 if (DBA::isResult($parent_item)) {
126                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
127                         $post['thr-parent'] = $parent_item['uri'];
128                         $toplevel_item = $parent_item;
129
130                         if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
131                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
132                         }
133                 }
134
135                 if (!DBA::isResult($toplevel_item)) {
136                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
137                         if ($return_path) {
138                                 DI::baseUrl()->redirect($return_path);
139                         }
140                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
141                 }
142
143                 // When commenting on a public post then store the post for the current user
144                 // This enables interaction like starring and saving into folders
145                 if ($toplevel_item['uid'] == 0) {
146                         $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]);
147                         Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]);
148                         if ($stored) {
149                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
150                         }
151                 }
152
153                 $post['parent']      = $toplevel_item['id'];
154                 $post['gravity']     = Item::GRAVITY_COMMENT;
155                 $post['wall']        = $toplevel_item['wall'];
156         } else {
157                 $parent_item         = [];
158                 $post['parent']      = 0;
159                 $post['gravity']     = Item::GRAVITY_PARENT;
160                 $post['thr-parent']  = $post['uri'];
161         }
162
163         $post = DI::contentItem()->getACL($post, $parent_item, $_REQUEST);
164
165         $post['pubmail'] = $post['pubmail'] && !$post['private'];
166
167         if (!empty($orig_post)) {
168                 $post['file'] = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
169         }
170
171         $post = DI::contentItem()->addCategories($post, $_REQUEST['category'] ?? '');
172
173         if (!$preview) {
174                 if (Photo::setPermissionFromBody($post['body'], $post['uid'], $post['contact-id'], $post['allow_cid'], $post['allow_gid'], $post['deny_cid'], $post['deny_gid'])) {
175                         $post['object-type'] = Activity\ObjectType::IMAGE;
176                 }
177
178                 $post = DI::contentItem()->moveAttachmentsFromBodyToAttach($post);
179         }
180
181         // Add the attachment to the body.
182         if (!empty($_REQUEST['has_attachment'])) {
183                 $post['body'] .= DI::contentItem()->storeAttachmentFromRequest($_REQUEST);
184         }
185
186         $post = DI::contentItem()->finalizePost($post);
187
188         if (!strlen($post['body'])) {
189                 if ($preview) {
190                         System::jsonExit(['preview' => '']);
191                 }
192
193                 DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
194                 if ($return_path) {
195                         DI::baseUrl()->redirect($return_path);
196                 }
197
198                 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
199         }
200
201         // preview mode - prepare the body for display and send it via json
202         if ($preview) {
203                 // We have to preset some fields, so that the conversation can be displayed
204                 $post['id']             = -1;
205                 $post['uri-id']         = -1;
206                 $post['author-network'] = Protocol::DFRN;
207                 $post['author-updated'] = '';
208                 $post['author-gsid']    = 0;
209                 $post['author-uri-id']  = ItemURI::getIdByURI($post['author-link']);
210                 $post['owner-updated']  = '';
211                 $post['has-media']      = false;
212                 $post['quote-uri-id']   = Item::getQuoteUriId($post['body'], $post['uid']);
213                 $post['body']           = BBCode::removeSharedData(Item::setHashtags($post['body']));
214                 $post['writable']       = true;
215
216                 $o = DI::conversation()->create([$post], 'search', false, true);
217
218                 System::jsonExit(['preview' => $o]);
219         }
220
221         Hook::callAll('post_local',$post);
222
223         unset($post['edit']);
224         unset($post['self']);
225         unset($post['api_source']);
226
227         if (!empty($_REQUEST['scheduled_at'])) {
228                 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
229                 if ($scheduled_at > DateTimeFormat::utcNow()) {
230                         unset($post['created']);
231                         unset($post['edited']);
232                         unset($post['commented']);
233                         unset($post['received']);
234                         unset($post['changed']);
235
236                         Post\Delayed::add($post['uri'], $post, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
237                         item_post_return(DI::baseUrl(), $return_path);
238                 }
239         }
240
241         if (!empty($post['cancel'])) {
242                 Logger::info('mod_item: post cancelled by addon.');
243                 if ($return_path) {
244                         DI::baseUrl()->redirect($return_path);
245                 }
246
247                 $json = ['cancel' => 1];
248                 if (!empty($_REQUEST['jsreload'])) {
249                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
250                 }
251
252                 System::jsonExit($json);
253         }
254
255         if ($orig_post) {
256                 $fields = [
257                         'title'        => $post['title'],
258                         'body'         => $post['body'],
259                         'attach'       => $post['attach'],
260                         'file'         => $post['file'],
261                         'edited'       => DateTimeFormat::utcNow(),
262                         'changed'      => DateTimeFormat::utcNow()
263                 ];
264
265                 $fields['body'] = Item::setHashtags($fields['body']);
266
267                 $quote_uri_id = Item::getQuoteUriId($fields['body'], $post['uid']);
268                 if (!empty($quote_uri_id)) {
269                         $fields['quote-uri-id'] = $quote_uri_id;
270                         $fields['body']         = BBCode::removeSharedData($post['body']);
271                 }
272
273                 Item::update($fields, ['id' => $post_id]);
274                 Item::updateDisplayCache($orig_post['uri-id']);
275
276                 if ($return_path) {
277                         DI::baseUrl()->redirect($return_path);
278                 }
279
280                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
281         }
282
283         $post_id = Item::insert($post);
284         if (!$post_id) {
285                 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
286                 if ($return_path) {
287                         DI::baseUrl()->redirect($return_path);
288                 }
289
290                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
291         }
292
293         $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
294         if (!DBA::isResult($post)) {
295                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
296                 if ($return_path) {
297                         DI::baseUrl()->redirect($return_path);
298                 }
299
300                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
301         }
302
303         $recipients = explode(',', $emailcc);
304
305         DI::contentItem()->postProcessPost($post, $recipients);
306
307         Logger::debug('post_complete');
308
309         item_post_return(DI::baseUrl(), $return_path);
310         // NOTREACHED
311 }
312
313 function item_post_return($baseurl, $return_path)
314 {
315         if ($return_path) {
316                 DI::baseUrl()->redirect($return_path);
317         }
318
319         $json = ['success' => 1];
320         if (!empty($_REQUEST['jsreload'])) {
321                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
322         }
323
324         Logger::debug('post_json', ['json' => $json]);
325
326         System::jsonExit($json);
327 }
328
329 function item_content(App $a)
330 {
331         if (!DI::userSession()->isAuthenticated()) {
332                 throw new HTTPException\UnauthorizedException();
333         }
334
335         $args = DI::args();
336
337         if (!$args->has(3)) {
338                 throw new HTTPException\BadRequestException();
339         }
340
341         $o = '';
342         switch ($args->get(1)) {
343                 case 'drop':
344                         if (DI::mode()->isAjax()) {
345                                 Item::deleteForUser(['id' => $args->get(2)], DI::userSession()->getLocalUserId());
346                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
347                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
348                         } else {
349                                 if (!empty($args->get(3))) {
350                                         $o = drop_item($args->get(2), $args->get(3));
351                                 } else {
352                                         $o = drop_item($args->get(2));
353                                 }
354                         }
355                         break;
356
357                 case 'block':
358                         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
359                         if (empty($item['author-id'])) {
360                                 throw new HTTPException\NotFoundException('Item not found');
361                         }
362
363                         Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
364
365                         if (DI::mode()->isAjax()) {
366                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
367                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
368                         } else {
369                                 item_redirect_after_action($item, $args->get(3));
370                         }
371                         break;
372         }
373
374         return $o;
375 }
376
377 /**
378  * @param int    $id
379  * @param string $return
380  * @return string
381  * @throws HTTPException\InternalServerErrorException
382  */
383 function drop_item(int $id, string $return = ''): string
384 {
385         // Locate item to be deleted
386         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
387
388         if (!DBA::isResult($item)) {
389                 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
390                 DI::baseUrl()->redirect('network');
391                 //NOTREACHED
392         }
393
394         if ($item['deleted']) {
395                 return '';
396         }
397
398         $contact_id = 0;
399
400         // check if logged in user is either the author or owner of this item
401         if (DI::userSession()->getRemoteContactID($item['uid']) == $item['contact-id']) {
402                 $contact_id = $item['contact-id'];
403         }
404
405         if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
406                 // delete the item
407                 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
408
409                 item_redirect_after_action($item, $return);
410                 //NOTREACHED
411         } else {
412                 Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
413                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
414                 DI::baseUrl()->redirect('display/' . $item['guid']);
415                 //NOTREACHED
416         }
417
418         return '';
419 }
420
421 function item_redirect_after_action(array $item, string $returnUrlHex)
422 {
423         $return_url = hex2bin($returnUrlHex);
424
425         // removes update_* from return_url to ignore Ajax refresh
426         $return_url = str_replace('update_', '', $return_url);
427
428         // Check if delete a comment
429         if ($item['gravity'] == Item::GRAVITY_COMMENT) {
430                 if (!empty($item['parent'])) {
431                         $parentitem = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid'], ['id' => $item['parent']]);
432                 }
433
434                 // Return to parent guid
435                 if (!empty($parentitem)) {
436                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
437                         //NOTREACHED
438                 } // In case something goes wrong
439                 else {
440                         DI::baseUrl()->redirect('network');
441                         //NOTREACHED
442                 }
443         } else {
444                 // if unknown location or deleting top level post called from display
445                 if (empty($return_url) || strpos($return_url, 'display') !== false) {
446                         DI::baseUrl()->redirect('network');
447                         //NOTREACHED
448                 } else {
449                         DI::baseUrl()->redirect($return_url);
450                         //NOTREACHED
451                 }
452         }
453 }