3 * @copyright Copyright (C) 2020, Friendica
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\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;
43 use Friendica\Model\Attach;
44 use Friendica\Model\Contact;
45 use Friendica\Model\Conversation;
46 use Friendica\Model\FileTag;
47 use Friendica\Model\Item;
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\Protocol\Diaspora;
57 use Friendica\Security\Security;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\ParseUrl;
60 use Friendica\Worker\Delivery;
62 function item_post(App $a) {
63 if (!Session::isAuthenticated()) {
64 throw new HTTPException\ForbiddenException();
69 if (!empty($_REQUEST['dropitems'])) {
70 $arr_drop = explode(',', $_REQUEST['dropitems']);
71 foreach ($arr_drop as $item) {
72 Item::deleteForUser(['id' => $item], $uid);
75 $json = ['success' => 1];
76 System::jsonExit($json);
79 Hook::callAll('post_local_start', $_REQUEST);
81 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
83 $api_source = $_REQUEST['api_source'] ?? false;
85 $return_path = $_REQUEST['return'] ?? '';
86 $preview = intval($_REQUEST['preview'] ?? 0);
89 * Check for doubly-submitted posts, and reject duplicates
90 * Note that we have to ignore previews, otherwise nothing will post
91 * after it's been previewed
93 if (!$preview && !empty($_REQUEST['post_id_random'])) {
94 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
95 Logger::info('item post: duplicate post');
96 item_post_return(DI::baseUrl(), $api_source, $return_path);
98 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
102 // Is this a reply to something?
103 $parent_item_id = intval($_REQUEST['parent'] ?? 0);
104 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
107 $toplevel_item = null;
108 $toplevel_item_id = 0;
109 $toplevel_user_id = null;
112 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
113 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
115 if ($parent_item_id || $thr_parent_uri) {
116 if ($parent_item_id) {
117 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item_id]);
118 } elseif ($thr_parent_uri) {
119 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
122 // if this isn't the top-level parent of the conversation, find it
123 if (DBA::isResult($parent_item)) {
124 // The URI and the contact is taken from the direct parent which needn't to be the top parent
125 $thr_parent_uri = $parent_item['uri'];
126 $toplevel_item = $parent_item;
128 if ($parent_item['gravity'] != GRAVITY_PARENT) {
129 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
133 if (!DBA::isResult($toplevel_item)) {
134 notice(DI::l10n()->t('Unable to locate original post.'));
136 DI::baseUrl()->redirect($return_path);
138 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
141 // When commenting on a public post then store the post for the current user
142 // This enables interaction like starring and saving into folders
143 if ($toplevel_item['uid'] == 0) {
144 $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], local_user());
145 Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
147 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
151 $toplevel_item_id = $toplevel_item['id'];
152 $toplevel_user_id = $toplevel_item['uid'];
154 $objecttype = Activity\ObjectType::COMMENT;
157 if ($toplevel_item_id) {
158 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
161 $post_id = intval($_REQUEST['post_id'] ?? 0);
162 $app = strip_tags($_REQUEST['source'] ?? '');
163 $extid = strip_tags($_REQUEST['extid'] ?? '');
164 $object = $_REQUEST['object'] ?? '';
166 // Don't use "defaults" here. It would turn 0 to 1
167 if (!isset($_REQUEST['wall'])) {
170 $wall = $_REQUEST['wall'];
173 // Ensure that the user id in a thread always stay the same
174 if (!is_null($toplevel_user_id) && in_array($toplevel_user_id, [local_user(), 0])) {
175 $profile_uid = $toplevel_user_id;
178 // Allow commenting if it is an answer to a public post
179 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
181 // Now check that valid personal details have been provided
182 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
183 notice(DI::l10n()->t('Permission denied.'));
185 DI::baseUrl()->redirect($return_path);
188 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
191 // Init post instance
194 // is this an edited post?
196 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
199 $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
200 if (!DBA::isResult($user) && !$toplevel_item_id) {
207 $body = $_REQUEST['body'] ?? '';
208 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
210 // If we have a speparate attachment, we need to add it to the body.
211 if (!empty($has_attachment)) {
212 $attachment_type = $_REQUEST['attachment_type'] ?? '';
213 $attachment_title = $_REQUEST['attachment_title'] ?? '';
214 $attachment_text = $_REQUEST['attachment_text'] ?? '';
216 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
217 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
219 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
220 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
222 // Fetch the basic attachment data
223 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
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 notice(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 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
354 if (!empty($filedas) && is_array($filedas)) {
355 // append the fileas stuff to the new categories list
356 $categories .= FileTag::arrayToFile($filedas);
359 // get contact info for poster
365 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
367 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
368 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
369 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
372 if (DBA::isResult($author)) {
373 $contact_id = $author['id'];
376 // get contact info for owner
377 if ($profile_uid == local_user() || $allow_comment) {
378 $contact_record = $author ?: [];
380 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
383 // Look for any tags and linkify them
385 $private_forum = false;
387 $only_to_forum = false;
390 $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) {
391 $tags = BBCode::getTags($body);
395 foreach ($tags as $tag) {
396 $tag_type = substr($tag, 0, 1);
398 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
402 /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
403 * Robert Johnson should be first in the $tags array
405 foreach ($tagged as $nextTag) {
406 if (stristr($nextTag, $tag . ' ')) {
411 $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
412 if ($success['replaced']) {
415 // When the forum is private or the forum is addressed with a "!" make the post private
416 if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
417 $private_forum = $success['contact']['prv'];
418 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
419 $private_id = $success['contact']['id'];
420 $forum_contact = $success['contact'];
421 } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
422 $private_forum = false;
423 $only_to_forum = true;
424 $private_id = $success['contact']['id'];
425 $forum_contact = $success['contact'];
432 $original_contact_id = $contact_id;
434 if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
435 // we tagged a forum in a top level post. Now we change the post
436 $private = $private_forum;
438 $str_group_allow = '';
439 $str_contact_deny = '';
440 $str_group_deny = '';
441 if ($private_forum) {
442 $str_contact_allow = '<' . $private_id . '>';
444 $str_contact_allow = '';
446 $contact_id = $private_id;
447 $contact_record = $forum_contact;
448 $_REQUEST['origin'] = false;
453 * When a photo was uploaded into the message using the (profile wall) ajax
454 * uploader, The permissions are initially set to disallow anybody but the
455 * owner from seeing it. This is because the permissions may not yet have been
456 * set for the post. If it's private, the photo permissions should be set
457 * appropriately. But we didn't know the final permissions on the post until
458 * now. So now we'll look for links of uploaded messages that are in the
459 * post and set them to the same permissions as the post itself.
464 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
465 $objecttype = Activity\ObjectType::IMAGE;
469 * Next link in any attachment references we find in the post.
473 /// @todo these lines should be moved to Model/Attach (Once it exists)
474 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
475 $attaches = $match[1];
476 if (count($attaches)) {
477 foreach ($attaches as $attach) {
478 // Ensure to only modify attachments that you own
479 $srch = '<' . intval($original_contact_id) . '>';
481 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
483 if (!Attach::exists($condition)) {
487 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
488 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
489 $condition = ['id' => $attach];
490 Attach::update($fields, $condition);
495 // embedded bookmark or attachment in post? set bookmark flag
497 $data = BBCode::getAttachmentData($body);
499 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
500 && ($posttype != Item::PT_PERSONAL_NOTE)) {
501 $posttype = Item::PT_PAGE;
502 $objecttype = Activity\ObjectType::BOOKMARK;
505 $body = DI::bbCodeVideo()->transform($body);
507 $body = BBCode::scaleExternalImages($body);
509 // Setting the object type if not defined before
511 $objecttype = Activity\ObjectType::NOTE; // Default value
512 $objectdata = BBCode::getAttachedData($body);
514 if ($objectdata["type"] == "link") {
515 $objecttype = Activity\ObjectType::BOOKMARK;
516 } elseif ($objectdata["type"] == "video") {
517 $objecttype = Activity\ObjectType::VIDEO;
518 } elseif ($objectdata["type"] == "photo") {
519 $objecttype = Activity\ObjectType::IMAGE;
527 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
528 foreach ($match[2] as $mtch) {
529 $fields = ['id', 'filename', 'filesize', 'filetype'];
530 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
531 if ($attachment !== false) {
532 if (strlen($attachments)) {
535 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
536 $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
538 $body = str_replace($match[1],'',$body);
542 if (!strlen($verb)) {
543 $verb = Activity::POST;
546 if ($network == "") {
547 $network = Protocol::DFRN;
550 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
552 // even if the post arrived via API we are considering that it
553 // originated on this site by default for determining relayability.
555 // Don't use "defaults" here. It would turn 0 to 1
556 if (!isset($_REQUEST['origin'])) {
559 $origin = $_REQUEST['origin'];
562 $uri = Item::newURI($api_source ? $profile_uid : $uid, $guid);
564 // Fallback so that we alway have a parent uri
565 if (!$thr_parent_uri || !$toplevel_item_id) {
566 $thr_parent_uri = $uri;
570 $datarray['uid'] = $profile_uid;
571 $datarray['wall'] = $wall;
572 $datarray['gravity'] = $gravity;
573 $datarray['network'] = $network;
574 $datarray['contact-id'] = $contact_id;
575 $datarray['owner-name'] = $contact_record['name'] ?? '';
576 $datarray['owner-link'] = $contact_record['url'] ?? '';
577 $datarray['owner-avatar'] = $contact_record['thumb'] ?? '';
578 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
579 $datarray['author-name'] = $author['name'];
580 $datarray['author-link'] = $author['url'];
581 $datarray['author-avatar'] = $author['thumb'];
582 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
583 $datarray['created'] = DateTimeFormat::utcNow();
584 $datarray['edited'] = DateTimeFormat::utcNow();
585 $datarray['commented'] = DateTimeFormat::utcNow();
586 $datarray['received'] = DateTimeFormat::utcNow();
587 $datarray['changed'] = DateTimeFormat::utcNow();
588 $datarray['extid'] = $extid;
589 $datarray['guid'] = $guid;
590 $datarray['uri'] = $uri;
591 $datarray['title'] = $title;
592 $datarray['body'] = $body;
593 $datarray['app'] = $app;
594 $datarray['location'] = $location;
595 $datarray['coord'] = $coord;
596 $datarray['file'] = $categories;
597 $datarray['inform'] = $inform;
598 $datarray['verb'] = $verb;
599 $datarray['post-type'] = $posttype;
600 $datarray['object-type'] = $objecttype;
601 $datarray['allow_cid'] = $str_contact_allow;
602 $datarray['allow_gid'] = $str_group_allow;
603 $datarray['deny_cid'] = $str_contact_deny;
604 $datarray['deny_gid'] = $str_group_deny;
605 $datarray['private'] = $private;
606 $datarray['pubmail'] = $pubmail_enabled;
607 $datarray['attach'] = $attachments;
609 $datarray['thr-parent'] = $thr_parent_uri;
611 $datarray['postopts'] = $postopts;
612 $datarray['origin'] = $origin;
613 $datarray['object'] = $object;
616 * These fields are for the convenience of addons...
617 * 'self' if true indicates the owner is posting on their own wall
618 * If parent is 0 it is a top-level post.
620 $datarray['parent'] = $toplevel_item_id;
621 $datarray['self'] = $self;
623 // This triggers posts via API and the mirror functions
624 $datarray['api_source'] = $api_source;
626 // This field is for storing the raw conversation data
627 $datarray['protocol'] = Conversation::PARCEL_DIRECT;
628 $datarray['direction'] = Conversation::PUSH;
630 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['thr-parent']]);
631 if (DBA::isResult($conversation)) {
632 if ($conversation['conversation-uri'] != '') {
633 $datarray['conversation-uri'] = $conversation['conversation-uri'];
635 if ($conversation['conversation-href'] != '') {
636 $datarray['conversation-href'] = $conversation['conversation-href'];
641 $datarray['edit'] = true;
643 // If this was a share, add missing data here
644 $datarray = Item::addShareDataFromOriginal($datarray);
646 $datarray['edit'] = false;
649 // Check for hashtags in the body and repair or add hashtag links
650 if ($preview || $orig_post) {
651 $datarray['body'] = Item::setHashtags($datarray['body']);
654 // preview mode - prepare the body for display and send it via json
656 // We set the datarray ID to -1 because in preview mode the dataray
657 // doesn't have an ID.
658 $datarray["id"] = -1;
659 $datarray["uri-id"] = -1;
660 $datarray["author-network"] = Protocol::DFRN;
662 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
664 System::jsonExit(['preview' => $o]);
667 Hook::callAll('post_local',$datarray);
669 if (!empty($datarray['cancel'])) {
670 Logger::info('mod_item: post cancelled by addon.');
672 DI::baseUrl()->redirect($return_path);
675 $json = ['cancel' => 1];
676 if (!empty($_REQUEST['jsreload'])) {
677 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
680 System::jsonExit($json);
684 // Fill the cache field
685 // This could be done in Item::update as well - but we have to check for the existance of some fields.
686 Item::putInCache($datarray);
689 'title' => $datarray['title'],
690 'body' => $datarray['body'],
691 'attach' => $datarray['attach'],
692 'file' => $datarray['file'],
693 'rendered-html' => $datarray['rendered-html'],
694 'rendered-hash' => $datarray['rendered-hash'],
695 'edited' => DateTimeFormat::utcNow(),
696 'changed' => DateTimeFormat::utcNow()];
698 Item::update($fields, ['id' => $post_id]);
701 DI::baseUrl()->redirect($return_path);
704 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
707 unset($datarray['edit']);
708 unset($datarray['self']);
709 unset($datarray['api_source']);
712 $signed = Diaspora::createCommentSignature($uid, $datarray);
713 if (!empty($signed)) {
714 $datarray['diaspora_signed_text'] = json_encode($signed);
718 $post_id = Item::insert($datarray);
721 notice(DI::l10n()->t('Item wasn\'t stored.'));
723 DI::baseUrl()->redirect($return_path);
726 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
729 $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
731 if (!DBA::isResult($datarray)) {
732 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
734 DI::baseUrl()->redirect($return_path);
737 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
740 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
742 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
743 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
746 // These notifications are sent if someone else is commenting other your wall
747 if ($contact_record != $author) {
748 if ($toplevel_item_id) {
750 'type' => Notification\Type::COMMENT,
751 'otype' => Notification\ObjectType::ITEM,
752 'verb' => Activity::POST,
753 'uid' => $profile_uid,
754 'cid' => $datarray['author-id'],
756 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
758 } elseif (empty($forum_contact)) {
760 'type' => Notification\Type::WALL,
761 'otype' => Notification\ObjectType::ITEM,
762 'verb' => Activity::POST,
763 'uid' => $profile_uid,
764 'cid' => $datarray['author-id'],
766 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
771 Hook::callAll('post_local_end', $datarray);
773 if (strlen($emailcc) && $profile_uid == local_user()) {
774 $recipients = explode(',', $emailcc);
775 if (count($recipients)) {
776 foreach ($recipients as $recipient) {
777 $address = trim($recipient);
778 if (!strlen($address)) {
781 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
782 $datarray, $address, $author['thumb'] ?? ''));
787 // When we are doing some forum posting via ! we have to start the notifier manually.
788 // These kind of posts don't initiate the notifier call in the item class.
789 if ($only_to_forum) {
790 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, (int)$datarray['uri-id'], (int)$datarray['uid']);
793 Logger::info('post_complete');
799 item_post_return(DI::baseUrl(), $api_source, $return_path);
803 function item_post_return($baseurl, $api_source, $return_path)
810 DI::baseUrl()->redirect($return_path);
813 $json = ['success' => 1];
814 if (!empty($_REQUEST['jsreload'])) {
815 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
818 Logger::info('post_json', ['json' => $json]);
820 System::jsonExit($json);
823 function item_content(App $a)
825 if (!Session::isAuthenticated()) {
826 throw new HTTPException\UnauthorizedException();
831 if (!$args->has(3)) {
832 throw new HTTPException\BadRequestException();
836 switch ($args->get(1)) {
838 if (DI::mode()->isAjax()) {
839 Item::deleteForUser(['id' => $args->get(2)], local_user());
840 // ajax return: [<item id>, 0 (no perm) | <owner id>]
841 System::jsonExit([intval($args->get(2)), local_user()]);
843 if (!empty($args->get(3))) {
844 $o = drop_item($args->get(2), $args->get(3));
846 $o = drop_item($args->get(2));
851 $item = Post::selectFirstForUser(local_user(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
852 if (empty($item['author-id'])) {
853 throw new HTTPException\NotFoundException('Item not found');
856 Contact\User::setBlocked($item['author-id'], local_user(), true);
858 if (DI::mode()->isAjax()) {
859 // ajax return: [<item id>, 0 (no perm) | <owner id>]
860 System::jsonExit([intval($args->get(2)), local_user()]);
862 item_redirect_after_action($item, $args->get(3));
872 * @param string $return
874 * @throws HTTPException\InternalServerErrorException
876 function drop_item(int $id, string $return = '')
878 // locate item to be deleted
879 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
880 $item = Post::selectFirstForUser(local_user(), $fields, ['id' => $id]);
882 if (!DBA::isResult($item)) {
883 notice(DI::l10n()->t('Item not found.'));
884 DI::baseUrl()->redirect('network');
887 if ($item['deleted']) {
893 // check if logged in user is either the author or owner of this item
894 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
895 $contact_id = $item['contact-id'];
898 if ((local_user() == $item['uid']) || $contact_id) {
900 Item::deleteForUser(['id' => $item['id']], local_user());
902 item_redirect_after_action($item, $return);
904 notice(DI::l10n()->t('Permission denied.'));
905 DI::baseUrl()->redirect('display/' . $item['guid']);
912 function item_redirect_after_action($item, $returnUrlHex)
914 $return_url = hex2bin($returnUrlHex);
916 // removes update_* from return_url to ignore Ajax refresh
917 $return_url = str_replace("update_", "", $return_url);
919 // Check if delete a comment
920 if ($item['gravity'] == GRAVITY_COMMENT) {
921 if (!empty($item['parent'])) {
922 $parentitem = Post::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
925 // Return to parent guid
926 if (!empty($parentitem)) {
927 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
929 } // In case something goes wrong
931 DI::baseUrl()->redirect('network');
935 // if unknown location or deleting top level post called from display
936 if (empty($return_url) || strpos($return_url, 'display') !== false) {
937 DI::baseUrl()->redirect('network');
940 DI::baseUrl()->redirect($return_url);