Fix warning: Undefined array key "post-reason"
[friendica.git/.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, 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 comments 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\Conversation;
33 use Friendica\Content\Text\BBCode;
34 use Friendica\Core\Hook;
35 use Friendica\Core\Logger;
36 use Friendica\Core\Protocol;
37 use Friendica\Core\System;
38 use Friendica\Core\Worker;
39 use Friendica\Database\DBA;
40 use Friendica\DI;
41 use Friendica\Model\Contact;
42 use Friendica\Model\Item;
43 use Friendica\Model\ItemURI;
44 use Friendica\Model\Post;
45 use Friendica\Network\HTTPException;
46 use Friendica\Util\DateTimeFormat;
47
48 function item_post(App $a) {
49         $uid = DI::userSession()->getLocalUserId();
50
51         if (!$uid) {
52                 throw new HTTPException\ForbiddenException();
53         }
54
55         if (!empty($_REQUEST['dropitems'])) {
56                 item_drop($uid, $_REQUEST['dropitems']);
57         }
58
59         Hook::callAll('post_local_start', $_REQUEST);
60
61         $return_path = $_REQUEST['return'] ?? '';
62         $preview     = intval($_REQUEST['preview'] ?? 0);
63
64         /*
65          * Check for doubly-submitted posts, and reject duplicates
66          * Note that we have to ignore previews, otherwise nothing will post
67          * after it's been previewed
68          */
69         if (!$preview && !empty($_REQUEST['post_id_random'])) {
70                 if (DI::session()->get('post-random') == $_REQUEST['post_id_random']) {
71                         Logger::warning('duplicate post');
72                         item_post_return(DI::baseUrl(), $return_path);
73                 } else {
74                         DI::session()->set('post-random', $_REQUEST['post_id_random']);
75                 }
76         }
77
78         if (empty($_REQUEST['post_id'])) {
79                 item_insert($uid, $_REQUEST, $preview, $return_path);
80         } else {
81                 item_edit($uid, $_REQUEST, $preview, $return_path);
82         }
83 }
84
85 function item_drop(int $uid, string $dropitems)
86 {
87         $arr_drop = explode(',', $dropitems);
88         foreach ($arr_drop as $item) {
89                 Item::deleteForUser(['id' => $item], $uid);
90         }
91
92         System::jsonExit(['success' => 1]);
93 }
94
95 function item_edit(int $uid, array $request, bool $preview, string $return_path)
96 {
97         $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $request['post_id'], 'uid' => $uid]);
98         if (!DBA::isResult($post)) {
99                 if ($return_path) {
100                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
101                         DI::baseUrl()->redirect($return_path);
102                 }
103                 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
104         }
105
106         $post['edit'] = $post;
107         $post['file'] = Post\Category::getTextByURIId($post['uri-id'], $post['uid']);
108
109         Post\Media::deleteByURIId($post['uri-id'], [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE, Post\Media::HTML]);
110         $post = item_process($post, $request, $preview, $return_path);
111
112         $fields = [
113                 'title'    => $post['title'],
114                 'body'     => $post['body'],
115                 'attach'   => $post['attach'],
116                 'file'     => $post['file'],
117                 'location' => $post['location'],
118                 'coord'    => $post['coord'],
119                 'edited'   => DateTimeFormat::utcNow(),
120                 'changed'  => DateTimeFormat::utcNow()
121         ];
122
123         $fields['body'] = Item::setHashtags($fields['body']);
124
125         $quote_uri_id = Item::getQuoteUriId($fields['body'], $post['uid']);
126         if (!empty($quote_uri_id)) {
127                 $fields['quote-uri-id'] = $quote_uri_id;
128                 $fields['body']         = BBCode::removeSharedData($post['body']);
129         }
130
131         Item::update($fields, ['id' => $post['id']]);
132         Item::updateDisplayCache($post['uri-id']);
133
134         if ($return_path) {
135                 DI::baseUrl()->redirect($return_path);
136         }
137
138         throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
139 }
140
141 function item_insert(int $uid, array $request, bool $preview, string $return_path)
142 {
143         $post = ['uid' => $uid];
144         $post = DI::contentItem()->initializePost($post);
145
146         $post['edit']      = null;
147         $post['post-type'] = $request['post_type'] ?? '';
148         $post['wall']      = $request['wall'] ?? true;
149         $post['pubmail']   = $request['pubmail_enable'] ?? false;
150         $post['created']   = $request['created_at'] ?? DateTimeFormat::utcNow();
151         $post['edited']    = $post['changed'] = $post['commented'] = $post['created'];
152         $post['app']       = '';
153         $post['inform']    = '';
154         $post['postopts']  = '';
155         $post['file']      = '';
156
157         if (!empty($request['parent'])) {
158                 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $request['parent']]);
159                 if ($parent_item) {
160                         // if this isn't the top-level parent of the conversation, find it
161                         if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
162                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
163                         } else {
164                                 $toplevel_item = $parent_item;
165                         }
166                 }
167
168                 if (empty($toplevel_item)) {
169                         if ($return_path) {
170                                 DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
171                                 DI::baseUrl()->redirect($return_path);
172                         }
173                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
174                 }
175
176                 // When commenting on a public post then store the post for the current user
177                 // This enables interaction like starring and saving into folders
178                 if ($toplevel_item['uid'] == 0) {
179                         $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]);
180                         Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]);
181                 }
182
183                 $post['parent']      = $toplevel_item['id'];
184                 $post['gravity']     = Item::GRAVITY_COMMENT;
185                 $post['thr-parent']  = $parent_item['uri'];
186                 $post['wall']        = $toplevel_item['wall'];
187         } else {
188                 $parent_item         = [];
189                 $post['parent']      = 0;
190                 $post['gravity']     = Item::GRAVITY_PARENT;
191                 $post['thr-parent']  = $post['uri'];
192         }
193
194         $post = DI::contentItem()->getACL($post, $parent_item, $request);
195
196         $post['pubmail'] = $post['pubmail'] && !$post['private'];
197
198         $post = item_process($post, $request, $preview, $return_path);
199
200         $post_id = Item::insert($post);
201         if (!$post_id) {
202                 if ($return_path) {
203                         DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
204                         DI::baseUrl()->redirect($return_path);
205                 }
206
207                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
208         }
209
210         $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
211         if (!$post) {
212                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
213                 if ($return_path) {
214                         DI::baseUrl()->redirect($return_path);
215                 }
216
217                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
218         }
219
220         $recipients = explode(',', $request['emailcc'] ?? '');
221
222         DI::contentItem()->postProcessPost($post, $recipients);
223
224         if (($post['private'] == Item::PRIVATE) && ($post['thr-parent-id'] != $post['uri-id'])) {
225                 DI::contentItem()->copyPermissions($post['thr-parent-id'], $post['uri-id'], $post['parent-uri-id']);
226         }
227
228         Logger::debug('post_complete');
229
230         item_post_return(DI::baseUrl(), $return_path);
231         // NOTREACHED
232 }
233
234 function item_process(array $post, array $request, bool $preview, string $return_path): array
235 {
236         $post['self']       = true;
237         $post['api_source'] = false;
238         $post['attach']     = '';
239         $post['title']      = trim($request['title'] ?? '');
240         $post['body']       = $request['body'] ?? '';
241         $post['location']   = trim($request['location'] ?? '');
242         $post['coord']      = trim($request['coord'] ?? '');
243
244         $post = DI::contentItem()->addCategories($post, $request['category'] ?? '');
245
246         // Add the attachment to the body.
247         if (!empty($request['has_attachment'])) {
248                 $post['body'] .= DI::contentItem()->storeAttachmentFromRequest($request);
249         }
250
251         $post = DI::contentItem()->finalizePost($post);
252
253         if (!strlen($post['body'])) {
254                 if ($preview) {
255                         System::jsonExit(['preview' => '']);
256                 }
257
258                 if ($return_path) {
259                         DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
260                         DI::baseUrl()->redirect($return_path);
261                 }
262
263                 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
264         }
265
266         // preview mode - prepare the body for display and send it via json
267         if ($preview) {
268                 // We have to preset some fields, so that the conversation can be displayed
269                 $post['id']             = -1;
270                 $post['uri-id']         = -1;
271                 $post['author-network'] = Protocol::DFRN;
272                 $post['author-updated'] = '';
273                 $post['author-alias']   = '';
274                 $post['author-gsid']    = 0;
275                 $post['author-uri-id']  = ItemURI::getIdByURI($post['author-link']);
276                 $post['owner-updated']  = '';
277                 $post['has-media']      = false;
278                 $post['quote-uri-id']   = Item::getQuoteUriId($post['body'], $post['uid']);
279                 $post['body']           = BBCode::removeSharedData(Item::setHashtags($post['body']));
280                 $post['writable']       = true;
281                 $post['sensitive']      = false;
282                 $post['post-reason']    = Item::PR_LOCAL;
283
284                 $o = DI::conversation()->render([$post], Conversation::MODE_SEARCH, false, true);
285
286                 System::jsonExit(['preview' => $o]);
287         }
288
289         Hook::callAll('post_local',$post);
290
291         unset($post['edit']);
292         unset($post['self']);
293         unset($post['api_source']);
294
295         if (!empty($request['scheduled_at'])) {
296                 $scheduled_at = DateTimeFormat::convert($request['scheduled_at'], 'UTC', DI::app()->getTimeZone());
297                 if ($scheduled_at > DateTimeFormat::utcNow()) {
298                         unset($post['created']);
299                         unset($post['edited']);
300                         unset($post['commented']);
301                         unset($post['received']);
302                         unset($post['changed']);
303
304                         Post\Delayed::add($post['uri'], $post, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
305                         item_post_return(DI::baseUrl(), $return_path);
306                 }
307         }
308
309         if (!empty($post['cancel'])) {
310                 Logger::info('mod_item: post cancelled by addon.');
311                 if ($return_path) {
312                         DI::baseUrl()->redirect($return_path);
313                 }
314
315                 $json = ['cancel' => 1];
316                 if (!empty($request['jsreload'])) {
317                         $json['reload'] = DI::baseUrl() . '/' . $request['jsreload'];
318                 }
319
320                 System::jsonExit($json);
321         }
322
323         return $post;
324 }
325
326 function item_post_return($baseurl, $return_path)
327 {
328         if ($return_path) {
329                 DI::baseUrl()->redirect($return_path);
330         }
331
332         $json = ['success' => 1];
333         if (!empty($_REQUEST['jsreload'])) {
334                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
335         }
336
337         Logger::debug('post_json', ['json' => $json]);
338
339         System::jsonExit($json);
340 }
341
342 function item_content(App $a)
343 {
344         if (!DI::userSession()->isAuthenticated()) {
345                 throw new HTTPException\UnauthorizedException();
346         }
347
348         $args = DI::args();
349
350         if (!$args->has(2)) {
351                 throw new HTTPException\BadRequestException();
352         }
353
354         $o = '';
355         switch ($args->get(1)) {
356                 case 'drop':
357                         if (DI::mode()->isAjax()) {
358                                 Item::deleteForUser(['id' => $args->get(2)], DI::userSession()->getLocalUserId());
359                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
360                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
361                         } else {
362                                 if (!empty($args->get(3))) {
363                                         $o = drop_item($args->get(2), $args->get(3));
364                                 } else {
365                                         $o = drop_item($args->get(2));
366                                 }
367                         }
368                         break;
369
370                 case 'block':
371                         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
372                         if (empty($item['author-id'])) {
373                                 throw new HTTPException\NotFoundException('Item not found');
374                         }
375
376                         Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
377
378                         if (DI::mode()->isAjax()) {
379                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
380                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
381                         } else {
382                                 item_redirect_after_action($item, $args->get(3));
383                         }
384                         break;
385
386                 case 'ignore':
387                         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
388                         if (empty($item['author-id'])) {
389                                 throw new HTTPException\NotFoundException('Item not found');
390                         }
391
392                         Contact\User::setIgnored($item['author-id'], DI::userSession()->getLocalUserId(), true);
393
394                         if (DI::mode()->isAjax()) {
395                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
396                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
397                         } else {
398                                 item_redirect_after_action($item, $args->get(3));
399                         }
400                         break;
401
402                 case 'collapse':
403                         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
404                         if (empty($item['author-id'])) {
405                                 throw new HTTPException\NotFoundException('Item not found');
406                         }
407
408                         Contact\User::setCollapsed($item['author-id'], DI::userSession()->getLocalUserId(), true);
409
410                         if (DI::mode()->isAjax()) {
411                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
412                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
413                         } else {
414                                 item_redirect_after_action($item, $args->get(3));
415                         }
416                         break;
417         }
418
419         return $o;
420 }
421
422 /**
423  * @param int    $id
424  * @param string $return
425  * @return string
426  * @throws HTTPException\InternalServerErrorException
427  */
428 function drop_item(int $id, string $return = ''): string
429 {
430         // Locate item to be deleted
431         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
432
433         if (!DBA::isResult($item)) {
434                 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
435                 DI::baseUrl()->redirect('network');
436                 //NOTREACHED
437         }
438
439         if ($item['deleted']) {
440                 return '';
441         }
442
443         $contact_id = 0;
444
445         // check if logged in user is either the author or owner of this item
446         if (DI::userSession()->getRemoteContactID($item['uid']) == $item['contact-id']) {
447                 $contact_id = $item['contact-id'];
448         }
449
450         if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
451                 // delete the item
452                 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
453
454                 item_redirect_after_action($item, $return);
455                 //NOTREACHED
456         } else {
457                 Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
458                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
459                 DI::baseUrl()->redirect('display/' . $item['guid']);
460                 //NOTREACHED
461         }
462
463         return '';
464 }
465
466 function item_redirect_after_action(array $item, string $returnUrlHex)
467 {
468         $return_url = hex2bin($returnUrlHex);
469
470         // removes update_* from return_url to ignore Ajax refresh
471         $return_url = str_replace('update_', '', $return_url);
472
473         // Check if delete a comment
474         if ($item['gravity'] == Item::GRAVITY_COMMENT) {
475                 if (!empty($item['parent'])) {
476                         $parentitem = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid'], ['id' => $item['parent']]);
477                 }
478
479                 // Return to parent guid
480                 if (!empty($parentitem)) {
481                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
482                         //NOTREACHED
483                 } // In case something goes wrong
484                 else {
485                         DI::baseUrl()->redirect('network');
486                         //NOTREACHED
487                 }
488         } else {
489                 // if unknown location or deleting top level post called from display
490                 if (empty($return_url) || strpos($return_url, 'display') !== false) {
491                         DI::baseUrl()->redirect('network');
492                         //NOTREACHED
493                 } else {
494                         DI::baseUrl()->redirect($return_url);
495                         //NOTREACHED
496                 }
497         }
498 }