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