]> git.mxchange.org Git - friendica.git/blob - mod/item.php
b62841e47dbcc3ccc960afc569a86dc62ebd621b
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\Item as ItemHelper;
33 use Friendica\Content\PageInfo;
34 use Friendica\Content\Text\BBCode;
35 use Friendica\Core\Hook;
36 use Friendica\Core\Logger;
37 use Friendica\Core\Protocol;
38 use Friendica\Core\Session;
39 use Friendica\Core\System;
40 use Friendica\Core\Worker;
41 use Friendica\Database\DBA;
42 use Friendica\DI;
43 use Friendica\Model\APContact;
44 use Friendica\Model\Attach;
45 use Friendica\Model\Contact;
46 use Friendica\Model\Conversation;
47 use Friendica\Model\FileTag;
48 use Friendica\Model\Item;
49 use Friendica\Model\ItemURI;
50 use Friendica\Model\Notification;
51 use Friendica\Model\Photo;
52 use Friendica\Model\Post;
53 use Friendica\Model\Tag;
54 use Friendica\Model\User;
55 use Friendica\Network\HTTPException;
56 use Friendica\Object\EMail\ItemCCEMail;
57 use Friendica\Protocol\Activity;
58 use Friendica\Protocol\Diaspora;
59 use Friendica\Security\Security;
60 use Friendica\Util\DateTimeFormat;
61 use Friendica\Util\ParseUrl;
62 use Friendica\Worker\Delivery;
63
64 function item_post(App $a) {
65         if (!Session::isAuthenticated()) {
66                 throw new HTTPException\ForbiddenException();
67         }
68
69         $uid = local_user();
70
71         if (!empty($_REQUEST['dropitems'])) {
72                 $arr_drop = explode(',', $_REQUEST['dropitems']);
73                 foreach ($arr_drop as $item) {
74                         Item::deleteForUser(['id' => $item], $uid);
75                 }
76
77                 $json = ['success' => 1];
78                 System::jsonExit($json);
79         }
80
81         Hook::callAll('post_local_start', $_REQUEST);
82
83         Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
84
85         $api_source = $_REQUEST['api_source'] ?? false;
86
87         $return_path = $_REQUEST['return'] ?? '';
88         $preview = intval($_REQUEST['preview'] ?? 0);
89
90         /*
91          * Check for doubly-submitted posts, and reject duplicates
92          * Note that we have to ignore previews, otherwise nothing will post
93          * after it's been previewed
94          */
95         if (!$preview && !empty($_REQUEST['post_id_random'])) {
96                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
97                         Logger::info('item post: duplicate post');
98                         item_post_return(DI::baseUrl(), $api_source, $return_path);
99                 } else {
100                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
101                 }
102         }
103
104         // Is this a reply to something?
105         $parent_item_id = intval($_REQUEST['parent'] ?? 0);
106         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
107
108         $parent_item = null;
109         $toplevel_item = null;
110         $toplevel_item_id = 0;
111         $toplevel_user_id = null;
112
113         $objecttype = null;
114         $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
115         $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
116
117         if ($parent_item_id || $thr_parent_uri) {
118                 if ($parent_item_id) {
119                         $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item_id]);
120                 } elseif ($thr_parent_uri) {
121                         $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
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                         $thr_parent_uri = $parent_item['uri'];
128                         $toplevel_item = $parent_item;
129
130                         if ($parent_item['gravity'] != GRAVITY_PARENT) {
131                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
132                         }
133                 }
134
135                 if (!DBA::isResult($toplevel_item)) {
136                         notice(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'], local_user());
147                         Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
148                         if ($stored) {
149                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
150                         }
151                 }
152
153                 $toplevel_item_id = $toplevel_item['id'];
154                 $toplevel_user_id = $toplevel_item['uid'];
155
156                 $objecttype = Activity\ObjectType::COMMENT;
157         }
158
159         if ($toplevel_item_id) {
160                 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
161         }
162
163         $post_id     = intval($_REQUEST['post_id'] ?? 0);
164         $app         = strip_tags($_REQUEST['source'] ?? '');
165         $extid       = strip_tags($_REQUEST['extid'] ?? '');
166         $object      = $_REQUEST['object'] ?? '';
167
168         // Don't use "defaults" here. It would turn 0 to 1
169         if (!isset($_REQUEST['wall'])) {
170                 $wall = 1;
171         } else {
172                 $wall = $_REQUEST['wall'];
173         }
174
175         // Ensure that the user id in a thread always stay the same
176         if (!is_null($toplevel_user_id) && in_array($toplevel_user_id, [local_user(), 0])) {
177                 $profile_uid = $toplevel_user_id;
178         }
179
180         // Allow commenting if it is an answer to a public post
181         $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
182
183         // Now check that valid personal details have been provided
184         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
185                 notice(DI::l10n()->t('Permission denied.'));
186                 if ($return_path) {
187                         DI::baseUrl()->redirect($return_path);
188                 }
189
190                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
191         }
192
193         // Init post instance
194         $orig_post = null;
195
196         // is this an edited post?
197         if ($post_id > 0) {
198                 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
199         }
200
201         $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
202         if (!DBA::isResult($user) && !$toplevel_item_id) {
203                 return 0;
204         }
205
206         $categories = '';
207         $postopts = '';
208         $emailcc = '';
209         $body = $_REQUEST['body'] ?? '';
210         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
211
212         // If we have a speparate attachment, we need to add it to the body.
213         if (!empty($has_attachment)) {
214                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
215                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
216                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
217
218                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
219                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
220
221                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
222                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
223
224                 // Fetch the basic attachment data
225                 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
226                 unset($attachment['keywords']);
227
228                 // Overwrite the basic data with possible changes from the frontend
229                 $attachment['type'] = $attachment_type;
230                 $attachment['title'] = $attachment_title;
231                 $attachment['text'] = $attachment_text;
232                 $attachment['url'] = $attachment_url;
233
234                 if (!empty($attachment_img_src)) {
235                         $attachment['images'] = [
236                                 0 => [
237                                         'src'    => $attachment_img_src,
238                                         'width'  => $attachment_img_width,
239                                         'height' => $attachment_img_height
240                                 ]
241                         ];
242                 } else {
243                         unset($attachment['images']);
244                 }
245
246                 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
247                 $body .= $att_bbcode;
248         }
249
250         // Convert links with empty descriptions to links without an explicit description
251         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
252
253         if (!empty($orig_post)) {
254                 $str_group_allow   = $orig_post['allow_gid'];
255                 $str_contact_allow = $orig_post['allow_cid'];
256                 $str_group_deny    = $orig_post['deny_gid'];
257                 $str_contact_deny  = $orig_post['deny_cid'];
258                 $location          = $orig_post['location'];
259                 $coord             = $orig_post['coord'];
260                 $verb              = $orig_post['verb'];
261                 $objecttype        = $orig_post['object-type'];
262                 $app               = $orig_post['app'];
263                 $categories        = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
264                 $title             = trim($_REQUEST['title'] ?? '');
265                 $body              = trim($body);
266                 $private           = $orig_post['private'];
267                 $pubmail_enabled   = $orig_post['pubmail'];
268                 $network           = $orig_post['network'];
269                 $guid              = $orig_post['guid'];
270                 $extid             = $orig_post['extid'];
271         } else {
272                 $aclFormatter = DI::aclFormatter();
273                 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
274                 $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
275                 $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
276                 $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
277
278                 $visibility = $_REQUEST['visibility'] ?? '';
279                 if ($visibility === 'public') {
280                         // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
281                         $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
282                 } else if ($visibility === 'custom') {
283                         // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
284                         // case that would make it public. So we always append the author's contact id to the allowed contacts.
285                         // See https://github.com/friendica/friendica/issues/9672
286                         $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid));
287                 }
288
289                 $title             = trim($_REQUEST['title']    ?? '');
290                 $location          = trim($_REQUEST['location'] ?? '');
291                 $coord             = trim($_REQUEST['coord']    ?? '');
292                 $verb              = trim($_REQUEST['verb']     ?? '');
293                 $emailcc           = trim($_REQUEST['emailcc']  ?? '');
294                 $body              = trim($body);
295                 $network           = trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN);
296                 $guid              = System::createUUID();
297
298                 $postopts = $_REQUEST['postopts'] ?? '';
299
300                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
301                         $private = Item::PRIVATE;
302                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
303                         $private = Item::UNLISTED;
304                 } else {
305                         $private = Item::PUBLIC;
306                 }
307
308                 // If this is a comment, set the permissions from the parent.
309
310                 if ($toplevel_item) {
311                         // for non native networks use the network of the original post as network of the item
312                         if (($toplevel_item['network'] != Protocol::DIASPORA)
313                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
314                                 && ($network == "")) {
315                                 $network = $toplevel_item['network'];
316                         }
317
318                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
319                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
320                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
321                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
322                         $private           = $toplevel_item['private'];
323
324                         $wall              = $toplevel_item['wall'];
325                 }
326
327                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
328
329                 // if using the API, we won't see pubmail_enable - figure out if it should be set
330                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
331                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
332                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
333                         }
334                 }
335
336                 if (!strlen($body)) {
337                         if ($preview) {
338                                 System::jsonExit(['preview' => '']);
339                         }
340
341                         notice(DI::l10n()->t('Empty post discarded.'));
342                         if ($return_path) {
343                                 DI::baseUrl()->redirect($return_path);
344                         }
345
346                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
347                 }
348         }
349
350         if (!empty($categories)) {
351                 // get the "fileas" tags for this post
352                 $filedas = FileTag::fileToArray($categories);
353         }
354
355         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
356
357         if (!empty($filedas) && is_array($filedas)) {
358                 // append the fileas stuff to the new categories list
359                 $categories .= FileTag::arrayToFile($filedas);
360         }
361
362         // get contact info for poster
363
364         $author = null;
365         $self   = false;
366         $contact_id = 0;
367
368         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
369                 $self = true;
370                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
371         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
372                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
373         }
374
375         if (DBA::isResult($author)) {
376                 $contact_id = $author['id'];
377         }
378
379         // get contact info for owner
380         if ($profile_uid == local_user() || $allow_comment) {
381                 $contact_record = $author ?: [];
382         } else {
383                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
384         }
385
386         // Look for any tags and linkify them
387         $inform   = '';
388         $private_forum = false;
389         $private_id = null;
390         $only_to_forum = false;
391         $forum_contact = [];
392
393         $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network, $str_contact_allow, &$inform, &$private_forum, &$private_id, &$only_to_forum, &$forum_contact) {
394                 $tags = BBCode::getTags($body);
395
396                 $tagged = [];
397
398                 foreach ($tags as $tag) {
399                         $tag_type = substr($tag, 0, 1);
400
401                         if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
402                                 continue;
403                         }
404
405                         /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
406                          * Robert Johnson should be first in the $tags array
407                          */
408                         foreach ($tagged as $nextTag) {
409                                 if (stristr($nextTag, $tag . ' ')) {
410                                         continue 2;
411                                 }
412                         }
413
414                         if ($success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network)) {
415                                 if ($success['replaced']) {
416                                         $tagged[] = $tag;
417                                 }
418                                 // When the forum is private or the forum is addressed with a "!" make the post private
419                                 if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
420                                         $private_forum = $success['contact']['prv'];
421                                         $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
422                                         $private_id = $success['contact']['id'];
423                                         $forum_contact = $success['contact'];
424                                 } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
425                                         $private_forum = false;
426                                         $only_to_forum = true;
427                                         $private_id = $success['contact']['id'];
428                                         $forum_contact = $success['contact'];
429                                 }
430                         }
431                 }
432
433                 return $body;
434         });
435
436         $original_contact_id = $contact_id;
437
438         if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
439                 // we tagged a forum in a top level post. Now we change the post                
440                 $private = $private_forum ? Item::PRIVATE : Item::UNLISTED;
441
442                 if ($only_to_forum) {
443                         $postopts = '';
444                 }
445
446                 if (!$private_forum) {
447                         $str_contact_allow = '';
448                         $str_group_allow   = '';
449                         $str_contact_deny  = '';
450                         $str_group_deny    = '';
451                 }
452
453                 if ($private_forum || !APContact::getByURL($forum_contact['url'])) {
454                         $str_group_allow = '';
455                         $str_contact_deny = '';
456                         $str_group_deny = '';
457                         if ($private_forum) {
458                                 $str_contact_allow = '<' . $private_id . '>';
459                         } else {
460                                 $str_contact_allow = '';
461                         }
462                         $contact_id = $private_id;
463                         $contact_record = $forum_contact;
464                         $_REQUEST['origin'] = false;
465                         $wall = 0;
466                 }
467         }
468
469         /*
470          * When a photo was uploaded into the message using the (profile wall) ajax
471          * uploader, The permissions are initially set to disallow anybody but the
472          * owner from seeing it. This is because the permissions may not yet have been
473          * set for the post. If it's private, the photo permissions should be set
474          * appropriately. But we didn't know the final permissions on the post until
475          * now. So now we'll look for links of uploaded messages that are in the
476          * post and set them to the same permissions as the post itself.
477          */
478
479         $match = null;
480
481         if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
482                 $objecttype = Activity\ObjectType::IMAGE;
483         }
484
485         /*
486          * Next link in any attachment references we find in the post.
487          */
488         $match = [];
489
490         /// @todo these lines should be moved to Model/Attach (Once it exists)
491         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
492                 $attaches = $match[1];
493                 if (count($attaches)) {
494                         foreach ($attaches as $attach) {
495                                 // Ensure to only modify attachments that you own
496                                 $srch = '<' . intval($original_contact_id) . '>';
497
498                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
499                                                 'id' => $attach];
500                                 if (!Attach::exists($condition)) {
501                                         continue;
502                                 }
503
504                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
505                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
506                                 $condition = ['id' => $attach];
507                                 Attach::update($fields, $condition);
508                         }
509                 }
510         }
511
512         // embedded bookmark or attachment in post? set bookmark flag
513
514         $data = BBCode::getAttachmentData($body);
515         $match = [];
516         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
517                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
518                 $posttype = Item::PT_PAGE;
519                 $objecttype =  Activity\ObjectType::BOOKMARK;
520         }
521
522         $body = DI::bbCodeVideo()->transform($body);
523
524         $body = BBCode::scaleExternalImages($body);
525
526         // Setting the object type if not defined before
527         if (!$objecttype) {
528                 $objecttype = Activity\ObjectType::NOTE; // Default value
529                 $objectdata = BBCode::getAttachedData($body);
530
531                 if ($objectdata["type"] == "link") {
532                         $objecttype = Activity\ObjectType::BOOKMARK;
533                 } elseif ($objectdata["type"] == "video") {
534                         $objecttype = Activity\ObjectType::VIDEO;
535                 } elseif ($objectdata["type"] == "photo") {
536                         $objecttype = Activity\ObjectType::IMAGE;
537                 }
538
539         }
540
541         $attachments = '';
542         $match = [];
543
544         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
545                 foreach ($match[2] as $mtch) {
546                         $fields = ['id', 'filename', 'filesize', 'filetype'];
547                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
548                         if ($attachment !== false) {
549                                 if (strlen($attachments)) {
550                                         $attachments .= ',';
551                                 }
552                                 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
553                                         $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
554                         }
555                         $body = str_replace($match[1],'',$body);
556                 }
557         }
558
559         if (!strlen($verb)) {
560                 $verb = Activity::POST;
561         }
562
563         if ($network == "") {
564                 $network = Protocol::DFRN;
565         }
566
567         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
568
569         // even if the post arrived via API we are considering that it
570         // originated on this site by default for determining relayability.
571
572         // Don't use "defaults" here. It would turn 0 to 1
573         if (!isset($_REQUEST['origin'])) {
574                 $origin = 1;
575         } else {
576                 $origin = $_REQUEST['origin'];
577         }
578
579         $uri = Item::newURI($api_source ? $profile_uid : $uid, $guid);
580
581         // Fallback so that we alway have a parent uri
582         if (!$thr_parent_uri || !$toplevel_item_id) {
583                 $thr_parent_uri = $uri;
584         }
585
586         $datarray = [];
587         $datarray['uid']           = $profile_uid;
588         $datarray['wall']          = $wall;
589         $datarray['gravity']       = $gravity;
590         $datarray['network']       = $network;
591         $datarray['contact-id']    = $contact_id;
592         $datarray['owner-name']    = $contact_record['name'] ?? '';
593         $datarray['owner-link']    = $contact_record['url'] ?? '';
594         $datarray['owner-avatar']  = $contact_record['thumb'] ?? '';
595         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
596         $datarray['author-name']   = $author['name'];
597         $datarray['author-link']   = $author['url'];
598         $datarray['author-avatar'] = $author['thumb'];
599         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
600         $datarray['created']       = DateTimeFormat::utcNow();
601         $datarray['edited']        = DateTimeFormat::utcNow();
602         $datarray['commented']     = DateTimeFormat::utcNow();
603         $datarray['received']      = DateTimeFormat::utcNow();
604         $datarray['changed']       = DateTimeFormat::utcNow();
605         $datarray['extid']         = $extid;
606         $datarray['guid']          = $guid;
607         $datarray['uri']           = $uri;
608         $datarray['title']         = $title;
609         $datarray['body']          = $body;
610         $datarray['app']           = $app;
611         $datarray['location']      = $location;
612         $datarray['coord']         = $coord;
613         $datarray['file']          = $categories;
614         $datarray['inform']        = $inform;
615         $datarray['verb']          = $verb;
616         $datarray['post-type']     = $posttype;
617         $datarray['object-type']   = $objecttype;
618         $datarray['allow_cid']     = $str_contact_allow;
619         $datarray['allow_gid']     = $str_group_allow;
620         $datarray['deny_cid']      = $str_contact_deny;
621         $datarray['deny_gid']      = $str_group_deny;
622         $datarray['private']       = $private;
623         $datarray['pubmail']       = $pubmail_enabled;
624         $datarray['attach']        = $attachments;
625
626         $datarray['thr-parent']    = $thr_parent_uri;
627
628         $datarray['postopts']      = $postopts;
629         $datarray['origin']        = $origin;
630         $datarray['object']        = $object;
631
632         $datarray['uri-id']        = ItemURI::getIdByURI($datarray['uri']);
633         $datarray['attachments']   = $_REQUEST['attachments'] ?? [];
634
635         /*
636          * These fields are for the convenience of addons...
637          * 'self' if true indicates the owner is posting on their own wall
638          * If parent is 0 it is a top-level post.
639          */
640         $datarray['parent']        = $toplevel_item_id;
641         $datarray['self']          = $self;
642
643         // This triggers posts via API and the mirror functions
644         $datarray['api_source'] = $api_source;
645
646         // This field is for storing the raw conversation data
647         $datarray['protocol'] = Conversation::PARCEL_DIRECT;
648         $datarray['direction'] = Conversation::PUSH;
649
650         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['thr-parent']]);
651         if (DBA::isResult($conversation)) {
652                 if ($conversation['conversation-uri'] != '') {
653                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
654                 }
655                 if ($conversation['conversation-href'] != '') {
656                         $datarray['conversation-href'] = $conversation['conversation-href'];
657                 }
658         }
659
660         if ($orig_post) {
661                 $datarray['edit'] = true;
662         } else {
663                 // If this was a share, add missing data here
664                 $datarray = Item::addShareDataFromOriginal($datarray);
665
666                 $datarray['edit'] = false;
667         }
668
669         // Check for hashtags in the body and repair or add hashtag links
670         if ($preview || $orig_post) {
671                 $datarray['body'] = Item::setHashtags($datarray['body']);
672         }
673
674         // preview mode - prepare the body for display and send it via json
675         if ($preview) {
676                 // We set the datarray ID to -1 because in preview mode the dataray
677                 // doesn't have an ID.
678                 $datarray["id"] = -1;
679                 $datarray["uri-id"] = -1;
680                 $datarray["author-network"] = Protocol::DFRN;
681
682                 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
683
684                 System::jsonExit(['preview' => $o]);
685         }
686
687         Hook::callAll('post_local',$datarray);
688
689         if (!empty($datarray['cancel'])) {
690                 Logger::info('mod_item: post cancelled by addon.');
691                 if ($return_path) {
692                         DI::baseUrl()->redirect($return_path);
693                 }
694
695                 $json = ['cancel' => 1];
696                 if (!empty($_REQUEST['jsreload'])) {
697                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
698                 }
699
700                 System::jsonExit($json);
701         }
702
703         if ($orig_post) {
704                 // Fill the cache field
705                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
706                 Item::putInCache($datarray);
707
708                 $fields = [
709                         'title' => $datarray['title'],
710                         'body' => $datarray['body'],
711                         'attach' => $datarray['attach'],
712                         'file' => $datarray['file'],
713                         'rendered-html' => $datarray['rendered-html'],
714                         'rendered-hash' => $datarray['rendered-hash'],
715                         'edited' => DateTimeFormat::utcNow(),
716                         'changed' => DateTimeFormat::utcNow()];
717
718                 Item::update($fields, ['id' => $post_id]);
719
720                 if ($return_path) {
721                         DI::baseUrl()->redirect($return_path);
722                 }
723
724                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
725         }
726
727         unset($datarray['edit']);
728         unset($datarray['self']);
729         unset($datarray['api_source']);
730
731         $post_id = Item::insert($datarray);
732
733         if (!$post_id) {
734                 notice(DI::l10n()->t('Item wasn\'t stored.'));
735                 if ($return_path) {
736                         DI::baseUrl()->redirect($return_path);
737                 }
738
739                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
740         }
741
742         $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
743
744         if (!DBA::isResult($datarray)) {
745                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
746                 if ($return_path) {
747                         DI::baseUrl()->redirect($return_path);
748                 }
749
750                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
751         }
752
753         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
754
755         if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
756                 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
757         }
758
759         // These notifications are sent if someone else is commenting other your wall
760         if ($contact_record != $author) {
761                 if ($toplevel_item_id) {
762                         notification([
763                                 'type'  => Notification\Type::COMMENT,
764                                 'otype' => Notification\ObjectType::ITEM,
765                                 'verb'  => Activity::POST,
766                                 'uid'   => $profile_uid,
767                                 'cid'   => $datarray['author-id'],
768                                 'item'  => $datarray,
769                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
770                         ]);
771                 } elseif (empty($forum_contact)) {
772                         notification([
773                                 'type'  => Notification\Type::WALL,
774                                 'otype' => Notification\ObjectType::ITEM,
775                                 'verb'  => Activity::POST,
776                                 'uid'   => $profile_uid,
777                                 'cid'   => $datarray['author-id'],
778                                 'item'  => $datarray,
779                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
780                         ]);
781                 }
782         }
783
784         Hook::callAll('post_local_end', $datarray);
785
786         if (strlen($emailcc) && $profile_uid == local_user()) {
787                 $recipients = explode(',', $emailcc);
788                 if (count($recipients)) {
789                         foreach ($recipients as $recipient) {
790                                 $address = trim($recipient);
791                                 if (!strlen($address)) {
792                                         continue;
793                                 }
794                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
795                                         $datarray, $address, $author['thumb'] ?? ''));
796                         }
797                 }
798         }
799
800         // When we are doing some forum posting via ! we have to start the notifier manually.
801         // These kind of posts don't initiate the notifier call in the item class.
802         if ($only_to_forum) {
803                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, (int)$datarray['uri-id'], (int)$datarray['uid']);
804         }
805
806         Logger::info('post_complete');
807
808         if ($api_source) {
809                 return $post_id;
810         }
811
812         item_post_return(DI::baseUrl(), $api_source, $return_path);
813         // NOTREACHED
814 }
815
816 function item_post_return($baseurl, $api_source, $return_path)
817 {
818         if ($api_source) {
819                 return;
820         }
821
822         if ($return_path) {
823                 DI::baseUrl()->redirect($return_path);
824         }
825
826         $json = ['success' => 1];
827         if (!empty($_REQUEST['jsreload'])) {
828                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
829         }
830
831         Logger::info('post_json', ['json' => $json]);
832
833         System::jsonExit($json);
834 }
835
836 function item_content(App $a)
837 {
838         if (!Session::isAuthenticated()) {
839                 throw new HTTPException\UnauthorizedException();
840         }
841
842         $args = DI::args();
843
844         if (!$args->has(3)) {
845                 throw new HTTPException\BadRequestException();
846         }
847
848         $o = '';
849         switch ($args->get(1)) {
850                 case 'drop':
851                         if (DI::mode()->isAjax()) {
852                                 Item::deleteForUser(['id' => $args->get(2)], local_user());
853                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
854                                 System::jsonExit([intval($args->get(2)), local_user()]);
855                         } else {
856                                 if (!empty($args->get(3))) {
857                                         $o = drop_item($args->get(2), $args->get(3));
858                                 } else {
859                                         $o = drop_item($args->get(2));
860                                 }
861                         }
862                         break;
863                 case 'block':
864                         $item = Post::selectFirstForUser(local_user(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
865                         if (empty($item['author-id'])) {
866                                 throw new HTTPException\NotFoundException('Item not found');
867                         }
868
869                         Contact\User::setBlocked($item['author-id'], local_user(), true);
870
871                         if (DI::mode()->isAjax()) {
872                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
873                                 System::jsonExit([intval($args->get(2)), local_user()]);
874                         } else {
875                                 item_redirect_after_action($item, $args->get(3));
876                         }
877                         break;
878         }
879
880         return $o;
881 }
882
883 /**
884  * @param int    $id
885  * @param string $return
886  * @return string
887  * @throws HTTPException\InternalServerErrorException
888  */
889 function drop_item(int $id, string $return = '')
890 {
891         // locate item to be deleted
892         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
893         $item = Post::selectFirstForUser(local_user(), $fields, ['id' => $id]);
894
895         if (!DBA::isResult($item)) {
896                 notice(DI::l10n()->t('Item not found.'));
897                 DI::baseUrl()->redirect('network');
898         }
899
900         if ($item['deleted']) {
901                 return '';
902         }
903
904         $contact_id = 0;
905
906         // check if logged in user is either the author or owner of this item
907         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
908                 $contact_id = $item['contact-id'];
909         }
910
911         if ((local_user() == $item['uid']) || $contact_id) {
912                 // delete the item
913                 Item::deleteForUser(['id' => $item['id']], local_user());
914
915                 item_redirect_after_action($item, $return);
916         } else {
917                 notice(DI::l10n()->t('Permission denied.'));
918                 DI::baseUrl()->redirect('display/' . $item['guid']);
919                 //NOTREACHED
920         }
921
922         return '';
923 }
924
925 function item_redirect_after_action($item, $returnUrlHex)
926 {
927         $return_url = hex2bin($returnUrlHex);
928
929         // removes update_* from return_url to ignore Ajax refresh
930         $return_url = str_replace("update_", "", $return_url);
931
932         // Check if delete a comment
933         if ($item['gravity'] == GRAVITY_COMMENT) {
934                 if (!empty($item['parent'])) {
935                         $parentitem = Post::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
936                 }
937
938                 // Return to parent guid
939                 if (!empty($parentitem)) {
940                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
941                         //NOTREACHED
942                 } // In case something goes wrong
943                 else {
944                         DI::baseUrl()->redirect('network');
945                         //NOTREACHED
946                 }
947         } else {
948                 // if unknown location or deleting top level post called from display
949                 if (empty($return_url) || strpos($return_url, 'display') !== false) {
950                         DI::baseUrl()->redirect('network');
951                         //NOTREACHED
952                 } else {
953                         DI::baseUrl()->redirect($return_url);
954                         //NOTREACHED
955                 }
956         }
957 }