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\Renderer;
39 use Friendica\Core\Session;
40 use Friendica\Core\System;
41 use Friendica\Core\Worker;
42 use Friendica\Database\DBA;
44 use Friendica\Model\Attach;
45 use Friendica\Model\Contact;
46 use Friendica\Model\Conversation;
47 use Friendica\Model\FileTag;
48 use Friendica\Model\Item;
49 use Friendica\Model\Notify\Type;
50 use Friendica\Model\Photo;
51 use Friendica\Model\Tag;
52 use Friendica\Network\HTTPException;
53 use Friendica\Object\EMail\ItemCCEMail;
54 use Friendica\Protocol\Activity;
55 use Friendica\Protocol\Diaspora;
56 use Friendica\Util\DateTimeFormat;
57 use Friendica\Util\Security;
58 use Friendica\Util\Strings;
59 use Friendica\Worker\Delivery;
61 function item_post(App $a) {
62 if (!Session::isAuthenticated()) {
63 throw new HTTPException\ForbiddenException();
68 if (!empty($_REQUEST['dropitems'])) {
69 $arr_drop = explode(',', $_REQUEST['dropitems']);
70 foreach ($arr_drop as $item) {
71 Item::deleteForUser(['id' => $item], $uid);
74 $json = ['success' => 1];
75 System::jsonExit($json);
78 Hook::callAll('post_local_start', $_REQUEST);
80 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
82 $api_source = $_REQUEST['api_source'] ?? false;
84 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
86 $return_path = $_REQUEST['return'] ?? '';
87 $preview = intval($_REQUEST['preview'] ?? 0);
90 * Check for doubly-submitted posts, and reject duplicates
91 * Note that we have to ignore previews, otherwise nothing will post
92 * after it's been previewed
94 if (!$preview && !empty($_REQUEST['post_id_random'])) {
95 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
96 Logger::info('item post: duplicate post');
97 item_post_return(DI::baseUrl(), $api_source, $return_path);
99 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
103 // Is this a reply to something?
104 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
105 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
107 $toplevel_item = null;
111 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
112 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
114 if ($toplevel_item_id || $thr_parent_uri) {
115 if ($toplevel_item_id) {
116 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
117 } elseif ($thr_parent_uri) {
118 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
121 // if this isn't the top-level parent of the conversation, find it
122 if (DBA::isResult($toplevel_item)) {
123 // The URI and the contact is taken from the direct parent which needn't to be the top parent
124 $thr_parent_uri = $toplevel_item['uri'];
126 if ($toplevel_item['gravity'] != GRAVITY_PARENT) {
127 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
131 if (!DBA::isResult($toplevel_item)) {
132 notice(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 $toplevel_item_id = $toplevel_item['id'];
140 $parent_user = $toplevel_item['uid'];
142 $objecttype = Activity\ObjectType::COMMENT;
145 if ($toplevel_item_id) {
146 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
149 $post_id = intval($_REQUEST['post_id'] ?? 0);
150 $app = strip_tags($_REQUEST['source'] ?? '');
151 $extid = strip_tags($_REQUEST['extid'] ?? '');
152 $object = $_REQUEST['object'] ?? '';
154 // Don't use "defaults" here. It would turn 0 to 1
155 if (!isset($_REQUEST['wall'])) {
158 $wall = $_REQUEST['wall'];
161 // Ensure that the user id in a thread always stay the same
162 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
163 $profile_uid = $parent_user;
166 // Check for multiple posts with the same message id (when the post was created via API)
167 if (($message_id != '') && ($profile_uid != 0)) {
168 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
169 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
174 // Allow commenting if it is an answer to a public post
175 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
177 // Now check that valid personal details have been provided
178 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
179 notice(DI::l10n()->t('Permission denied.'));
181 DI::baseUrl()->redirect($return_path);
184 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
187 // Init post instance
190 // is this an edited post?
192 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
195 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
197 if (!DBA::isResult($user) && !$toplevel_item_id) {
204 $body = $_REQUEST['body'] ?? '';
205 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
207 // If we have a speparate attachment, we need to add it to the body.
208 if (!empty($has_attachment)) {
209 $attachment_type = $_REQUEST['attachment_type'] ?? '';
210 $attachment_title = $_REQUEST['attachment_title'] ?? '';
211 $attachment_text = $_REQUEST['attachment_text'] ?? '';
213 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
214 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
216 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
217 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
219 'type' => $attachment_type,
220 'title' => $attachment_title,
221 'text' => $attachment_text,
222 'url' => $attachment_url,
225 if (!empty($attachment_img_src)) {
226 $attachment['images'] = [
228 'src' => $attachment_img_src,
229 'width' => $attachment_img_width,
230 'height' => $attachment_img_height
235 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
236 $body .= $att_bbcode;
239 // Convert links with empty descriptions to links without an explicit description
240 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
242 if (!empty($orig_post)) {
243 $str_group_allow = $orig_post['allow_gid'];
244 $str_contact_allow = $orig_post['allow_cid'];
245 $str_group_deny = $orig_post['deny_gid'];
246 $str_contact_deny = $orig_post['deny_cid'];
247 $location = $orig_post['location'];
248 $coord = $orig_post['coord'];
249 $verb = $orig_post['verb'];
250 $objecttype = $orig_post['object-type'];
251 $app = $orig_post['app'];
252 $categories = $orig_post['file'] ?? '';
253 $title = Strings::escapeTags(trim($_REQUEST['title']));
255 $private = $orig_post['private'];
256 $pubmail_enabled = $orig_post['pubmail'];
257 $network = $orig_post['network'];
258 $guid = $orig_post['guid'];
259 $extid = $orig_post['extid'];
261 $str_contact_allow = '';
262 $str_group_allow = '';
263 $str_contact_deny = '';
264 $str_group_deny = '';
266 if (($_REQUEST['visibility'] ?? '') !== 'public') {
267 $aclFormatter = DI::aclFormatter();
268 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
269 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
270 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
271 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
274 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
275 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
276 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
277 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
278 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
280 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
281 $guid = System::createUUID();
283 $postopts = $_REQUEST['postopts'] ?? '';
285 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
286 $private = Item::PRIVATE;
287 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
288 $private = Item::UNLISTED;
290 $private = Item::PUBLIC;
293 // If this is a comment, set the permissions from the parent.
295 if ($toplevel_item) {
296 // for non native networks use the network of the original post as network of the item
297 if (($toplevel_item['network'] != Protocol::DIASPORA)
298 && ($toplevel_item['network'] != Protocol::OSTATUS)
299 && ($network == "")) {
300 $network = $toplevel_item['network'];
303 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
304 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
305 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
306 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
307 $private = $toplevel_item['private'];
309 $wall = $toplevel_item['wall'];
312 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
314 // if using the API, we won't see pubmail_enable - figure out if it should be set
315 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
316 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
317 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
321 if (!strlen($body)) {
323 System::jsonExit(['preview' => '']);
326 info(DI::l10n()->t('Empty post discarded.'));
328 DI::baseUrl()->redirect($return_path);
331 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
335 if (!empty($categories)) {
336 // get the "fileas" tags for this post
337 $filedas = FileTag::fileToArray($categories);
340 // save old and new categories, so we can determine what needs to be deleted from pconfig
341 $categories_old = $categories;
342 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
343 $categories_new = $categories;
345 if (!empty($filedas) && is_array($filedas)) {
346 // append the fileas stuff to the new categories list
347 $categories .= FileTag::arrayToFile($filedas);
350 // get contact info for poster
356 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
358 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
359 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
360 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
363 if (DBA::isResult($author)) {
364 $contact_id = $author['id'];
367 // get contact info for owner
368 if ($profile_uid == local_user() || $allow_comment) {
369 $contact_record = $author ?: [];
371 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
374 // Look for any tags and linkify them
376 $private_forum = false;
378 $only_to_forum = false;
381 $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) {
382 $tags = BBCode::getTags($body);
386 foreach ($tags as $tag) {
387 $tag_type = substr($tag, 0, 1);
389 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
393 /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
394 * Robert Johnson should be first in the $tags array
396 foreach ($tagged as $nextTag) {
397 if (stristr($nextTag, $tag . ' ')) {
402 $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
403 if ($success['replaced']) {
406 // When the forum is private or the forum is addressed with a "!" make the post private
407 if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
408 $private_forum = $success['contact']['prv'];
409 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
410 $private_id = $success['contact']['id'];
411 $forum_contact = $success['contact'];
412 } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
413 $private_forum = false;
414 $only_to_forum = true;
415 $private_id = $success['contact']['id'];
416 $forum_contact = $success['contact'];
423 $original_contact_id = $contact_id;
425 if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
426 // we tagged a forum in a top level post. Now we change the post
427 $private = $private_forum;
429 $str_group_allow = '';
430 $str_contact_deny = '';
431 $str_group_deny = '';
432 if ($private_forum) {
433 $str_contact_allow = '<' . $private_id . '>';
435 $str_contact_allow = '';
437 $contact_id = $private_id;
438 $contact_record = $forum_contact;
439 $_REQUEST['origin'] = false;
444 * When a photo was uploaded into the message using the (profile wall) ajax
445 * uploader, The permissions are initially set to disallow anybody but the
446 * owner from seeing it. This is because the permissions may not yet have been
447 * set for the post. If it's private, the photo permissions should be set
448 * appropriately. But we didn't know the final permissions on the post until
449 * now. So now we'll look for links of uploaded messages that are in the
450 * post and set them to the same permissions as the post itself.
455 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
456 $objecttype = Activity\ObjectType::IMAGE;
460 * Next link in any attachment references we find in the post.
464 /// @todo these lines should be moved to Model/Attach (Once it exists)
465 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
466 $attaches = $match[1];
467 if (count($attaches)) {
468 foreach ($attaches as $attach) {
469 // Ensure to only modify attachments that you own
470 $srch = '<' . intval($original_contact_id) . '>';
472 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
474 if (!Attach::exists($condition)) {
478 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
479 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
480 $condition = ['id' => $attach];
481 Attach::update($fields, $condition);
486 // embedded bookmark or attachment in post? set bookmark flag
488 $data = BBCode::getAttachmentData($body);
489 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
490 && ($posttype != Item::PT_PERSONAL_NOTE)) {
491 $posttype = Item::PT_PAGE;
492 $objecttype = Activity\ObjectType::BOOKMARK;
495 $body = DI::bbCodeVideo()->transform($body);
497 $body = BBCode::scaleExternalImages($body);
499 // Setting the object type if not defined before
501 $objecttype = Activity\ObjectType::NOTE; // Default value
502 $objectdata = BBCode::getAttachedData($body);
504 if ($objectdata["type"] == "link") {
505 $objecttype = Activity\ObjectType::BOOKMARK;
506 } elseif ($objectdata["type"] == "video") {
507 $objecttype = Activity\ObjectType::VIDEO;
508 } elseif ($objectdata["type"] == "photo") {
509 $objecttype = Activity\ObjectType::IMAGE;
517 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
518 foreach ($match[2] as $mtch) {
519 $fields = ['id', 'filename', 'filesize', 'filetype'];
520 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
521 if ($attachment !== false) {
522 if (strlen($attachments)) {
525 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
526 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
527 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
529 $body = str_replace($match[1],'',$body);
533 if (!strlen($verb)) {
534 $verb = Activity::POST;
537 if ($network == "") {
538 $network = Protocol::DFRN;
541 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
543 // even if the post arrived via API we are considering that it
544 // originated on this site by default for determining relayability.
546 // Don't use "defaults" here. It would turn 0 to 1
547 if (!isset($_REQUEST['origin'])) {
550 $origin = $_REQUEST['origin'];
553 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
555 // Fallback so that we alway have a parent uri
556 if (!$thr_parent_uri || !$toplevel_item_id) {
557 $thr_parent_uri = $uri;
561 $datarray['uid'] = $profile_uid;
562 $datarray['wall'] = $wall;
563 $datarray['gravity'] = $gravity;
564 $datarray['network'] = $network;
565 $datarray['contact-id'] = $contact_id;
566 $datarray['owner-name'] = $contact_record['name'] ?? '';
567 $datarray['owner-link'] = $contact_record['url'] ?? '';
568 $datarray['owner-avatar'] = $contact_record['thumb'] ?? '';
569 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
570 $datarray['author-name'] = $author['name'];
571 $datarray['author-link'] = $author['url'];
572 $datarray['author-avatar'] = $author['thumb'];
573 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
574 $datarray['created'] = DateTimeFormat::utcNow();
575 $datarray['edited'] = DateTimeFormat::utcNow();
576 $datarray['commented'] = DateTimeFormat::utcNow();
577 $datarray['received'] = DateTimeFormat::utcNow();
578 $datarray['changed'] = DateTimeFormat::utcNow();
579 $datarray['extid'] = $extid;
580 $datarray['guid'] = $guid;
581 $datarray['uri'] = $uri;
582 $datarray['title'] = $title;
583 $datarray['body'] = $body;
584 $datarray['app'] = $app;
585 $datarray['location'] = $location;
586 $datarray['coord'] = $coord;
587 $datarray['file'] = $categories;
588 $datarray['inform'] = $inform;
589 $datarray['verb'] = $verb;
590 $datarray['post-type'] = $posttype;
591 $datarray['object-type'] = $objecttype;
592 $datarray['allow_cid'] = $str_contact_allow;
593 $datarray['allow_gid'] = $str_group_allow;
594 $datarray['deny_cid'] = $str_contact_deny;
595 $datarray['deny_gid'] = $str_group_deny;
596 $datarray['private'] = $private;
597 $datarray['pubmail'] = $pubmail_enabled;
598 $datarray['attach'] = $attachments;
600 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
601 $datarray['parent-uri'] = $thr_parent_uri;
603 $datarray['postopts'] = $postopts;
604 $datarray['origin'] = $origin;
605 $datarray['moderated'] = false;
606 $datarray['object'] = $object;
609 * These fields are for the convenience of addons...
610 * 'self' if true indicates the owner is posting on their own wall
611 * If parent is 0 it is a top-level post.
613 $datarray['parent'] = $toplevel_item_id;
614 $datarray['self'] = $self;
616 // This triggers posts via API and the mirror functions
617 $datarray['api_source'] = $api_source;
619 // This field is for storing the raw conversation data
620 $datarray['protocol'] = Conversation::PARCEL_DFRN;
622 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
623 if (DBA::isResult($conversation)) {
624 if ($conversation['conversation-uri'] != '') {
625 $datarray['conversation-uri'] = $conversation['conversation-uri'];
627 if ($conversation['conversation-href'] != '') {
628 $datarray['conversation-href'] = $conversation['conversation-href'];
633 $datarray['edit'] = true;
635 // If this was a share, add missing data here
636 $datarray = Item::addShareDataFromOriginal($datarray);
638 $datarray['edit'] = false;
641 // Check for hashtags in the body and repair or add hashtag links
642 if ($preview || $orig_post) {
643 $datarray['body'] = Item::setHashtags($datarray['body']);
646 // preview mode - prepare the body for display and send it via json
648 // We set the datarray ID to -1 because in preview mode the dataray
649 // doesn't have an ID.
650 $datarray["id"] = -1;
651 $datarray["uri-id"] = -1;
652 $datarray["item_id"] = -1;
653 $datarray["author-network"] = Protocol::DFRN;
655 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
657 System::jsonExit(['preview' => $o]);
660 Hook::callAll('post_local',$datarray);
662 if (!empty($datarray['cancel'])) {
663 Logger::info('mod_item: post cancelled by addon.');
665 DI::baseUrl()->redirect($return_path);
668 $json = ['cancel' => 1];
669 if (!empty($_REQUEST['jsreload'])) {
670 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
673 System::jsonExit($json);
677 // Fill the cache field
678 // This could be done in Item::update as well - but we have to check for the existance of some fields.
679 Item::putInCache($datarray);
682 'title' => $datarray['title'],
683 'body' => $datarray['body'],
684 'attach' => $datarray['attach'],
685 'file' => $datarray['file'],
686 'rendered-html' => $datarray['rendered-html'],
687 'rendered-hash' => $datarray['rendered-hash'],
688 'edited' => DateTimeFormat::utcNow(),
689 'changed' => DateTimeFormat::utcNow()];
691 Item::update($fields, ['id' => $post_id]);
693 // update filetags in pconfig
694 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
696 info(DI::l10n()->t('Post updated.'));
698 DI::baseUrl()->redirect($return_path);
701 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
704 unset($datarray['edit']);
705 unset($datarray['self']);
706 unset($datarray['api_source']);
709 $signed = Diaspora::createCommentSignature($uid, $datarray);
710 if (!empty($signed)) {
711 $datarray['diaspora_signed_text'] = json_encode($signed);
715 $post_id = Item::insert($datarray);
718 info(DI::l10n()->t('Item wasn\'t stored.'));
720 DI::baseUrl()->redirect($return_path);
723 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
726 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
728 if (!DBA::isResult($datarray)) {
729 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
731 DI::baseUrl()->redirect($return_path);
734 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
737 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
739 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
740 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
743 // update filetags in pconfig
744 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
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' => Type::COMMENT,
751 'notify_flags' => $user['notify-flags'],
752 'language' => $user['language'],
753 'to_name' => $user['username'],
754 'to_email' => $user['email'],
755 'uid' => $user['uid'],
757 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
758 'source_name' => $datarray['author-name'],
759 'source_link' => $datarray['author-link'],
760 'source_photo' => $datarray['author-avatar'],
761 'verb' => Activity::POST,
763 'parent' => $toplevel_item_id,
764 'parent_uri' => $toplevel_item['uri']
766 } elseif (empty($forum_contact)) {
768 'type' => Type::WALL,
769 'notify_flags' => $user['notify-flags'],
770 'language' => $user['language'],
771 'to_name' => $user['username'],
772 'to_email' => $user['email'],
773 'uid' => $user['uid'],
775 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
776 'source_name' => $datarray['author-name'],
777 'source_link' => $datarray['author-link'],
778 'source_photo' => $datarray['author-avatar'],
779 'verb' => Activity::POST,
785 Hook::callAll('post_local_end', $datarray);
787 if (strlen($emailcc) && $profile_uid == local_user()) {
788 $recipients = explode(',', $emailcc);
789 if (count($recipients)) {
790 foreach ($recipients as $recipient) {
791 $address = trim($recipient);
792 if (!strlen($address)) {
795 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
796 $datarray, $address, $author['thumb'] ?? ''));
801 // Insert an item entry for UID=0 for global entries.
802 // We now do it in the background to save some time.
803 // This is important in interactive environments like the frontend or the API.
804 // We don't fork a new process since this is done anyway with the following command
805 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
807 // When we are doing some forum posting via ! we have to start the notifier manually.
808 // These kind of posts don't initiate the notifier call in the item class.
809 if ($only_to_forum) {
810 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
813 Logger::info('post_complete');
819 info(DI::l10n()->t('Post published.'));
820 item_post_return(DI::baseUrl(), $api_source, $return_path);
824 function item_post_return($baseurl, $api_source, $return_path)
831 DI::baseUrl()->redirect($return_path);
834 $json = ['success' => 1];
835 if (!empty($_REQUEST['jsreload'])) {
836 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
839 Logger::info('post_json', ['json' => $json]);
841 System::jsonExit($json);
844 function item_content(App $a)
846 if (!Session::isAuthenticated()) {
852 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
853 if (DI::mode()->isAjax()) {
854 Item::deleteForUser(['id' => $a->argv[2]], local_user());
855 // ajax return: [<item id>, 0 (no perm) | <owner id>]
856 System::jsonExit([intval($a->argv[2]), local_user()]);
858 if (!empty($a->argv[3])) {
859 $o = drop_item($a->argv[2], $a->argv[3]);
862 $o = drop_item($a->argv[2]);
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 = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
882 if (!DBA::isResult($item)) {
883 notice(DI::l10n()->t('Item not found.') . EOL);
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) {
899 // Check if we should do HTML-based delete confirmation
900 if (!empty($_REQUEST['confirm'])) {
901 // <form> can't take arguments in its "action" parameter
902 // so add any arguments as hidden inputs
903 $query = explode_querystring(DI::args()->getQueryString());
906 foreach ($query['args'] as $arg) {
907 if (strpos($arg, 'confirm=') === false) {
908 $arg_parts = explode('=', $arg);
909 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
913 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
915 '$message' => DI::l10n()->t('Do you really want to delete this item?'),
916 '$extra_inputs' => $inputs,
917 '$confirm' => DI::l10n()->t('Yes'),
918 '$confirm_url' => $query['base'],
919 '$confirm_name' => 'confirmed',
920 '$cancel' => DI::l10n()->t('Cancel'),
923 // Now check how the user responded to the confirmation query
924 if (!empty($_REQUEST['canceled'])) {
925 DI::baseUrl()->redirect('display/' . $item['guid']);
928 $is_comment = $item['gravity'] == GRAVITY_COMMENT;
930 if (!empty($item['parent'])) {
932 $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
936 Item::deleteForUser(['id' => $item['id']], local_user());
938 $return_url = hex2bin($return);
940 // removes update_* from return_url to ignore Ajax refresh
941 $return_url = str_replace("update_", "", $return_url);
943 // Check if delete a comment
945 // Return to parent guid
946 if (!empty($parentitem)) {
947 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
949 } // In case something goes wrong
951 DI::baseUrl()->redirect('network');
955 // if unknown location or deleting top level post called from display
956 if (empty($return_url) || strpos($return_url, 'display') !== false) {
957 DI::baseUrl()->redirect('network');
960 DI::baseUrl()->redirect($return_url);
965 notice(DI::l10n()->t('Permission denied.'));
966 DI::baseUrl()->redirect('display/' . $item['guid']);