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 (!DI::userSession()->isAuthenticated()) {
62 throw new HTTPException\ForbiddenException();
65 $uid = DI::userSession()->getLocalUserId();
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) ?: DI::userSession()->getLocalUserId();
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'] != Item::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'], DI::userSession()->getLocalUserId(), ['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, [DI::userSession()->getLocalUserId(), 0])) {
173 $profile_uid = $toplevel_user_id;
176 // Allow commenting if it is an answer to a public post
177 $allow_comment = DI::userSession()->getLocalUserId() && $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' => DI::userSession()->getLocalUserId(), '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 == DI::userSession()->getLocalUserId() && !$private) {
328 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
329 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", DI::userSession()->getLocalUserId(), '']);
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 (DI::userSession()->getLocalUserId() && ((DI::userSession()->getLocalUserId() == $profile_uid) || $allow_comment)) {
368 $author = DBA::selectFirst('contact', [], ['uid' => DI::userSession()->getLocalUserId(), 'self' => true]);
369 } elseif (!empty(DI::userSession()->getRemoteContactID($profile_uid))) {
370 $author = DBA::selectFirst('contact', [], ['id' => DI::userSession()->getRemoteContactID($profile_uid)]);
373 if (DBA::isResult($author)) {
374 $contact_id = $author['id'];
377 // get contact info for owner
378 if ($profile_uid == DI::userSession()->getLocalUserId() || $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' => DI::userSession()->getLocalUserId() ? DI::userSession()->getLocalUserId() : $profile_uid,
389 'gravity' => $toplevel_item_id ? Item::GRAVITY_COMMENT : Item::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 ? Item::GRAVITY_COMMENT : Item::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 'uid' => $profile_uid,
539 'gravity' => $gravity,
540 'network' => $network,
541 'contact-id' => $contact_id,
542 'owner-name' => $contact_record['name'] ?? '',
543 'owner-link' => $contact_record['url'] ?? '',
544 'owner-avatar' => $contact_record['thumb'] ?? '',
545 'author-name' => $author['name'],
546 'author-link' => $author['url'],
547 'author-avatar' => $author['thumb'],
548 'created' => empty($_REQUEST['created_at']) ? DateTimeFormat::utcNow() : $_REQUEST['created_at'],
549 'received' => DateTimeFormat::utcNow(),
556 'location' => $location,
558 'file' => $categories,
561 'post-type' => $posttype,
562 'object-type' => $objecttype,
563 'allow_cid' => $str_contact_allow,
564 'allow_gid' => $str_group_allow,
565 'deny_cid' => $str_contact_deny,
566 'deny_gid' => $str_group_deny,
567 'private' => $private,
568 'pubmail' => $pubmail_enabled,
569 'attach' => $attachments,
570 'thr-parent' => $thr_parent_uri,
571 'postopts' => $postopts,
574 'attachments' => $_REQUEST['attachments'] ?? [],
576 * These fields are for the convenience of addons...
577 * 'self' if true indicates the owner is posting on their own wall
578 * If parent is 0 it is a top-level post.
580 'parent' => $toplevel_item_id,
582 // This triggers posts via API and the mirror functions
583 'api_source' => $api_source,
584 // This field is for storing the raw conversation data
585 'protocol' => Conversation::PARCEL_DIRECT,
586 'direction' => Conversation::PUSH,
589 // These cannot be part of above initialization ...
590 $datarray['edited'] = $datarray['created'];
591 $datarray['commented'] = $datarray['created'];
592 $datarray['changed'] = $datarray['created'];
593 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
594 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
596 $datarray['edit'] = $orig_post;
598 // Check for hashtags in the body and repair or add hashtag links
599 if ($preview || $orig_post) {
600 $datarray['body'] = Item::setHashtags($datarray['body']);
603 // preview mode - prepare the body for display and send it via json
605 // We set the datarray ID to -1 because in preview mode the dataray
606 // doesn't have an ID.
607 $datarray['id'] = -1;
608 $datarray['uri-id'] = -1;
609 $datarray['author-network'] = Protocol::DFRN;
610 $datarray['author-updated'] = '';
611 $datarray['author-gsid'] = 0;
612 $datarray['author-uri-id'] = ItemURI::getIdByURI($datarray['author-link']);
613 $datarray['owner-updated'] = '';
614 $datarray['has-media'] = false;
615 $datarray['body'] = Item::improveSharedDataInBody($datarray);
617 $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true);
619 System::jsonExit(['preview' => $o]);
622 Hook::callAll('post_local',$datarray);
624 if (!empty($_REQUEST['scheduled_at'])) {
625 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
626 if ($scheduled_at > DateTimeFormat::utcNow()) {
627 unset($datarray['created']);
628 unset($datarray['edited']);
629 unset($datarray['commented']);
630 unset($datarray['received']);
631 unset($datarray['changed']);
632 unset($datarray['edit']);
633 unset($datarray['self']);
634 unset($datarray['api_source']);
636 Post\Delayed::add($datarray['uri'], $datarray, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
637 item_post_return(DI::baseUrl(), $api_source, $return_path);
641 if (!empty($datarray['cancel'])) {
642 Logger::info('mod_item: post cancelled by addon.');
644 DI::baseUrl()->redirect($return_path);
647 $json = ['cancel' => 1];
648 if (!empty($_REQUEST['jsreload'])) {
649 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
652 System::jsonExit($json);
655 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
656 $datarray['body'] = Item::improveSharedDataInBody($datarray);
660 'title' => $datarray['title'],
661 'body' => $datarray['body'],
662 'attach' => $datarray['attach'],
663 'file' => $datarray['file'],
664 'edited' => DateTimeFormat::utcNow(),
665 'changed' => DateTimeFormat::utcNow()
668 Item::update($fields, ['id' => $post_id]);
669 Item::updateDisplayCache($datarray['uri-id']);
672 DI::baseUrl()->redirect($return_path);
675 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
678 unset($datarray['edit']);
679 unset($datarray['self']);
680 unset($datarray['api_source']);
682 $post_id = Item::insert($datarray);
685 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
687 DI::baseUrl()->redirect($return_path);
690 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
693 $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
695 if (!DBA::isResult($datarray)) {
696 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
698 DI::baseUrl()->redirect($return_path);
701 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
704 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
706 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == Item::GRAVITY_COMMENT)) {
707 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
710 // These notifications are sent if someone else is commenting other your wall
711 if ($contact_record != $author) {
712 if ($toplevel_item_id) {
713 DI::notify()->createFromArray([
714 'type' => Notification\Type::COMMENT,
715 'otype' => Notification\ObjectType::ITEM,
716 'verb' => Activity::POST,
717 'uid' => $profile_uid,
718 'cid' => $datarray['author-id'],
720 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
722 } elseif (empty($forum_contact)) {
723 DI::notify()->createFromArray([
724 'type' => Notification\Type::WALL,
725 'otype' => Notification\ObjectType::ITEM,
726 'verb' => Activity::POST,
727 'uid' => $profile_uid,
728 'cid' => $datarray['author-id'],
730 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
735 Hook::callAll('post_local_end', $datarray);
737 if (strlen($emailcc) && $profile_uid == DI::userSession()->getLocalUserId()) {
738 $recipients = explode(',', $emailcc);
739 if (count($recipients)) {
740 foreach ($recipients as $recipient) {
741 $address = trim($recipient);
742 if (!strlen($address)) {
745 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
746 $datarray, $address, $author['thumb'] ?? ''));
751 Logger::debug('post_complete');
757 item_post_return(DI::baseUrl(), $api_source, $return_path);
761 function item_post_return($baseurl, $api_source, $return_path)
768 DI::baseUrl()->redirect($return_path);
771 $json = ['success' => 1];
772 if (!empty($_REQUEST['jsreload'])) {
773 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
776 Logger::debug('post_json', ['json' => $json]);
778 System::jsonExit($json);
781 function item_content(App $a)
783 if (!DI::userSession()->isAuthenticated()) {
784 throw new HTTPException\UnauthorizedException();
789 if (!$args->has(3)) {
790 throw new HTTPException\BadRequestException();
794 switch ($args->get(1)) {
796 if (DI::mode()->isAjax()) {
797 Item::deleteForUser(['id' => $args->get(2)], DI::userSession()->getLocalUserId());
798 // ajax return: [<item id>, 0 (no perm) | <owner id>]
799 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
801 if (!empty($args->get(3))) {
802 $o = drop_item($args->get(2), $args->get(3));
804 $o = drop_item($args->get(2));
810 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
811 if (empty($item['author-id'])) {
812 throw new HTTPException\NotFoundException('Item not found');
815 Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
817 if (DI::mode()->isAjax()) {
818 // ajax return: [<item id>, 0 (no perm) | <owner id>]
819 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
821 item_redirect_after_action($item, $args->get(3));
831 * @param string $return
833 * @throws HTTPException\InternalServerErrorException
835 function drop_item(int $id, string $return = ''): string
837 // Locate item to be deleted
838 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
840 if (!DBA::isResult($item)) {
841 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
842 DI::baseUrl()->redirect('network');
846 if ($item['deleted']) {
852 // check if logged in user is either the author or owner of this item
853 if (DI::userSession()->getRemoteContactID($item['uid']) == $item['contact-id']) {
854 $contact_id = $item['contact-id'];
857 if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
859 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
861 item_redirect_after_action($item, $return);
864 Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
865 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
866 DI::baseUrl()->redirect('display/' . $item['guid']);
873 function item_redirect_after_action(array $item, string $returnUrlHex)
875 $return_url = hex2bin($returnUrlHex);
877 // removes update_* from return_url to ignore Ajax refresh
878 $return_url = str_replace('update_', '', $return_url);
880 // Check if delete a comment
881 if ($item['gravity'] == Item::GRAVITY_COMMENT) {
882 if (!empty($item['parent'])) {
883 $parentitem = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid'], ['id' => $item['parent']]);
886 // Return to parent guid
887 if (!empty($parentitem)) {
888 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
890 } // In case something goes wrong
892 DI::baseUrl()->redirect('network');
896 // if unknown location or deleting top level post called from display
897 if (empty($return_url) || strpos($return_url, 'display') !== false) {
898 DI::baseUrl()->redirect('network');
901 DI::baseUrl()->redirect($return_url);