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