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\Session;
38 use Friendica\Core\System;
39 use Friendica\Core\Worker;
40 use Friendica\Database\DBA;
42 use Friendica\Model\Attach;
43 use Friendica\Model\Contact;
44 use Friendica\Model\Conversation;
45 use Friendica\Model\FileTag;
46 use Friendica\Model\Item;
47 use Friendica\Model\ItemURI;
48 use Friendica\Model\Notification;
49 use Friendica\Model\Photo;
50 use Friendica\Model\Post;
51 use Friendica\Model\Tag;
52 use Friendica\Model\User;
53 use Friendica\Network\HTTPException;
54 use Friendica\Object\EMail\ItemCCEMail;
55 use Friendica\Protocol\Activity;
56 use Friendica\Security\Security;
57 use Friendica\Util\DateTimeFormat;
58 use Friendica\Util\ParseUrl;
60 function item_post(App $a) {
61 if (!Session::isAuthenticated()) {
62 throw new HTTPException\ForbiddenException();
67 if (!empty($_REQUEST['dropitems'])) {
68 $arr_drop = explode(',', $_REQUEST['dropitems']);
69 foreach ($arr_drop as $item) {
70 Item::deleteForUser(['id' => $item], $uid);
73 $json = ['success' => 1];
74 System::jsonExit($json);
77 Hook::callAll('post_local_start', $_REQUEST);
79 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
81 $api_source = $_REQUEST['api_source'] ?? false;
83 $return_path = $_REQUEST['return'] ?? '';
84 $preview = intval($_REQUEST['preview'] ?? 0);
87 * Check for doubly-submitted posts, and reject duplicates
88 * Note that we have to ignore previews, otherwise nothing will post
89 * after it's been previewed
91 if (!$preview && !empty($_REQUEST['post_id_random'])) {
92 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
93 Logger::warning('duplicate post');
94 item_post_return(DI::baseUrl(), $api_source, $return_path);
96 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
100 // Is this a reply to something?
101 $parent_item_id = intval($_REQUEST['parent'] ?? 0);
102 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
105 $toplevel_item = null;
106 $toplevel_item_id = 0;
107 $toplevel_user_id = null;
110 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
111 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
113 if ($parent_item_id || $thr_parent_uri) {
114 if ($parent_item_id) {
115 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item_id]);
116 } elseif ($thr_parent_uri) {
117 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
120 // if this isn't the top-level parent of the conversation, find it
121 if (DBA::isResult($parent_item)) {
122 // The URI and the contact is taken from the direct parent which needn't to be the top parent
123 $thr_parent_uri = $parent_item['uri'];
124 $toplevel_item = $parent_item;
126 if ($parent_item['gravity'] != GRAVITY_PARENT) {
127 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
131 if (!DBA::isResult($toplevel_item)) {
132 DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
134 DI::baseUrl()->redirect($return_path);
136 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
139 // When commenting on a public post then store the post for the current user
140 // This enables interaction like starring and saving into folders
141 if ($toplevel_item['uid'] == 0) {
142 $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], local_user(), ['post-reason' => Item::PR_ACTIVITY]);
143 Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
145 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
149 $toplevel_item_id = $toplevel_item['id'];
150 $toplevel_user_id = $toplevel_item['uid'];
152 $objecttype = Activity\ObjectType::COMMENT;
155 if ($toplevel_item_id) {
156 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
159 $post_id = intval($_REQUEST['post_id'] ?? 0);
160 $app = strip_tags($_REQUEST['source'] ?? '');
161 $extid = strip_tags($_REQUEST['extid'] ?? '');
162 $object = $_REQUEST['object'] ?? '';
164 // Don't use "defaults" here. It would turn 0 to 1
165 if (!isset($_REQUEST['wall'])) {
168 $wall = $_REQUEST['wall'];
171 // Ensure that the user id in a thread always stay the same
172 if (!is_null($toplevel_user_id) && in_array($toplevel_user_id, [local_user(), 0])) {
173 $profile_uid = $toplevel_user_id;
176 // Allow commenting if it is an answer to a public post
177 $allow_comment = local_user() && $toplevel_item_id && in_array($toplevel_item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($toplevel_item['network'], Protocol::FEDERATED);
179 // Now check that valid personal details have been provided
180 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
181 Logger::warning('Permission denied.', ['local' => local_user(), 'profile_uid' => $profile_uid, 'toplevel_item_id' => $toplevel_item_id, 'network' => $toplevel_item['network']]);
182 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
184 DI::baseUrl()->redirect($return_path);
187 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
190 // Init post instance
193 // is this an edited post?
195 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
198 $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
199 if (!DBA::isResult($user) && !$toplevel_item_id) {
206 $body = $_REQUEST['body'] ?? '';
207 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
209 // If we have a speparate attachment, we need to add it to the body.
210 if (!empty($has_attachment)) {
211 $attachment_type = $_REQUEST['attachment_type'] ?? '';
212 $attachment_title = $_REQUEST['attachment_title'] ?? '';
213 $attachment_text = $_REQUEST['attachment_text'] ?? '';
215 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
216 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
218 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
219 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
221 // Fetch the basic attachment data
222 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
223 unset($attachment['keywords']);
225 // Overwrite the basic data with possible changes from the frontend
226 $attachment['type'] = $attachment_type;
227 $attachment['title'] = $attachment_title;
228 $attachment['text'] = $attachment_text;
229 $attachment['url'] = $attachment_url;
231 if (!empty($attachment_img_src)) {
232 $attachment['images'] = [
234 'src' => $attachment_img_src,
235 'width' => $attachment_img_width,
236 'height' => $attachment_img_height
240 unset($attachment['images']);
243 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
244 $body .= $att_bbcode;
247 // Convert links with empty descriptions to links without an explicit description
248 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
250 if (!empty($orig_post)) {
251 $str_group_allow = $orig_post['allow_gid'];
252 $str_contact_allow = $orig_post['allow_cid'];
253 $str_group_deny = $orig_post['deny_gid'];
254 $str_contact_deny = $orig_post['deny_cid'];
255 $location = $orig_post['location'];
256 $coord = $orig_post['coord'];
257 $verb = $orig_post['verb'];
258 $objecttype = $orig_post['object-type'];
259 $app = $orig_post['app'];
260 $categories = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
261 $title = trim($_REQUEST['title'] ?? '');
263 $private = $orig_post['private'];
264 $pubmail_enabled = $orig_post['pubmail'];
265 $network = $orig_post['network'];
266 $guid = $orig_post['guid'];
267 $extid = $orig_post['extid'];
269 $aclFormatter = DI::aclFormatter();
270 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
271 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
272 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
273 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
275 $visibility = $_REQUEST['visibility'] ?? '';
276 if ($visibility === 'public') {
277 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
278 $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
279 } else if ($visibility === 'custom') {
280 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
281 // case that would make it public. So we always append the author's contact id to the allowed contacts.
282 // See https://github.com/friendica/friendica/issues/9672
283 $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid));
286 $title = trim($_REQUEST['title'] ?? '');
287 $location = trim($_REQUEST['location'] ?? '');
288 $coord = trim($_REQUEST['coord'] ?? '');
289 $verb = trim($_REQUEST['verb'] ?? '');
290 $emailcc = trim($_REQUEST['emailcc'] ?? '');
292 $network = trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN);
293 $guid = System::createUUID();
295 $postopts = $_REQUEST['postopts'] ?? '';
297 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
298 $private = Item::PRIVATE;
299 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
300 $private = Item::UNLISTED;
302 $private = Item::PUBLIC;
305 // If this is a comment, set the permissions from the parent.
307 if ($toplevel_item) {
308 // for non native networks use the network of the original post as network of the item
309 if (($toplevel_item['network'] != Protocol::DIASPORA)
310 && ($toplevel_item['network'] != Protocol::OSTATUS)
311 && ($network == "")) {
312 $network = $toplevel_item['network'];
315 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
316 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
317 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
318 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
319 $private = $toplevel_item['private'];
321 $wall = $toplevel_item['wall'];
324 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
326 // if using the API, we won't see pubmail_enable - figure out if it should be set
327 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
328 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
329 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
333 if (!strlen($body)) {
335 System::jsonExit(['preview' => '']);
338 DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
340 DI::baseUrl()->redirect($return_path);
343 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
347 if (!empty($categories)) {
348 // get the "fileas" tags for this post
349 $filedas = FileTag::fileToArray($categories);
352 $list_array = explode(',', trim($_REQUEST['category'] ?? ''));
353 $categories = FileTag::arrayToFile($list_array, 'category');
355 if (!empty($filedas) && is_array($filedas)) {
356 // append the fileas stuff to the new categories list
357 $categories .= FileTag::arrayToFile($filedas);
360 // get contact info for poster
366 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
368 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
369 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
370 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
373 if (DBA::isResult($author)) {
374 $contact_id = $author['id'];
377 // get contact info for owner
378 if ($profile_uid == local_user() || $allow_comment) {
379 $contact_record = $author ?: [];
381 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
384 // Personal notes must never be altered to a forum post.
385 if ($posttype != Item::PT_PERSONAL_NOTE) {
386 // Look for any tags and linkify them
388 'uid' => local_user() ? local_user() : $profile_uid,
389 'gravity' => $toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT,
390 'network' => $network,
392 'postopts' => $postopts,
393 'private' => $private,
394 'allow_cid' => $str_contact_allow,
395 'allow_gid' => $str_group_allow,
396 'deny_cid' => $str_contact_deny,
397 'deny_gid' => $str_group_deny,
400 $item = DI::contentItem()->expandTags($item);
402 $body = $item['body'];
403 $inform = $item['inform'];
404 $postopts = $item['postopts'];
405 $private = $item['private'];
406 $str_contact_allow = $item['allow_cid'];
407 $str_group_allow = $item['allow_gid'];
408 $str_contact_deny = $item['deny_cid'];
409 $str_group_deny = $item['deny_gid'];
415 * When a photo was uploaded into the message using the (profile wall) ajax
416 * uploader, The permissions are initially set to disallow anybody but the
417 * owner from seeing it. This is because the permissions may not yet have been
418 * set for the post. If it's private, the photo permissions should be set
419 * appropriately. But we didn't know the final permissions on the post until
420 * now. So now we'll look for links of uploaded messages that are in the
421 * post and set them to the same permissions as the post itself.
426 if (!$preview && Photo::setPermissionFromBody($body, $uid, $contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
427 $objecttype = Activity\ObjectType::IMAGE;
431 * Next link in any attachment references we find in the post.
435 /// @todo these lines should be moved to Model/Attach (Once it exists)
436 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
437 $attaches = $match[1];
438 if (count($attaches)) {
439 foreach ($attaches as $attach) {
440 // Ensure to only modify attachments that you own
441 $srch = '<' . intval($contact_id) . '>';
444 'allow_cid' => $srch,
450 if (!Attach::exists($condition)) {
454 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
455 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
456 $condition = ['id' => $attach];
457 Attach::update($fields, $condition);
462 // embedded bookmark or attachment in post? set bookmark flag
464 $data = BBCode::getAttachmentData($body);
466 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
467 && ($posttype != Item::PT_PERSONAL_NOTE)) {
468 $posttype = Item::PT_PAGE;
469 $objecttype = Activity\ObjectType::BOOKMARK;
472 $body = DI::bbCodeVideo()->transform($body);
474 $body = BBCode::scaleExternalImages($body);
476 // Setting the object type if not defined before
478 $objecttype = Activity\ObjectType::NOTE; // Default value
479 $objectdata = BBCode::getAttachedData($body);
481 if ($objectdata["type"] == "link") {
482 $objecttype = Activity\ObjectType::BOOKMARK;
483 } elseif ($objectdata["type"] == "video") {
484 $objecttype = Activity\ObjectType::VIDEO;
485 } elseif ($objectdata["type"] == "photo") {
486 $objecttype = Activity\ObjectType::IMAGE;
494 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
495 foreach ($match[2] as $mtch) {
496 $fields = ['id', 'filename', 'filesize', 'filetype'];
497 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
498 if ($attachment !== false) {
499 if (strlen($attachments)) {
502 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
503 $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
505 $body = str_replace($match[1],'',$body);
509 if (!strlen($verb)) {
510 $verb = Activity::POST;
513 if ($network == "") {
514 $network = Protocol::DFRN;
517 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
519 // even if the post arrived via API we are considering that it
520 // originated on this site by default for determining relayability.
522 // Don't use "defaults" here. It would turn 0 to 1
523 if (!isset($_REQUEST['origin'])) {
526 $origin = $_REQUEST['origin'];
529 $uri = Item::newURI($guid);
531 // Fallback so that we alway have a parent uri
532 if (!$thr_parent_uri || !$toplevel_item_id) {
533 $thr_parent_uri = $uri;
537 $datarray['uid'] = $profile_uid;
538 $datarray['wall'] = $wall;
539 $datarray['gravity'] = $gravity;
540 $datarray['network'] = $network;
541 $datarray['contact-id'] = $contact_id;
542 $datarray['owner-name'] = $contact_record['name'] ?? '';
543 $datarray['owner-link'] = $contact_record['url'] ?? '';
544 $datarray['owner-avatar'] = $contact_record['thumb'] ?? '';
545 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
546 $datarray['author-name'] = $author['name'];
547 $datarray['author-link'] = $author['url'];
548 $datarray['author-avatar'] = $author['thumb'];
549 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
550 $datarray['created'] = empty($_REQUEST['created_at']) ? DateTimeFormat::utcNow() : $_REQUEST['created_at'];
551 $datarray['edited'] = $datarray['created'];
552 $datarray['commented'] = $datarray['created'];
553 $datarray['changed'] = $datarray['created'];
554 $datarray['received'] = DateTimeFormat::utcNow();
555 $datarray['extid'] = $extid;
556 $datarray['guid'] = $guid;
557 $datarray['uri'] = $uri;
558 $datarray['title'] = $title;
559 $datarray['body'] = $body;
560 $datarray['app'] = $app;
561 $datarray['location'] = $location;
562 $datarray['coord'] = $coord;
563 $datarray['file'] = $categories;
564 $datarray['inform'] = $inform;
565 $datarray['verb'] = $verb;
566 $datarray['post-type'] = $posttype;
567 $datarray['object-type'] = $objecttype;
568 $datarray['allow_cid'] = $str_contact_allow;
569 $datarray['allow_gid'] = $str_group_allow;
570 $datarray['deny_cid'] = $str_contact_deny;
571 $datarray['deny_gid'] = $str_group_deny;
572 $datarray['private'] = $private;
573 $datarray['pubmail'] = $pubmail_enabled;
574 $datarray['attach'] = $attachments;
576 $datarray['thr-parent'] = $thr_parent_uri;
578 $datarray['postopts'] = $postopts;
579 $datarray['origin'] = $origin;
580 $datarray['object'] = $object;
582 $datarray['attachments'] = $_REQUEST['attachments'] ?? [];
585 * These fields are for the convenience of addons...
586 * 'self' if true indicates the owner is posting on their own wall
587 * If parent is 0 it is a top-level post.
589 $datarray['parent'] = $toplevel_item_id;
590 $datarray['self'] = $self;
592 // This triggers posts via API and the mirror functions
593 $datarray['api_source'] = $api_source;
595 // This field is for storing the raw conversation data
596 $datarray['protocol'] = Conversation::PARCEL_DIRECT;
597 $datarray['direction'] = Conversation::PUSH;
599 $datarray['edit'] = $orig_post;
601 // Check for hashtags in the body and repair or add hashtag links
602 if ($preview || $orig_post) {
603 $datarray['body'] = Item::setHashtags($datarray['body']);
606 // preview mode - prepare the body for display and send it via json
608 // We set the datarray ID to -1 because in preview mode the dataray
609 // doesn't have an ID.
610 $datarray["id"] = -1;
611 $datarray["uri-id"] = -1;
612 $datarray["author-network"] = Protocol::DFRN;
613 $datarray["author-updated"] = '';
614 $datarray["author-gsid"] = 0;
615 $datarray["author-uri-id"] = ItemURI::getIdByURI($datarray["author-link"]);
616 $datarray["owner-updated"] = '';
617 $datarray["has-media"] = false;
618 $datarray['body'] = Item::improveSharedDataInBody($datarray);
620 $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true);
622 System::jsonExit(['preview' => $o]);
625 Hook::callAll('post_local',$datarray);
627 if (!empty($_REQUEST['scheduled_at'])) {
628 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
629 if ($scheduled_at > DateTimeFormat::utcNow()) {
630 unset($datarray['created']);
631 unset($datarray['edited']);
632 unset($datarray['commented']);
633 unset($datarray['received']);
634 unset($datarray['changed']);
635 unset($datarray['edit']);
636 unset($datarray['self']);
637 unset($datarray['api_source']);
639 Post\Delayed::add($datarray['uri'], $datarray, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
640 item_post_return(DI::baseUrl(), $api_source, $return_path);
644 if (!empty($datarray['cancel'])) {
645 Logger::info('mod_item: post cancelled by addon.');
647 DI::baseUrl()->redirect($return_path);
650 $json = ['cancel' => 1];
651 if (!empty($_REQUEST['jsreload'])) {
652 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
655 System::jsonExit($json);
658 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
659 $datarray['body'] = Item::improveSharedDataInBody($datarray);
663 'title' => $datarray['title'],
664 'body' => $datarray['body'],
665 'attach' => $datarray['attach'],
666 'file' => $datarray['file'],
667 'edited' => DateTimeFormat::utcNow(),
668 'changed' => DateTimeFormat::utcNow()
671 Item::update($fields, ['id' => $post_id]);
672 Item::updateDisplayCache($datarray['uri-id']);
675 DI::baseUrl()->redirect($return_path);
678 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
681 unset($datarray['edit']);
682 unset($datarray['self']);
683 unset($datarray['api_source']);
685 $post_id = Item::insert($datarray);
688 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
690 DI::baseUrl()->redirect($return_path);
693 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
696 $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
698 if (!DBA::isResult($datarray)) {
699 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
701 DI::baseUrl()->redirect($return_path);
704 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
707 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
709 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
710 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
713 // These notifications are sent if someone else is commenting other your wall
714 if ($contact_record != $author) {
715 if ($toplevel_item_id) {
716 DI::notify()->createFromArray([
717 'type' => Notification\Type::COMMENT,
718 'otype' => Notification\ObjectType::ITEM,
719 'verb' => Activity::POST,
720 'uid' => $profile_uid,
721 'cid' => $datarray['author-id'],
723 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
725 } elseif (empty($forum_contact)) {
726 DI::notify()->createFromArray([
727 'type' => Notification\Type::WALL,
728 'otype' => Notification\ObjectType::ITEM,
729 'verb' => Activity::POST,
730 'uid' => $profile_uid,
731 'cid' => $datarray['author-id'],
733 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
738 Hook::callAll('post_local_end', $datarray);
740 if (strlen($emailcc) && $profile_uid == local_user()) {
741 $recipients = explode(',', $emailcc);
742 if (count($recipients)) {
743 foreach ($recipients as $recipient) {
744 $address = trim($recipient);
745 if (!strlen($address)) {
748 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
749 $datarray, $address, $author['thumb'] ?? ''));
754 Logger::debug('post_complete');
760 item_post_return(DI::baseUrl(), $api_source, $return_path);
764 function item_post_return($baseurl, $api_source, $return_path)
771 DI::baseUrl()->redirect($return_path);
774 $json = ['success' => 1];
775 if (!empty($_REQUEST['jsreload'])) {
776 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
779 Logger::debug('post_json', ['json' => $json]);
781 System::jsonExit($json);
784 function item_content(App $a)
786 if (!Session::isAuthenticated()) {
787 throw new HTTPException\UnauthorizedException();
792 if (!$args->has(3)) {
793 throw new HTTPException\BadRequestException();
797 switch ($args->get(1)) {
799 if (DI::mode()->isAjax()) {
800 Item::deleteForUser(['id' => $args->get(2)], local_user());
801 // ajax return: [<item id>, 0 (no perm) | <owner id>]
802 System::jsonExit([intval($args->get(2)), local_user()]);
804 if (!empty($args->get(3))) {
805 $o = drop_item($args->get(2), $args->get(3));
807 $o = drop_item($args->get(2));
812 $item = Post::selectFirstForUser(local_user(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
813 if (empty($item['author-id'])) {
814 throw new HTTPException\NotFoundException('Item not found');
817 Contact\User::setBlocked($item['author-id'], local_user(), true);
819 if (DI::mode()->isAjax()) {
820 // ajax return: [<item id>, 0 (no perm) | <owner id>]
821 System::jsonExit([intval($args->get(2)), local_user()]);
823 item_redirect_after_action($item, $args->get(3));
833 * @param string $return
835 * @throws HTTPException\InternalServerErrorException
837 function drop_item(int $id, string $return = '')
839 // locate item to be deleted
840 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
841 $item = Post::selectFirstForUser(local_user(), $fields, ['id' => $id]);
843 if (!DBA::isResult($item)) {
844 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
845 DI::baseUrl()->redirect('network');
848 if ($item['deleted']) {
854 // check if logged in user is either the author or owner of this item
855 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
856 $contact_id = $item['contact-id'];
859 if ((local_user() == $item['uid']) || $contact_id) {
861 Item::deleteForUser(['id' => $item['id']], local_user());
863 item_redirect_after_action($item, $return);
865 Logger::warning('Permission denied.', ['local' => local_user(), 'uid' => $item['uid'], 'cid' => $contact_id]);
866 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
867 DI::baseUrl()->redirect('display/' . $item['guid']);
874 function item_redirect_after_action($item, $returnUrlHex)
876 $return_url = hex2bin($returnUrlHex);
878 // removes update_* from return_url to ignore Ajax refresh
879 $return_url = str_replace("update_", "", $return_url);
881 // Check if delete a comment
882 if ($item['gravity'] == GRAVITY_COMMENT) {
883 if (!empty($item['parent'])) {
884 $parentitem = Post::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
887 // Return to parent guid
888 if (!empty($parentitem)) {
889 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
891 } // In case something goes wrong
893 DI::baseUrl()->redirect('network');
897 // if unknown location or deleting top level post called from display
898 if (empty($return_url) || strpos($return_url, 'display') !== false) {
899 DI::baseUrl()->redirect('network');
902 DI::baseUrl()->redirect($return_url);