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