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