3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
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.
27 * All of these become an "item" which is our basic unit of
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;
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;
59 function item_post(App $a) {
60 if (!DI::userSession()->isAuthenticated()) {
61 throw new HTTPException\ForbiddenException();
64 $uid = DI::userSession()->getLocalUserId();
66 if (!empty($_REQUEST['dropitems'])) {
67 $arr_drop = explode(',', $_REQUEST['dropitems']);
68 foreach ($arr_drop as $item) {
69 Item::deleteForUser(['id' => $item], $uid);
72 $json = ['success' => 1];
73 System::jsonExit($json);
76 Hook::callAll('post_local_start', $_REQUEST);
78 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
80 $return_path = $_REQUEST['return'] ?? '';
81 $preview = intval($_REQUEST['preview'] ?? 0);
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
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);
93 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
97 // Is this a reply to something?
98 $parent_item_id = intval($_REQUEST['parent'] ?? 0);
99 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
102 $toplevel_item = null;
103 $toplevel_item_id = 0;
104 $toplevel_user_id = null;
107 $profile_uid = DI::userSession()->getLocalUserId();
108 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
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]);
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;
123 if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
124 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
128 if (!DBA::isResult($toplevel_item)) {
129 DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
131 DI::baseUrl()->redirect($return_path);
133 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
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]);
142 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
146 $toplevel_item_id = $toplevel_item['id'];
147 $toplevel_user_id = $toplevel_item['uid'];
149 $objecttype = Activity\ObjectType::COMMENT;
152 if ($toplevel_item_id) {
153 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
156 $post_id = intval($_REQUEST['post_id'] ?? 0);
157 $app = strip_tags($_REQUEST['source'] ?? '');
158 $extid = strip_tags($_REQUEST['extid'] ?? '');
159 $object = $_REQUEST['object'] ?? '';
161 // Don't use "defaults" here. It would turn 0 to 1
162 if (!isset($_REQUEST['wall'])) {
165 $wall = $_REQUEST['wall'];
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;
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);
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.'));
181 DI::baseUrl()->redirect($return_path);
184 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
187 // Init post instance
190 // is this an edited post?
192 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
195 $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
196 if (!DBA::isResult($user) && !$toplevel_item_id) {
203 $body = $_REQUEST['body'] ?? '';
204 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
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'] ?? '';
212 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
213 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
215 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
216 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
218 // Fetch the basic attachment data
219 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
220 unset($attachment['keywords']);
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;
228 if (!empty($attachment_img_src)) {
229 $attachment['images'] = [
231 'src' => $attachment_img_src,
232 'width' => $attachment_img_width,
233 'height' => $attachment_img_height
237 unset($attachment['images']);
240 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
241 $body .= $att_bbcode;
244 // Convert links with empty descriptions to links without an explicit description
245 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
247 if (!empty($orig_post)) {
248 $str_group_allow = $orig_post['allow_gid'];
249 $str_contact_allow = $orig_post['allow_cid'];
250 $str_group_deny = $orig_post['deny_gid'];
251 $str_contact_deny = $orig_post['deny_cid'];
252 $location = $orig_post['location'];
253 $coord = $orig_post['coord'];
254 $verb = $orig_post['verb'];
255 $objecttype = $orig_post['object-type'];
256 $app = $orig_post['app'];
257 $categories = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
258 $title = trim($_REQUEST['title'] ?? '');
260 $private = $orig_post['private'];
261 $pubmail_enabled = $orig_post['pubmail'];
262 $network = $orig_post['network'];
263 $guid = $orig_post['guid'];
264 $extid = $orig_post['extid'];
266 $aclFormatter = DI::aclFormatter();
267 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
268 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
269 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
270 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
272 $visibility = $_REQUEST['visibility'] ?? '';
273 if ($visibility === 'public') {
274 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
275 $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
276 } else if ($visibility === 'custom') {
277 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
278 // case that would make it public. So we always append the author's contact id to the allowed contacts.
279 // See https://github.com/friendica/friendica/issues/9672
280 $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid));
283 $title = trim($_REQUEST['title'] ?? '');
284 $location = trim($_REQUEST['location'] ?? '');
285 $coord = trim($_REQUEST['coord'] ?? '');
286 $verb = trim($_REQUEST['verb'] ?? '');
287 $emailcc = trim($_REQUEST['emailcc'] ?? '');
289 $network = trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN);
290 $guid = System::createUUID();
292 $postopts = $_REQUEST['postopts'] ?? '';
294 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
295 $private = Item::PRIVATE;
296 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
297 $private = Item::UNLISTED;
299 $private = Item::PUBLIC;
302 // If this is a comment, set the permissions from the parent.
304 if ($toplevel_item) {
305 // for non native networks use the network of the original post as network of the item
306 if (($toplevel_item['network'] != Protocol::DIASPORA)
307 && ($toplevel_item['network'] != Protocol::OSTATUS)
308 && ($network == '')) {
309 $network = $toplevel_item['network'];
312 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
313 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
314 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
315 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
316 $private = $toplevel_item['private'];
318 $wall = $toplevel_item['wall'];
321 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
323 if (!strlen($body)) {
325 System::jsonExit(['preview' => '']);
328 DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
330 DI::baseUrl()->redirect($return_path);
333 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
337 if (!empty($categories)) {
338 // get the "fileas" tags for this post
339 $filedas = FileTag::fileToArray($categories);
342 $list_array = explode(',', trim($_REQUEST['category'] ?? ''));
343 $categories = FileTag::arrayToFile($list_array, 'category');
345 if (!empty($filedas) && is_array($filedas)) {
346 // append the fileas stuff to the new categories list
347 $categories .= FileTag::arrayToFile($filedas);
350 // get contact info for poster
356 if (DI::userSession()->getLocalUserId() && ((DI::userSession()->getLocalUserId() == $profile_uid) || $allow_comment)) {
358 $author = DBA::selectFirst('contact', [], ['uid' => DI::userSession()->getLocalUserId(), 'self' => true]);
359 } elseif (!empty(DI::userSession()->getRemoteContactID($profile_uid))) {
360 $author = DBA::selectFirst('contact', [], ['id' => DI::userSession()->getRemoteContactID($profile_uid)]);
363 if (DBA::isResult($author)) {
364 $contact_id = $author['id'];
367 // get contact info for owner
368 if ($profile_uid == DI::userSession()->getLocalUserId() || $allow_comment) {
369 $contact_record = $author ?: [];
371 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
374 // Personal notes must never be altered to a forum post.
375 if ($posttype != Item::PT_PERSONAL_NOTE) {
376 // Look for any tags and linkify them
378 'uid' => DI::userSession()->getLocalUserId() ? DI::userSession()->getLocalUserId() : $profile_uid,
379 'gravity' => $toplevel_item_id ? Item::GRAVITY_COMMENT : Item::GRAVITY_PARENT,
380 'network' => $network,
382 'postopts' => $postopts,
383 'private' => $private,
384 'allow_cid' => $str_contact_allow,
385 'allow_gid' => $str_group_allow,
386 'deny_cid' => $str_contact_deny,
387 'deny_gid' => $str_group_deny,
390 $item = DI::contentItem()->expandTags($item);
392 $body = $item['body'];
393 $inform = $item['inform'];
394 $postopts = $item['postopts'];
395 $private = $item['private'];
396 $str_contact_allow = $item['allow_cid'];
397 $str_group_allow = $item['allow_gid'];
398 $str_contact_deny = $item['deny_cid'];
399 $str_group_deny = $item['deny_gid'];
405 * When a photo was uploaded into the message using the (profile wall) ajax
406 * uploader, The permissions are initially set to disallow anybody but the
407 * owner from seeing it. This is because the permissions may not yet have been
408 * set for the post. If it's private, the photo permissions should be set
409 * appropriately. But we didn't know the final permissions on the post until
410 * now. So now we'll look for links of uploaded messages that are in the
411 * post and set them to the same permissions as the post itself.
416 if (!$preview && Photo::setPermissionFromBody($body, $uid, $contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
417 $objecttype = Activity\ObjectType::IMAGE;
421 * Next link in any attachment references we find in the post.
425 /// @todo these lines should be moved to Model/Attach (Once it exists)
426 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
427 $attaches = $match[1];
428 if (count($attaches)) {
429 foreach ($attaches as $attach) {
430 // Ensure to only modify attachments that you own
431 $srch = '<' . intval($contact_id) . '>';
434 'allow_cid' => $srch,
440 if (!Attach::exists($condition)) {
444 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
445 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
446 $condition = ['id' => $attach];
447 Attach::update($fields, $condition);
452 // embedded bookmark or attachment in post? set bookmark flag
454 $data = BBCode::getAttachmentData($body);
456 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data['type']))
457 && ($posttype != Item::PT_PERSONAL_NOTE)) {
458 $posttype = Item::PT_PAGE;
459 $objecttype = Activity\ObjectType::BOOKMARK;
462 $body = DI::bbCodeVideo()->transform($body);
464 $body = BBCode::scaleExternalImages($body);
466 // Setting the object type if not defined before
468 $objecttype = Activity\ObjectType::NOTE; // Default value
469 $objectdata = BBCode::getAttachedData($body);
471 if ($objectdata['type'] == 'link') {
472 $objecttype = Activity\ObjectType::BOOKMARK;
473 } elseif ($objectdata['type'] == 'video') {
474 $objecttype = Activity\ObjectType::VIDEO;
475 } elseif ($objectdata['type'] == 'photo') {
476 $objecttype = Activity\ObjectType::IMAGE;
484 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
485 foreach ($match[2] as $mtch) {
486 $fields = ['id', 'filename', 'filesize', 'filetype'];
487 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
488 if ($attachment !== false) {
489 if (strlen($attachments)) {
492 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
493 $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
495 $body = str_replace($match[1],'',$body);
499 if (!strlen($verb)) {
500 $verb = Activity::POST;
503 if ($network == '') {
504 $network = Protocol::DFRN;
507 $gravity = ($toplevel_item_id ? Item::GRAVITY_COMMENT : Item::GRAVITY_PARENT);
509 // even if the post arrived via API we are considering that it
510 // originated on this site by default for determining relayability.
512 // Don't use "defaults" here. It would turn 0 to 1
513 if (!isset($_REQUEST['origin'])) {
516 $origin = $_REQUEST['origin'];
519 $uri = Item::newURI($guid);
521 // Fallback so that we alway have a parent uri
522 if (!$thr_parent_uri || !$toplevel_item_id) {
523 $thr_parent_uri = $uri;
527 'uid' => $profile_uid,
529 'gravity' => $gravity,
530 'network' => $network,
531 'contact-id' => $contact_id,
532 'owner-name' => $contact_record['name'] ?? '',
533 'owner-link' => $contact_record['url'] ?? '',
534 'owner-avatar' => $contact_record['thumb'] ?? '',
535 'author-name' => $author['name'],
536 'author-link' => $author['url'],
537 'author-avatar' => $author['thumb'],
538 'created' => empty($_REQUEST['created_at']) ? DateTimeFormat::utcNow() : $_REQUEST['created_at'],
539 'received' => DateTimeFormat::utcNow(),
546 'location' => $location,
548 'file' => $categories,
551 'post-type' => $posttype,
552 'object-type' => $objecttype,
553 'allow_cid' => $str_contact_allow,
554 'allow_gid' => $str_group_allow,
555 'deny_cid' => $str_contact_deny,
556 'deny_gid' => $str_group_deny,
557 'private' => $private,
558 'pubmail' => $pubmail_enabled,
559 'attach' => $attachments,
560 'thr-parent' => $thr_parent_uri,
561 'postopts' => $postopts,
564 'attachments' => $_REQUEST['attachments'] ?? [],
566 * These fields are for the convenience of addons...
567 * 'self' if true indicates the owner is posting on their own wall
568 * If parent is 0 it is a top-level post.
570 'parent' => $toplevel_item_id,
572 // This triggers posts via API and the mirror functions
573 'api_source' => false,
574 // This field is for storing the raw conversation data
575 'protocol' => Conversation::PARCEL_DIRECT,
576 'direction' => Conversation::PUSH,
579 // These cannot be part of above initialization ...
580 $datarray['edited'] = $datarray['created'];
581 $datarray['commented'] = $datarray['created'];
582 $datarray['changed'] = $datarray['created'];
583 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
584 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
586 $datarray['edit'] = $orig_post;
588 // Check for hashtags in the body and repair or add hashtag links
589 if ($preview || $orig_post) {
590 $datarray['body'] = Item::setHashtags($datarray['body']);
593 // preview mode - prepare the body for display and send it via json
595 // We set the datarray ID to -1 because in preview mode the dataray
596 // doesn't have an ID.
597 $datarray['id'] = -1;
598 $datarray['uri-id'] = -1;
599 $datarray['author-network'] = Protocol::DFRN;
600 $datarray['author-updated'] = '';
601 $datarray['author-gsid'] = 0;
602 $datarray['author-uri-id'] = ItemURI::getIdByURI($datarray['author-link']);
603 $datarray['owner-updated'] = '';
604 $datarray['has-media'] = false;
605 $datarray['quote-uri-id'] = Item::getQuoteUriId($datarray['body'], $datarray['uid']);
606 $datarray['body'] = BBCode::removeSharedData($datarray['body']);
608 $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true);
610 System::jsonExit(['preview' => $o]);
613 Hook::callAll('post_local',$datarray);
615 if (!empty($_REQUEST['scheduled_at'])) {
616 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
617 if ($scheduled_at > DateTimeFormat::utcNow()) {
618 unset($datarray['created']);
619 unset($datarray['edited']);
620 unset($datarray['commented']);
621 unset($datarray['received']);
622 unset($datarray['changed']);
623 unset($datarray['edit']);
624 unset($datarray['self']);
625 unset($datarray['api_source']);
627 Post\Delayed::add($datarray['uri'], $datarray, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
628 item_post_return(DI::baseUrl(), $return_path);
632 if (!empty($datarray['cancel'])) {
633 Logger::info('mod_item: post cancelled by addon.');
635 DI::baseUrl()->redirect($return_path);
638 $json = ['cancel' => 1];
639 if (!empty($_REQUEST['jsreload'])) {
640 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
643 System::jsonExit($json);
646 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
648 $quote_uri_id = Item::getQuoteUriId($datarray['body'], $datarray['uid']);
649 if (!empty($quote_uri_id)) {
650 $datarray['quote-uri-id'] = $quote_uri_id;
651 $datarray['body'] = BBCode::removeSharedData($datarray['body']);
656 'title' => $datarray['title'],
657 'body' => $datarray['body'],
658 'attach' => $datarray['attach'],
659 'file' => $datarray['file'],
660 'edited' => DateTimeFormat::utcNow(),
661 'changed' => DateTimeFormat::utcNow()
664 Item::update($fields, ['id' => $post_id]);
665 Item::updateDisplayCache($datarray['uri-id']);
668 DI::baseUrl()->redirect($return_path);
671 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
674 unset($datarray['edit']);
675 unset($datarray['self']);
676 unset($datarray['api_source']);
678 $post_id = Item::insert($datarray);
681 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
683 DI::baseUrl()->redirect($return_path);
686 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
689 $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
691 if (!DBA::isResult($datarray)) {
692 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
694 DI::baseUrl()->redirect($return_path);
697 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
700 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
702 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == Item::GRAVITY_COMMENT)) {
703 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
706 // These notifications are sent if someone else is commenting other your wall
707 if ($contact_record != $author) {
708 if ($toplevel_item_id) {
709 DI::notify()->createFromArray([
710 'type' => Notification\Type::COMMENT,
711 'otype' => Notification\ObjectType::ITEM,
712 'verb' => Activity::POST,
713 'uid' => $profile_uid,
714 'cid' => $datarray['author-id'],
716 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
718 } elseif (empty($forum_contact)) {
719 DI::notify()->createFromArray([
720 'type' => Notification\Type::WALL,
721 'otype' => Notification\ObjectType::ITEM,
722 'verb' => Activity::POST,
723 'uid' => $profile_uid,
724 'cid' => $datarray['author-id'],
726 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
731 Hook::callAll('post_local_end', $datarray);
733 if (strlen($emailcc) && $profile_uid == DI::userSession()->getLocalUserId()) {
734 $recipients = explode(',', $emailcc);
735 if (count($recipients)) {
736 foreach ($recipients as $recipient) {
737 $address = trim($recipient);
738 if (!strlen($address)) {
741 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
742 $datarray, $address, $author['thumb'] ?? ''));
747 Logger::debug('post_complete');
749 item_post_return(DI::baseUrl(), $return_path);
753 function item_post_return($baseurl, $return_path)
756 DI::baseUrl()->redirect($return_path);
759 $json = ['success' => 1];
760 if (!empty($_REQUEST['jsreload'])) {
761 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
764 Logger::debug('post_json', ['json' => $json]);
766 System::jsonExit($json);
769 function item_content(App $a)
771 if (!DI::userSession()->isAuthenticated()) {
772 throw new HTTPException\UnauthorizedException();
777 if (!$args->has(3)) {
778 throw new HTTPException\BadRequestException();
782 switch ($args->get(1)) {
784 if (DI::mode()->isAjax()) {
785 Item::deleteForUser(['id' => $args->get(2)], DI::userSession()->getLocalUserId());
786 // ajax return: [<item id>, 0 (no perm) | <owner id>]
787 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
789 if (!empty($args->get(3))) {
790 $o = drop_item($args->get(2), $args->get(3));
792 $o = drop_item($args->get(2));
798 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
799 if (empty($item['author-id'])) {
800 throw new HTTPException\NotFoundException('Item not found');
803 Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
805 if (DI::mode()->isAjax()) {
806 // ajax return: [<item id>, 0 (no perm) | <owner id>]
807 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
809 item_redirect_after_action($item, $args->get(3));
819 * @param string $return
821 * @throws HTTPException\InternalServerErrorException
823 function drop_item(int $id, string $return = ''): string
825 // Locate item to be deleted
826 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
828 if (!DBA::isResult($item)) {
829 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
830 DI::baseUrl()->redirect('network');
834 if ($item['deleted']) {
840 // check if logged in user is either the author or owner of this item
841 if (DI::userSession()->getRemoteContactID($item['uid']) == $item['contact-id']) {
842 $contact_id = $item['contact-id'];
845 if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
847 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
849 item_redirect_after_action($item, $return);
852 Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
853 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
854 DI::baseUrl()->redirect('display/' . $item['guid']);
861 function item_redirect_after_action(array $item, string $returnUrlHex)
863 $return_url = hex2bin($returnUrlHex);
865 // removes update_* from return_url to ignore Ajax refresh
866 $return_url = str_replace('update_', '', $return_url);
868 // Check if delete a comment
869 if ($item['gravity'] == Item::GRAVITY_COMMENT) {
870 if (!empty($item['parent'])) {
871 $parentitem = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid'], ['id' => $item['parent']]);
874 // Return to parent guid
875 if (!empty($parentitem)) {
876 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
878 } // In case something goes wrong
880 DI::baseUrl()->redirect('network');
884 // if unknown location or deleting top level post called from display
885 if (empty($return_url) || strpos($return_url, 'display') !== false) {
886 DI::baseUrl()->redirect('network');
889 DI::baseUrl()->redirect($return_url);