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\Group;
47 use Friendica\Model\Item;
48 use Friendica\Model\ItemURI;
49 use Friendica\Model\Notification;
50 use Friendica\Model\Photo;
51 use Friendica\Model\Post;
52 use Friendica\Model\Tag;
53 use Friendica\Model\User;
54 use Friendica\Network\HTTPException;
55 use Friendica\Object\EMail\ItemCCEMail;
56 use Friendica\Protocol\Activity;
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() && $toplevel_item_id && in_array($toplevel_item['private'], [Item::PUBLIC, Item::UNLISTED]) && 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 Logger::notice('Permission denied.', ['local' => local_user(), 'profile_uid' => $profile_uid, 'toplevel_item_id' => $toplevel_item_id, 'network' => $toplevel_item['network']]);
184 notice(DI::l10n()->t('Permission denied.'));
186 DI::baseUrl()->redirect($return_path);
189 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
192 // Init post instance
195 // is this an edited post?
197 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
200 $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
201 if (!DBA::isResult($user) && !$toplevel_item_id) {
208 $body = $_REQUEST['body'] ?? '';
209 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
211 // If we have a speparate attachment, we need to add it to the body.
212 if (!empty($has_attachment)) {
213 $attachment_type = $_REQUEST['attachment_type'] ?? '';
214 $attachment_title = $_REQUEST['attachment_title'] ?? '';
215 $attachment_text = $_REQUEST['attachment_text'] ?? '';
217 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
218 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
220 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
221 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
223 // Fetch the basic attachment data
224 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
225 unset($attachment['keywords']);
227 // Overwrite the basic data with possible changes from the frontend
228 $attachment['type'] = $attachment_type;
229 $attachment['title'] = $attachment_title;
230 $attachment['text'] = $attachment_text;
231 $attachment['url'] = $attachment_url;
233 if (!empty($attachment_img_src)) {
234 $attachment['images'] = [
236 'src' => $attachment_img_src,
237 'width' => $attachment_img_width,
238 'height' => $attachment_img_height
242 unset($attachment['images']);
245 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
246 $body .= $att_bbcode;
249 // Convert links with empty descriptions to links without an explicit description
250 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
252 if (!empty($orig_post)) {
253 $str_group_allow = $orig_post['allow_gid'];
254 $str_contact_allow = $orig_post['allow_cid'];
255 $str_group_deny = $orig_post['deny_gid'];
256 $str_contact_deny = $orig_post['deny_cid'];
257 $location = $orig_post['location'];
258 $coord = $orig_post['coord'];
259 $verb = $orig_post['verb'];
260 $objecttype = $orig_post['object-type'];
261 $app = $orig_post['app'];
262 $categories = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
263 $title = trim($_REQUEST['title'] ?? '');
265 $private = $orig_post['private'];
266 $pubmail_enabled = $orig_post['pubmail'];
267 $network = $orig_post['network'];
268 $guid = $orig_post['guid'];
269 $extid = $orig_post['extid'];
271 $aclFormatter = DI::aclFormatter();
272 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
273 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
274 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
275 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
277 $visibility = $_REQUEST['visibility'] ?? '';
278 if ($visibility === 'public') {
279 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
280 $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
281 } else if ($visibility === 'custom') {
282 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
283 // case that would make it public. So we always append the author's contact id to the allowed contacts.
284 // See https://github.com/friendica/friendica/issues/9672
285 $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid));
288 $title = trim($_REQUEST['title'] ?? '');
289 $location = trim($_REQUEST['location'] ?? '');
290 $coord = trim($_REQUEST['coord'] ?? '');
291 $verb = trim($_REQUEST['verb'] ?? '');
292 $emailcc = trim($_REQUEST['emailcc'] ?? '');
294 $network = trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN);
295 $guid = System::createUUID();
297 $postopts = $_REQUEST['postopts'] ?? '';
299 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
300 $private = Item::PRIVATE;
301 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
302 $private = Item::UNLISTED;
304 $private = Item::PUBLIC;
307 // If this is a comment, set the permissions from the parent.
309 if ($toplevel_item) {
310 // for non native networks use the network of the original post as network of the item
311 if (($toplevel_item['network'] != Protocol::DIASPORA)
312 && ($toplevel_item['network'] != Protocol::OSTATUS)
313 && ($network == "")) {
314 $network = $toplevel_item['network'];
317 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
318 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
319 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
320 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
321 $private = $toplevel_item['private'];
323 $wall = $toplevel_item['wall'];
326 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
328 // if using the API, we won't see pubmail_enable - figure out if it should be set
329 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
330 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
331 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
335 if (!strlen($body)) {
337 System::jsonExit(['preview' => '']);
340 notice(DI::l10n()->t('Empty post discarded.'));
342 DI::baseUrl()->redirect($return_path);
345 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
349 if (!empty($categories)) {
350 // get the "fileas" tags for this post
351 $filedas = FileTag::fileToArray($categories);
354 $list_array = explode(',', trim($_REQUEST['category'] ?? ''));
355 $categories = FileTag::arrayToFile($list_array, 'category');
357 if (!empty($filedas) && is_array($filedas)) {
358 // append the fileas stuff to the new categories list
359 $categories .= FileTag::arrayToFile($filedas);
362 // get contact info for poster
368 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
370 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
371 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
372 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
375 if (DBA::isResult($author)) {
376 $contact_id = $author['id'];
379 // get contact info for owner
380 if ($profile_uid == local_user() || $allow_comment) {
381 $contact_record = $author ?: [];
383 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
386 // Personal notes must never be altered to a forum post.
387 if ($posttype != Item::PT_PERSONAL_NOTE) {
388 // Look for any tags and linkify them
390 'uid' => local_user() ? local_user() : $profile_uid,
391 'gravity' => $toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT,
392 'network' => $network,
394 'postopts' => $postopts,
395 'private' => $private,
396 'allow_cid' => $str_contact_allow,
397 'allow_gid' => $str_group_allow,
398 'deny_cid' => $str_contact_deny,
399 'deny_gid' => $str_group_deny,
402 $item = DI::contentItem()->expandTags($item);
404 $body = $item['body'];
405 $inform = $item['inform'];
406 $postopts = $item['postopts'];
407 $private = $item['private'];
408 $str_contact_allow = $item['allow_cid'];
409 $str_group_allow = $item['allow_gid'];
410 $str_contact_deny = $item['deny_cid'];
411 $str_group_deny = $item['deny_gid'];
417 * When a photo was uploaded into the message using the (profile wall) ajax
418 * uploader, The permissions are initially set to disallow anybody but the
419 * owner from seeing it. This is because the permissions may not yet have been
420 * set for the post. If it's private, the photo permissions should be set
421 * appropriately. But we didn't know the final permissions on the post until
422 * now. So now we'll look for links of uploaded messages that are in the
423 * post and set them to the same permissions as the post itself.
428 if (!$preview && Photo::setPermissionFromBody($body, $uid, $contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
429 $objecttype = Activity\ObjectType::IMAGE;
433 * Next link in any attachment references we find in the post.
437 /// @todo these lines should be moved to Model/Attach (Once it exists)
438 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
439 $attaches = $match[1];
440 if (count($attaches)) {
441 foreach ($attaches as $attach) {
442 // Ensure to only modify attachments that you own
443 $srch = '<' . intval($contact_id) . '>';
445 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
447 if (!Attach::exists($condition)) {
451 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
452 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
453 $condition = ['id' => $attach];
454 Attach::update($fields, $condition);
459 // embedded bookmark or attachment in post? set bookmark flag
461 $data = BBCode::getAttachmentData($body);
463 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
464 && ($posttype != Item::PT_PERSONAL_NOTE)) {
465 $posttype = Item::PT_PAGE;
466 $objecttype = Activity\ObjectType::BOOKMARK;
469 $body = DI::bbCodeVideo()->transform($body);
471 $body = BBCode::scaleExternalImages($body);
473 // Setting the object type if not defined before
475 $objecttype = Activity\ObjectType::NOTE; // Default value
476 $objectdata = BBCode::getAttachedData($body);
478 if ($objectdata["type"] == "link") {
479 $objecttype = Activity\ObjectType::BOOKMARK;
480 } elseif ($objectdata["type"] == "video") {
481 $objecttype = Activity\ObjectType::VIDEO;
482 } elseif ($objectdata["type"] == "photo") {
483 $objecttype = Activity\ObjectType::IMAGE;
491 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
492 foreach ($match[2] as $mtch) {
493 $fields = ['id', 'filename', 'filesize', 'filetype'];
494 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
495 if ($attachment !== false) {
496 if (strlen($attachments)) {
499 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
500 $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
502 $body = str_replace($match[1],'',$body);
506 if (!strlen($verb)) {
507 $verb = Activity::POST;
510 if ($network == "") {
511 $network = Protocol::DFRN;
514 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
516 // even if the post arrived via API we are considering that it
517 // originated on this site by default for determining relayability.
519 // Don't use "defaults" here. It would turn 0 to 1
520 if (!isset($_REQUEST['origin'])) {
523 $origin = $_REQUEST['origin'];
526 $uri = Item::newURI($api_source ? $profile_uid : $uid, $guid);
528 // Fallback so that we alway have a parent uri
529 if (!$thr_parent_uri || !$toplevel_item_id) {
530 $thr_parent_uri = $uri;
534 $datarray['uid'] = $profile_uid;
535 $datarray['wall'] = $wall;
536 $datarray['gravity'] = $gravity;
537 $datarray['network'] = $network;
538 $datarray['contact-id'] = $contact_id;
539 $datarray['owner-name'] = $contact_record['name'] ?? '';
540 $datarray['owner-link'] = $contact_record['url'] ?? '';
541 $datarray['owner-avatar'] = $contact_record['thumb'] ?? '';
542 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
543 $datarray['author-name'] = $author['name'];
544 $datarray['author-link'] = $author['url'];
545 $datarray['author-avatar'] = $author['thumb'];
546 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
547 $datarray['created'] = DateTimeFormat::utcNow();
548 $datarray['edited'] = DateTimeFormat::utcNow();
549 $datarray['commented'] = DateTimeFormat::utcNow();
550 $datarray['received'] = DateTimeFormat::utcNow();
551 $datarray['changed'] = DateTimeFormat::utcNow();
552 $datarray['extid'] = $extid;
553 $datarray['guid'] = $guid;
554 $datarray['uri'] = $uri;
555 $datarray['title'] = $title;
556 $datarray['body'] = $body;
557 $datarray['app'] = $app;
558 $datarray['location'] = $location;
559 $datarray['coord'] = $coord;
560 $datarray['file'] = $categories;
561 $datarray['inform'] = $inform;
562 $datarray['verb'] = $verb;
563 $datarray['post-type'] = $posttype;
564 $datarray['object-type'] = $objecttype;
565 $datarray['allow_cid'] = $str_contact_allow;
566 $datarray['allow_gid'] = $str_group_allow;
567 $datarray['deny_cid'] = $str_contact_deny;
568 $datarray['deny_gid'] = $str_group_deny;
569 $datarray['private'] = $private;
570 $datarray['pubmail'] = $pubmail_enabled;
571 $datarray['attach'] = $attachments;
573 $datarray['thr-parent'] = $thr_parent_uri;
575 $datarray['postopts'] = $postopts;
576 $datarray['origin'] = $origin;
577 $datarray['object'] = $object;
579 $datarray['attachments'] = $_REQUEST['attachments'] ?? [];
582 * These fields are for the convenience of addons...
583 * 'self' if true indicates the owner is posting on their own wall
584 * If parent is 0 it is a top-level post.
586 $datarray['parent'] = $toplevel_item_id;
587 $datarray['self'] = $self;
589 // This triggers posts via API and the mirror functions
590 $datarray['api_source'] = $api_source;
592 // This field is for storing the raw conversation data
593 $datarray['protocol'] = Conversation::PARCEL_DIRECT;
594 $datarray['direction'] = Conversation::PUSH;
596 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['thr-parent']]);
597 if (DBA::isResult($conversation)) {
598 if ($conversation['conversation-uri'] != '') {
599 $datarray['conversation-uri'] = $conversation['conversation-uri'];
601 if ($conversation['conversation-href'] != '') {
602 $datarray['conversation-href'] = $conversation['conversation-href'];
607 $datarray['edit'] = true;
609 // If this was a share, add missing data here
610 $datarray = Item::addShareDataFromOriginal($datarray);
612 $datarray['edit'] = false;
615 // Check for hashtags in the body and repair or add hashtag links
616 if ($preview || $orig_post) {
617 $datarray['body'] = Item::setHashtags($datarray['body']);
620 // preview mode - prepare the body for display and send it via json
622 // We set the datarray ID to -1 because in preview mode the dataray
623 // doesn't have an ID.
624 $datarray["id"] = -1;
625 $datarray["uri-id"] = -1;
626 $datarray["author-network"] = Protocol::DFRN;
628 $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true);
630 System::jsonExit(['preview' => $o]);
633 Hook::callAll('post_local',$datarray);
635 if (!empty($_REQUEST['scheduled_at'])) {
636 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
637 if ($scheduled_at > DateTimeFormat::utcNow()) {
638 unset($datarray['created']);
639 unset($datarray['edited']);
640 unset($datarray['commented']);
641 unset($datarray['received']);
642 unset($datarray['changed']);
643 unset($datarray['edit']);
644 unset($datarray['self']);
645 unset($datarray['api_source']);
647 Post\Delayed::add($datarray['uri'], $datarray, PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
648 item_post_return(DI::baseUrl(), $api_source, $return_path);
652 if (!empty($datarray['cancel'])) {
653 Logger::info('mod_item: post cancelled by addon.');
655 DI::baseUrl()->redirect($return_path);
658 $json = ['cancel' => 1];
659 if (!empty($_REQUEST['jsreload'])) {
660 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
663 System::jsonExit($json);
666 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
669 // Fill the cache field
670 // This could be done in Item::update as well - but we have to check for the existance of some fields.
671 Item::putInCache($datarray);
674 'title' => $datarray['title'],
675 'body' => $datarray['body'],
676 'attach' => $datarray['attach'],
677 'file' => $datarray['file'],
678 'rendered-html' => $datarray['rendered-html'],
679 'rendered-hash' => $datarray['rendered-hash'],
680 'edited' => DateTimeFormat::utcNow(),
681 'changed' => DateTimeFormat::utcNow()];
683 Item::update($fields, ['id' => $post_id]);
686 DI::baseUrl()->redirect($return_path);
689 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
692 unset($datarray['edit']);
693 unset($datarray['self']);
694 unset($datarray['api_source']);
696 $post_id = Item::insert($datarray);
699 notice(DI::l10n()->t('Item wasn\'t stored.'));
701 DI::baseUrl()->redirect($return_path);
704 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
707 $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
709 if (!DBA::isResult($datarray)) {
710 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
712 DI::baseUrl()->redirect($return_path);
715 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
718 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
720 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
721 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
724 // These notifications are sent if someone else is commenting other your wall
725 if ($contact_record != $author) {
726 if ($toplevel_item_id) {
727 DI::notify()->createFromArray([
728 'type' => Notification\Type::COMMENT,
729 'otype' => Notification\ObjectType::ITEM,
730 'verb' => Activity::POST,
731 'uid' => $profile_uid,
732 'cid' => $datarray['author-id'],
734 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
736 } elseif (empty($forum_contact)) {
737 DI::notify()->createFromArray([
738 'type' => Notification\Type::WALL,
739 'otype' => Notification\ObjectType::ITEM,
740 'verb' => Activity::POST,
741 'uid' => $profile_uid,
742 'cid' => $datarray['author-id'],
744 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
749 Hook::callAll('post_local_end', $datarray);
751 if (strlen($emailcc) && $profile_uid == local_user()) {
752 $recipients = explode(',', $emailcc);
753 if (count($recipients)) {
754 foreach ($recipients as $recipient) {
755 $address = trim($recipient);
756 if (!strlen($address)) {
759 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
760 $datarray, $address, $author['thumb'] ?? ''));
765 Logger::info('post_complete');
771 item_post_return(DI::baseUrl(), $api_source, $return_path);
775 function item_post_return($baseurl, $api_source, $return_path)
782 DI::baseUrl()->redirect($return_path);
785 $json = ['success' => 1];
786 if (!empty($_REQUEST['jsreload'])) {
787 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
790 Logger::info('post_json', ['json' => $json]);
792 System::jsonExit($json);
795 function item_content(App $a)
797 if (!Session::isAuthenticated()) {
798 throw new HTTPException\UnauthorizedException();
803 if (!$args->has(3)) {
804 throw new HTTPException\BadRequestException();
808 switch ($args->get(1)) {
810 if (DI::mode()->isAjax()) {
811 Item::deleteForUser(['id' => $args->get(2)], local_user());
812 // ajax return: [<item id>, 0 (no perm) | <owner id>]
813 System::jsonExit([intval($args->get(2)), local_user()]);
815 if (!empty($args->get(3))) {
816 $o = drop_item($args->get(2), $args->get(3));
818 $o = drop_item($args->get(2));
823 $item = Post::selectFirstForUser(local_user(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
824 if (empty($item['author-id'])) {
825 throw new HTTPException\NotFoundException('Item not found');
828 Contact\User::setBlocked($item['author-id'], local_user(), true);
830 if (DI::mode()->isAjax()) {
831 // ajax return: [<item id>, 0 (no perm) | <owner id>]
832 System::jsonExit([intval($args->get(2)), local_user()]);
834 item_redirect_after_action($item, $args->get(3));
844 * @param string $return
846 * @throws HTTPException\InternalServerErrorException
848 function drop_item(int $id, string $return = '')
850 // locate item to be deleted
851 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
852 $item = Post::selectFirstForUser(local_user(), $fields, ['id' => $id]);
854 if (!DBA::isResult($item)) {
855 notice(DI::l10n()->t('Item not found.'));
856 DI::baseUrl()->redirect('network');
859 if ($item['deleted']) {
865 // check if logged in user is either the author or owner of this item
866 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
867 $contact_id = $item['contact-id'];
870 if ((local_user() == $item['uid']) || $contact_id) {
872 Item::deleteForUser(['id' => $item['id']], local_user());
874 item_redirect_after_action($item, $return);
876 Logger::notice('Permission denied.', ['local' => local_user(), 'uid' => $item['uid'], 'cid' => $contact_id]);
877 notice(DI::l10n()->t('Permission denied.'));
878 DI::baseUrl()->redirect('display/' . $item['guid']);
885 function item_redirect_after_action($item, $returnUrlHex)
887 $return_url = hex2bin($returnUrlHex);
889 // removes update_* from return_url to ignore Ajax refresh
890 $return_url = str_replace("update_", "", $return_url);
892 // Check if delete a comment
893 if ($item['gravity'] == GRAVITY_COMMENT) {
894 if (!empty($item['parent'])) {
895 $parentitem = Post::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
898 // Return to parent guid
899 if (!empty($parentitem)) {
900 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
902 } // In case something goes wrong
904 DI::baseUrl()->redirect('network');
908 // if unknown location or deleting top level post called from display
909 if (empty($return_url) || strpos($return_url, 'display') !== false) {
910 DI::baseUrl()->redirect('network');
913 DI::baseUrl()->redirect($return_url);