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