c30bbcc08809456818e443bf756c25009c3cd10a
[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\Renderer;
39 use Friendica\Core\Session;
40 use Friendica\Core\System;
41 use Friendica\Core\Worker;
42 use Friendica\Database\DBA;
43 use Friendica\DI;
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\Notify\Type;
50 use Friendica\Model\Photo;
51 use Friendica\Model\Tag;
52 use Friendica\Network\HTTPException;
53 use Friendica\Object\EMail\ItemCCEMail;
54 use Friendica\Protocol\Activity;
55 use Friendica\Protocol\Diaspora;
56 use Friendica\Util\DateTimeFormat;
57 use Friendica\Util\Security;
58 use Friendica\Util\Strings;
59 use Friendica\Worker\Delivery;
60
61 require_once __DIR__ . '/../include/items.php';
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         $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
87
88         $return_path = $_REQUEST['return'] ?? '';
89         $preview = intval($_REQUEST['preview'] ?? 0);
90
91         /*
92          * Check for doubly-submitted posts, and reject duplicates
93          * Note that we have to ignore previews, otherwise nothing will post
94          * after it's been previewed
95          */
96         if (!$preview && !empty($_REQUEST['post_id_random'])) {
97                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
98                         Logger::info('item post: duplicate post');
99                         item_post_return(DI::baseUrl(), $api_source, $return_path);
100                 } else {
101                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
102                 }
103         }
104
105         // Is this a reply to something?
106         $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
107         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
108
109         $toplevel_item = null;
110         $parent_user = 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 ($toplevel_item_id || $thr_parent_uri) {
117                 if ($toplevel_item_id) {
118                         $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
119                 } elseif ($thr_parent_uri) {
120                         $toplevel_item = Item::selectFirst([], ['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($toplevel_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 = $toplevel_item['uri'];
127
128                         if ($toplevel_item['gravity'] != GRAVITY_PARENT) {
129                                 $toplevel_item = Item::selectFirst([], ['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                 $toplevel_item_id = $toplevel_item['id'];
142                 $parent_user = $toplevel_item['uid'];
143
144                 $objecttype = Activity\ObjectType::COMMENT;
145         }
146
147         if ($toplevel_item_id) {
148                 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
149         }
150
151         $post_id     = intval($_REQUEST['post_id'] ?? 0);
152         $app         = strip_tags($_REQUEST['source'] ?? '');
153         $extid       = strip_tags($_REQUEST['extid'] ?? '');
154         $object      = $_REQUEST['object'] ?? '';
155
156         // Don't use "defaults" here. It would turn 0 to 1
157         if (!isset($_REQUEST['wall'])) {
158                 $wall = 1;
159         } else {
160                 $wall = $_REQUEST['wall'];
161         }
162
163         // Ensure that the user id in a thread always stay the same
164         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
165                 $profile_uid = $parent_user;
166         }
167
168         // Check for multiple posts with the same message id (when the post was created via API)
169         if (($message_id != '') && ($profile_uid != 0)) {
170                 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
171                         Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
172                         return 0;
173                 }
174         }
175
176         // Allow commenting if it is an answer to a public post
177         $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
178
179         // Now check that valid personal details have been provided
180         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
181                 notice(DI::l10n()->t('Permission denied.'));
182                 if ($return_path) {
183                         DI::baseUrl()->redirect($return_path);
184                 }
185
186                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
187         }
188
189         // Init post instance
190         $orig_post = null;
191
192         // is this an edited post?
193         if ($post_id > 0) {
194                 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
195         }
196
197         $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
198
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        = $orig_post['file'] ?? '';
255                 $title             = Strings::escapeTags(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                 $str_contact_allow = '';
264                 $str_group_allow   = '';
265                 $str_contact_deny  = '';
266                 $str_group_deny    = '';
267
268                 if (($_REQUEST['visibility'] ?? '') !== 'public') {
269                         $aclFormatter = DI::aclFormatter();
270                         $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
271                         $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
272                         $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
273                         $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
274                 }
275
276                 $title             = Strings::escapeTags(trim($_REQUEST['title']    ?? ''));
277                 $location          = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
278                 $coord             = Strings::escapeTags(trim($_REQUEST['coord']    ?? ''));
279                 $verb              = Strings::escapeTags(trim($_REQUEST['verb']     ?? ''));
280                 $emailcc           = Strings::escapeTags(trim($_REQUEST['emailcc']  ?? ''));
281                 $body              = trim($body);
282                 $network           = Strings::escapeTags(trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN));
283                 $guid              = System::createUUID();
284
285                 $postopts = $_REQUEST['postopts'] ?? '';
286
287                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
288                         $private = Item::PRIVATE;
289                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
290                         $private = Item::UNLISTED;
291                 } else {
292                         $private = Item::PUBLIC;
293                 }
294
295                 // If this is a comment, set the permissions from the parent.
296
297                 if ($toplevel_item) {
298                         // for non native networks use the network of the original post as network of the item
299                         if (($toplevel_item['network'] != Protocol::DIASPORA)
300                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
301                                 && ($network == "")) {
302                                 $network = $toplevel_item['network'];
303                         }
304
305                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
306                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
307                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
308                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
309                         $private           = $toplevel_item['private'];
310
311                         $wall              = $toplevel_item['wall'];
312                 }
313
314                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
315
316                 // if using the API, we won't see pubmail_enable - figure out if it should be set
317                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
318                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
319                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
320                         }
321                 }
322
323                 if (!strlen($body)) {
324                         if ($preview) {
325                                 System::jsonExit(['preview' => '']);
326                         }
327
328                         info(DI::l10n()->t('Empty post discarded.'));
329                         if ($return_path) {
330                                 DI::baseUrl()->redirect($return_path);
331                         }
332
333                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
334                 }
335         }
336
337         if (!empty($categories)) {
338                 // get the "fileas" tags for this post
339                 $filedas = FileTag::fileToArray($categories);
340         }
341
342         // save old and new categories, so we can determine what needs to be deleted from pconfig
343         $categories_old = $categories;
344         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
345         $categories_new = $categories;
346
347         if (!empty($filedas) && is_array($filedas)) {
348                 // append the fileas stuff to the new categories list
349                 $categories .= FileTag::arrayToFile($filedas);
350         }
351
352         // get contact info for poster
353
354         $author = null;
355         $self   = false;
356         $contact_id = 0;
357
358         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
359                 $self = true;
360                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
361         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
362                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
363         }
364
365         if (DBA::isResult($author)) {
366                 $contact_id = $author['id'];
367         }
368
369         // get contact info for owner
370         if ($profile_uid == local_user() || $allow_comment) {
371                 $contact_record = $author ?: [];
372         } else {
373                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
374         }
375
376         // Look for any tags and linkify them
377         $inform   = '';
378         $private_forum = false;
379         $private_id = null;
380         $only_to_forum = false;
381         $forum_contact = [];
382
383         $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) {
384                 $tags = BBCode::getTags($body);
385
386                 $tagged = [];
387
388                 foreach ($tags as $tag) {
389                         $tag_type = substr($tag, 0, 1);
390
391                         if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
392                                 continue;
393                         }
394
395                         /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
396                          * Robert Johnson should be first in the $tags array
397                          */
398                         foreach ($tagged as $nextTag) {
399                                 if (stristr($nextTag, $tag . ' ')) {
400                                         continue 2;
401                                 }
402                         }
403
404                         $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
405                         if ($success['replaced']) {
406                                 $tagged[] = $tag;
407                         }
408                         // When the forum is private or the forum is addressed with a "!" make the post private
409                         if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
410                                 $private_forum = $success['contact']['prv'];
411                                 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
412                                 $private_id = $success['contact']['id'];
413                                 $forum_contact = $success['contact'];
414                         } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
415                                 $private_forum = false;
416                                 $only_to_forum = true;
417                                 $private_id = $success['contact']['id'];
418                                 $forum_contact = $success['contact'];
419                         }
420                 }
421
422                 return $body;
423         });
424
425         $original_contact_id = $contact_id;
426
427         if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
428                 // we tagged a forum in a top level post. Now we change the post
429                 $private = $private_forum;
430
431                 $str_group_allow = '';
432                 $str_contact_deny = '';
433                 $str_group_deny = '';
434                 if ($private_forum) {
435                         $str_contact_allow = '<' . $private_id . '>';
436                 } else {
437                         $str_contact_allow = '';
438                 }
439                 $contact_id = $private_id;
440                 $contact_record = $forum_contact;
441                 $_REQUEST['origin'] = false;
442                 $wall = 0;
443         }
444
445         /*
446          * When a photo was uploaded into the message using the (profile wall) ajax
447          * uploader, The permissions are initially set to disallow anybody but the
448          * owner from seeing it. This is because the permissions may not yet have been
449          * set for the post. If it's private, the photo permissions should be set
450          * appropriately. But we didn't know the final permissions on the post until
451          * now. So now we'll look for links of uploaded messages that are in the
452          * post and set them to the same permissions as the post itself.
453          */
454
455         $match = null;
456
457         if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
458                 $objecttype = Activity\ObjectType::IMAGE;
459         }
460
461         /*
462          * Next link in any attachment references we find in the post.
463          */
464         $match = false;
465
466         /// @todo these lines should be moved to Model/Attach (Once it exists)
467         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
468                 $attaches = $match[1];
469                 if (count($attaches)) {
470                         foreach ($attaches as $attach) {
471                                 // Ensure to only modify attachments that you own
472                                 $srch = '<' . intval($original_contact_id) . '>';
473
474                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
475                                                 'id' => $attach];
476                                 if (!Attach::exists($condition)) {
477                                         continue;
478                                 }
479
480                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
481                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
482                                 $condition = ['id' => $attach];
483                                 Attach::update($fields, $condition);
484                         }
485                 }
486         }
487
488         // embedded bookmark or attachment in post? set bookmark flag
489
490         $data = BBCode::getAttachmentData($body);
491         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
492                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
493                 $posttype = Item::PT_PAGE;
494                 $objecttype =  Activity\ObjectType::BOOKMARK;
495         }
496
497         $body = DI::bbCodeVideo()->transform($body);
498
499         $body = BBCode::scaleExternalImages($body);
500
501         // Setting the object type if not defined before
502         if (!$objecttype) {
503                 $objecttype = Activity\ObjectType::NOTE; // Default value
504                 $objectdata = BBCode::getAttachedData($body);
505
506                 if ($objectdata["type"] == "link") {
507                         $objecttype = Activity\ObjectType::BOOKMARK;
508                 } elseif ($objectdata["type"] == "video") {
509                         $objecttype = Activity\ObjectType::VIDEO;
510                 } elseif ($objectdata["type"] == "photo") {
511                         $objecttype = Activity\ObjectType::IMAGE;
512                 }
513
514         }
515
516         $attachments = '';
517         $match = false;
518
519         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
520                 foreach ($match[2] as $mtch) {
521                         $fields = ['id', 'filename', 'filesize', 'filetype'];
522                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
523                         if ($attachment !== false) {
524                                 if (strlen($attachments)) {
525                                         $attachments .= ',';
526                                 }
527                                 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
528                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
529                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
530                         }
531                         $body = str_replace($match[1],'',$body);
532                 }
533         }
534
535         if (!strlen($verb)) {
536                 $verb = Activity::POST;
537         }
538
539         if ($network == "") {
540                 $network = Protocol::DFRN;
541         }
542
543         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
544
545         // even if the post arrived via API we are considering that it
546         // originated on this site by default for determining relayability.
547
548         // Don't use "defaults" here. It would turn 0 to 1
549         if (!isset($_REQUEST['origin'])) {
550                 $origin = 1;
551         } else {
552                 $origin = $_REQUEST['origin'];
553         }
554
555         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
556
557         // Fallback so that we alway have a parent uri
558         if (!$thr_parent_uri || !$toplevel_item_id) {
559                 $thr_parent_uri = $uri;
560         }
561
562         $datarray = [];
563         $datarray['uid']           = $profile_uid;
564         $datarray['wall']          = $wall;
565         $datarray['gravity']       = $gravity;
566         $datarray['network']       = $network;
567         $datarray['contact-id']    = $contact_id;
568         $datarray['owner-name']    = $contact_record['name'] ?? '';
569         $datarray['owner-link']    = $contact_record['url'] ?? '';
570         $datarray['owner-avatar']  = $contact_record['thumb'] ?? '';
571         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
572         $datarray['author-name']   = $author['name'];
573         $datarray['author-link']   = $author['url'];
574         $datarray['author-avatar'] = $author['thumb'];
575         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
576         $datarray['created']       = DateTimeFormat::utcNow();
577         $datarray['edited']        = DateTimeFormat::utcNow();
578         $datarray['commented']     = DateTimeFormat::utcNow();
579         $datarray['received']      = DateTimeFormat::utcNow();
580         $datarray['changed']       = DateTimeFormat::utcNow();
581         $datarray['extid']         = $extid;
582         $datarray['guid']          = $guid;
583         $datarray['uri']           = $uri;
584         $datarray['title']         = $title;
585         $datarray['body']          = $body;
586         $datarray['app']           = $app;
587         $datarray['location']      = $location;
588         $datarray['coord']         = $coord;
589         $datarray['file']          = $categories;
590         $datarray['inform']        = $inform;
591         $datarray['verb']          = $verb;
592         $datarray['post-type']     = $posttype;
593         $datarray['object-type']   = $objecttype;
594         $datarray['allow_cid']     = $str_contact_allow;
595         $datarray['allow_gid']     = $str_group_allow;
596         $datarray['deny_cid']      = $str_contact_deny;
597         $datarray['deny_gid']      = $str_group_deny;
598         $datarray['private']       = $private;
599         $datarray['pubmail']       = $pubmail_enabled;
600         $datarray['attach']        = $attachments;
601
602         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
603         $datarray['parent-uri']    = $thr_parent_uri;
604
605         $datarray['postopts']      = $postopts;
606         $datarray['origin']        = $origin;
607         $datarray['moderated']     = false;
608         $datarray['object']        = $object;
609
610         /*
611          * These fields are for the convenience of addons...
612          * 'self' if true indicates the owner is posting on their own wall
613          * If parent is 0 it is a top-level post.
614          */
615         $datarray['parent']        = $toplevel_item_id;
616         $datarray['self']          = $self;
617
618         // This triggers posts via API and the mirror functions
619         $datarray['api_source'] = $api_source;
620
621         // This field is for storing the raw conversation data
622         $datarray['protocol'] = Conversation::PARCEL_DFRN;
623
624         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
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["item_id"] = -1;
655                 $datarray["author-network"] = Protocol::DFRN;
656
657                 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
658
659                 System::jsonExit(['preview' => $o]);
660         }
661
662         Hook::callAll('post_local',$datarray);
663
664         if (!empty($datarray['cancel'])) {
665                 Logger::info('mod_item: post cancelled by addon.');
666                 if ($return_path) {
667                         DI::baseUrl()->redirect($return_path);
668                 }
669
670                 $json = ['cancel' => 1];
671                 if (!empty($_REQUEST['jsreload'])) {
672                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
673                 }
674
675                 System::jsonExit($json);
676         }
677
678         if ($orig_post) {
679                 // Fill the cache field
680                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
681                 Item::putInCache($datarray);
682
683                 $fields = [
684                         'title' => $datarray['title'],
685                         'body' => $datarray['body'],
686                         'attach' => $datarray['attach'],
687                         'file' => $datarray['file'],
688                         'rendered-html' => $datarray['rendered-html'],
689                         'rendered-hash' => $datarray['rendered-hash'],
690                         'edited' => DateTimeFormat::utcNow(),
691                         'changed' => DateTimeFormat::utcNow()];
692
693                 Item::update($fields, ['id' => $post_id]);
694
695                 // update filetags in pconfig
696                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
697
698                 info(DI::l10n()->t('Post updated.'));
699                 if ($return_path) {
700                         DI::baseUrl()->redirect($return_path);
701                 }
702
703                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
704         }
705
706         unset($datarray['edit']);
707         unset($datarray['self']);
708         unset($datarray['api_source']);
709
710         if ($origin) {
711                 $signed = Diaspora::createCommentSignature($uid, $datarray);
712                 if (!empty($signed)) {
713                         $datarray['diaspora_signed_text'] = json_encode($signed);
714                 }
715         }
716
717         $post_id = Item::insert($datarray);
718
719         if (!$post_id) {
720                 info(DI::l10n()->t('Item wasn\'t stored.'));
721                 if ($return_path) {
722                         DI::baseUrl()->redirect($return_path);
723                 }
724
725                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
726         }
727
728         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
729
730         if (!DBA::isResult($datarray)) {
731                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
732                 if ($return_path) {
733                         DI::baseUrl()->redirect($return_path);
734                 }
735
736                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
737         }
738
739         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
740
741         if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
742                 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
743         }
744
745         // update filetags in pconfig
746         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
747
748         // These notifications are sent if someone else is commenting other your wall
749         if ($contact_record != $author) {
750                 if ($toplevel_item_id) {
751                         notification([
752                                 'type'         => Type::COMMENT,
753                                 'notify_flags' => $user['notify-flags'],
754                                 'language'     => $user['language'],
755                                 'to_name'      => $user['username'],
756                                 'to_email'     => $user['email'],
757                                 'uid'          => $user['uid'],
758                                 'item'         => $datarray,
759                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
760                                 'source_name'  => $datarray['author-name'],
761                                 'source_link'  => $datarray['author-link'],
762                                 'source_photo' => $datarray['author-avatar'],
763                                 'verb'         => Activity::POST,
764                                 'otype'        => 'item',
765                                 'parent'       => $toplevel_item_id,
766                                 'parent_uri'   => $toplevel_item['uri']
767                         ]);
768                 } elseif (empty($forum_contact)) {
769                         notification([
770                                 'type'         => Type::WALL,
771                                 'notify_flags' => $user['notify-flags'],
772                                 'language'     => $user['language'],
773                                 'to_name'      => $user['username'],
774                                 'to_email'     => $user['email'],
775                                 'uid'          => $user['uid'],
776                                 'item'         => $datarray,
777                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
778                                 'source_name'  => $datarray['author-name'],
779                                 'source_link'  => $datarray['author-link'],
780                                 'source_photo' => $datarray['author-avatar'],
781                                 'verb'         => Activity::POST,
782                                 'otype'        => 'item'
783                         ]);
784                 }
785         }
786
787         Hook::callAll('post_local_end', $datarray);
788
789         if (strlen($emailcc) && $profile_uid == local_user()) {
790                 $recipients = explode(',', $emailcc);
791                 if (count($recipients)) {
792                         foreach ($recipients as $recipient) {
793                                 $address = trim($recipient);
794                                 if (!strlen($address)) {
795                                         continue;
796                                 }
797                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
798                                         $datarray, $address, $author['thumb'] ?? ''));
799                         }
800                 }
801         }
802
803         // Insert an item entry for UID=0 for global entries.
804         // We now do it in the background to save some time.
805         // This is important in interactive environments like the frontend or the API.
806         // We don't fork a new process since this is done anyway with the following command
807         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
808
809         // When we are doing some forum posting via ! we have to start the notifier manually.
810         // These kind of posts don't initiate the notifier call in the item class.
811         if ($only_to_forum) {
812                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
813         }
814
815         Logger::info('post_complete');
816
817         if ($api_source) {
818                 return $post_id;
819         }
820
821         info(DI::l10n()->t('Post published.'));
822         item_post_return(DI::baseUrl(), $api_source, $return_path);
823         // NOTREACHED
824 }
825
826 function item_post_return($baseurl, $api_source, $return_path)
827 {
828         if ($api_source) {
829                 return;
830         }
831
832         if ($return_path) {
833                 DI::baseUrl()->redirect($return_path);
834         }
835
836         $json = ['success' => 1];
837         if (!empty($_REQUEST['jsreload'])) {
838                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
839         }
840
841         Logger::info('post_json', ['json' => $json]);
842
843         System::jsonExit($json);
844 }
845
846 function item_content(App $a)
847 {
848         if (!Session::isAuthenticated()) {
849                 return;
850         }
851
852         $o = '';
853
854         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
855                 if (DI::mode()->isAjax()) {
856                         Item::deleteForUser(['id' => $a->argv[2]], local_user());
857                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
858                         System::jsonExit([intval($a->argv[2]), local_user()]);
859                 } else {
860                         if (!empty($a->argv[3])) {
861                                 $o = drop_item($a->argv[2], $a->argv[3]);
862                         }
863                         else {
864                                 $o = drop_item($a->argv[2]);
865                         }
866                 }
867         }
868
869         return $o;
870 }
871
872 /**
873  * @param int    $id
874  * @param string $return
875  * @return string
876  * @throws HTTPException\InternalServerErrorException
877  */
878 function drop_item(int $id, string $return = '')
879 {
880         // locate item to be deleted
881         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
882         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
883
884         if (!DBA::isResult($item)) {
885                 notice(DI::l10n()->t('Item not found.') . EOL);
886                 DI::baseUrl()->redirect('network');
887         }
888
889         if ($item['deleted']) {
890                 return '';
891         }
892
893         $contact_id = 0;
894
895         // check if logged in user is either the author or owner of this item
896         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
897                 $contact_id = $item['contact-id'];
898         }
899
900         if ((local_user() == $item['uid']) || $contact_id) {
901                 // Check if we should do HTML-based delete confirmation
902                 if (!empty($_REQUEST['confirm'])) {
903                         // <form> can't take arguments in its "action" parameter
904                         // so add any arguments as hidden inputs
905                         $query = explode_querystring(DI::args()->getQueryString());
906                         $inputs = [];
907
908                         foreach ($query['args'] as $arg) {
909                                 if (strpos($arg, 'confirm=') === false) {
910                                         $arg_parts = explode('=', $arg);
911                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
912                                 }
913                         }
914
915                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
916                                 '$method' => 'get',
917                                 '$message' => DI::l10n()->t('Do you really want to delete this item?'),
918                                 '$extra_inputs' => $inputs,
919                                 '$confirm' => DI::l10n()->t('Yes'),
920                                 '$confirm_url' => $query['base'],
921                                 '$confirm_name' => 'confirmed',
922                                 '$cancel' => DI::l10n()->t('Cancel'),
923                         ]);
924                 }
925                 // Now check how the user responded to the confirmation query
926                 if (!empty($_REQUEST['canceled'])) {
927                         DI::baseUrl()->redirect('display/' . $item['guid']);
928                 }
929
930                 $is_comment = $item['gravity'] == GRAVITY_COMMENT;
931                 $parentitem = null;
932                 if (!empty($item['parent'])) {
933                         $fields = ['guid'];
934                         $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
935                 }
936
937                 // delete the item
938                 Item::deleteForUser(['id' => $item['id']], local_user());
939
940                 $return_url = hex2bin($return);
941
942                 // removes update_* from return_url to ignore Ajax refresh
943                 $return_url = str_replace("update_", "", $return_url);
944
945                 // Check if delete a comment
946                 if ($is_comment) {
947                         // Return to parent guid
948                         if (!empty($parentitem)) {
949                                 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
950                                 //NOTREACHED
951                         } // In case something goes wrong
952                         else {
953                                 DI::baseUrl()->redirect('network');
954                                 //NOTREACHED
955                         }
956                 } else {
957                         // if unknown location or deleting top level post called from display
958                         if (empty($return_url) || strpos($return_url, 'display') !== false) {
959                                 DI::baseUrl()->redirect('network');
960                                 //NOTREACHED
961                         } else {
962                                 DI::baseUrl()->redirect($return_url);
963                                 //NOTREACHED
964                         }
965                 }
966         } else {
967                 notice(DI::l10n()->t('Permission denied.'));
968                 DI::baseUrl()->redirect('display/' . $item['guid']);
969                 //NOTREACHED
970         }
971
972         return '';
973 }