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