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 require_once __DIR__ . '/../include/items.php';
63 function item_post(App $a) {
64 if (!Session::isAuthenticated()) {
65 throw new HTTPException\ForbiddenException();
70 if (!empty($_REQUEST['dropitems'])) {
71 $arr_drop = explode(',', $_REQUEST['dropitems']);
72 foreach ($arr_drop as $item) {
73 Item::deleteForUser(['id' => $item], $uid);
76 $json = ['success' => 1];
77 System::jsonExit($json);
80 Hook::callAll('post_local_start', $_REQUEST);
82 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
84 $api_source = $_REQUEST['api_source'] ?? false;
86 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
88 $return_path = $_REQUEST['return'] ?? '';
89 $preview = intval($_REQUEST['preview'] ?? 0);
92 * Check for doubly-submitted posts, and reject duplicates
93 * Note that we have to ignore previews, otherwise nothing will post
94 * after it's been previewed
96 if (!$preview && !empty($_REQUEST['post_id_random'])) {
97 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
98 Logger::info('item post: duplicate post');
99 item_post_return(DI::baseUrl(), $api_source, $return_path);
101 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
105 // Is this a reply to something?
106 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
107 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
109 $toplevel_item = null;
113 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
114 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
116 if ($toplevel_item_id || $thr_parent_uri) {
117 if ($toplevel_item_id) {
118 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
119 } elseif ($thr_parent_uri) {
120 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
123 // if this isn't the top-level parent of the conversation, find it
124 if (DBA::isResult($toplevel_item)) {
125 // The URI and the contact is taken from the direct parent which needn't to be the top parent
126 $thr_parent_uri = $toplevel_item['uri'];
128 if ($toplevel_item['gravity'] != GRAVITY_PARENT) {
129 $toplevel_item = Item::selectFirst([], ['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 $toplevel_item_id = $toplevel_item['id'];
142 $parent_user = $toplevel_item['uid'];
144 $objecttype = Activity\ObjectType::COMMENT;
147 if ($toplevel_item_id) {
148 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
151 $post_id = intval($_REQUEST['post_id'] ?? 0);
152 $app = strip_tags($_REQUEST['source'] ?? '');
153 $extid = strip_tags($_REQUEST['extid'] ?? '');
154 $object = $_REQUEST['object'] ?? '';
156 // Don't use "defaults" here. It would turn 0 to 1
157 if (!isset($_REQUEST['wall'])) {
160 $wall = $_REQUEST['wall'];
163 // Ensure that the user id in a thread always stay the same
164 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
165 $profile_uid = $parent_user;
168 // Check for multiple posts with the same message id (when the post was created via API)
169 if (($message_id != '') && ($profile_uid != 0)) {
170 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
171 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
176 // Allow commenting if it is an answer to a public post
177 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && 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 notice(DI::l10n()->t('Permission denied.'));
183 DI::baseUrl()->redirect($return_path);
186 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
189 // Init post instance
192 // is this an edited post?
194 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
197 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
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 'type' => $attachment_type,
222 'title' => $attachment_title,
223 'text' => $attachment_text,
224 'url' => $attachment_url,
227 if (!empty($attachment_img_src)) {
228 $attachment['images'] = [
230 'src' => $attachment_img_src,
231 'width' => $attachment_img_width,
232 'height' => $attachment_img_height
237 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
238 $body .= $att_bbcode;
241 // Convert links with empty descriptions to links without an explicit description
242 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
244 if (!empty($orig_post)) {
245 $str_group_allow = $orig_post['allow_gid'];
246 $str_contact_allow = $orig_post['allow_cid'];
247 $str_group_deny = $orig_post['deny_gid'];
248 $str_contact_deny = $orig_post['deny_cid'];
249 $location = $orig_post['location'];
250 $coord = $orig_post['coord'];
251 $verb = $orig_post['verb'];
252 $objecttype = $orig_post['object-type'];
253 $app = $orig_post['app'];
254 $categories = $orig_post['file'] ?? '';
255 $title = Strings::escapeTags(trim($_REQUEST['title']));
257 $private = $orig_post['private'];
258 $pubmail_enabled = $orig_post['pubmail'];
259 $network = $orig_post['network'];
260 $guid = $orig_post['guid'];
261 $extid = $orig_post['extid'];
263 $str_contact_allow = '';
264 $str_group_allow = '';
265 $str_contact_deny = '';
266 $str_group_deny = '';
268 if (($_REQUEST['visibility'] ?? '') !== 'public') {
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'] ?? '';
276 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
277 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
278 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
279 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
280 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
282 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
283 $guid = System::createUUID();
285 $postopts = $_REQUEST['postopts'] ?? '';
287 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
288 $private = Item::PRIVATE;
289 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
290 $private = Item::UNLISTED;
292 $private = Item::PUBLIC;
295 // If this is a comment, set the permissions from the parent.
297 if ($toplevel_item) {
298 // for non native networks use the network of the original post as network of the item
299 if (($toplevel_item['network'] != Protocol::DIASPORA)
300 && ($toplevel_item['network'] != Protocol::OSTATUS)
301 && ($network == "")) {
302 $network = $toplevel_item['network'];
305 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
306 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
307 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
308 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
309 $private = $toplevel_item['private'];
311 $wall = $toplevel_item['wall'];
314 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
316 // if using the API, we won't see pubmail_enable - figure out if it should be set
317 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
318 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
319 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
323 if (!strlen($body)) {
325 System::jsonExit(['preview' => '']);
328 info(DI::l10n()->t('Empty post discarded.'));
330 DI::baseUrl()->redirect($return_path);
333 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
337 if (!empty($categories)) {
338 // get the "fileas" tags for this post
339 $filedas = FileTag::fileToArray($categories);
342 // save old and new categories, so we can determine what needs to be deleted from pconfig
343 $categories_old = $categories;
344 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
345 $categories_new = $categories;
347 if (!empty($filedas) && is_array($filedas)) {
348 // append the fileas stuff to the new categories list
349 $categories .= FileTag::arrayToFile($filedas);
352 // get contact info for poster
358 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
360 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
361 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
362 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
365 if (DBA::isResult($author)) {
366 $contact_id = $author['id'];
369 // get contact info for owner
370 if ($profile_uid == local_user() || $allow_comment) {
371 $contact_record = $author ?: [];
373 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
376 // Look for any tags and linkify them
378 $private_forum = false;
380 $only_to_forum = false;
383 $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) {
384 $tags = BBCode::getTags($body);
388 foreach ($tags as $tag) {
389 $tag_type = substr($tag, 0, 1);
391 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
395 /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
396 * Robert Johnson should be first in the $tags array
398 foreach ($tagged as $nextTag) {
399 if (stristr($nextTag, $tag . ' ')) {
404 $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
405 if ($success['replaced']) {
408 // When the forum is private or the forum is addressed with a "!" make the post private
409 if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
410 $private_forum = $success['contact']['prv'];
411 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
412 $private_id = $success['contact']['id'];
413 $forum_contact = $success['contact'];
414 } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
415 $private_forum = false;
416 $only_to_forum = true;
417 $private_id = $success['contact']['id'];
418 $forum_contact = $success['contact'];
425 $original_contact_id = $contact_id;
427 if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
428 // we tagged a forum in a top level post. Now we change the post
429 $private = $private_forum;
431 $str_group_allow = '';
432 $str_contact_deny = '';
433 $str_group_deny = '';
434 if ($private_forum) {
435 $str_contact_allow = '<' . $private_id . '>';
437 $str_contact_allow = '';
439 $contact_id = $private_id;
440 $contact_record = $forum_contact;
441 $_REQUEST['origin'] = false;
446 * When a photo was uploaded into the message using the (profile wall) ajax
447 * uploader, The permissions are initially set to disallow anybody but the
448 * owner from seeing it. This is because the permissions may not yet have been
449 * set for the post. If it's private, the photo permissions should be set
450 * appropriately. But we didn't know the final permissions on the post until
451 * now. So now we'll look for links of uploaded messages that are in the
452 * post and set them to the same permissions as the post itself.
457 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
458 $objecttype = Activity\ObjectType::IMAGE;
462 * Next link in any attachment references we find in the post.
466 /// @todo these lines should be moved to Model/Attach (Once it exists)
467 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
468 $attaches = $match[1];
469 if (count($attaches)) {
470 foreach ($attaches as $attach) {
471 // Ensure to only modify attachments that you own
472 $srch = '<' . intval($original_contact_id) . '>';
474 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
476 if (!Attach::exists($condition)) {
480 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
481 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
482 $condition = ['id' => $attach];
483 Attach::update($fields, $condition);
488 // embedded bookmark or attachment in post? set bookmark flag
490 $data = BBCode::getAttachmentData($body);
491 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
492 && ($posttype != Item::PT_PERSONAL_NOTE)) {
493 $posttype = Item::PT_PAGE;
494 $objecttype = Activity\ObjectType::BOOKMARK;
497 $body = DI::bbCodeVideo()->transform($body);
499 $body = BBCode::scaleExternalImages($body);
501 // Setting the object type if not defined before
503 $objecttype = Activity\ObjectType::NOTE; // Default value
504 $objectdata = BBCode::getAttachedData($body);
506 if ($objectdata["type"] == "link") {
507 $objecttype = Activity\ObjectType::BOOKMARK;
508 } elseif ($objectdata["type"] == "video") {
509 $objecttype = Activity\ObjectType::VIDEO;
510 } elseif ($objectdata["type"] == "photo") {
511 $objecttype = Activity\ObjectType::IMAGE;
519 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
520 foreach ($match[2] as $mtch) {
521 $fields = ['id', 'filename', 'filesize', 'filetype'];
522 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
523 if ($attachment !== false) {
524 if (strlen($attachments)) {
527 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
528 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
529 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
531 $body = str_replace($match[1],'',$body);
535 if (!strlen($verb)) {
536 $verb = Activity::POST;
539 if ($network == "") {
540 $network = Protocol::DFRN;
543 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
545 // even if the post arrived via API we are considering that it
546 // originated on this site by default for determining relayability.
548 // Don't use "defaults" here. It would turn 0 to 1
549 if (!isset($_REQUEST['origin'])) {
552 $origin = $_REQUEST['origin'];
555 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
557 // Fallback so that we alway have a parent uri
558 if (!$thr_parent_uri || !$toplevel_item_id) {
559 $thr_parent_uri = $uri;
563 $datarray['uid'] = $profile_uid;
564 $datarray['wall'] = $wall;
565 $datarray['gravity'] = $gravity;
566 $datarray['network'] = $network;
567 $datarray['contact-id'] = $contact_id;
568 $datarray['owner-name'] = $contact_record['name'] ?? '';
569 $datarray['owner-link'] = $contact_record['url'] ?? '';
570 $datarray['owner-avatar'] = $contact_record['thumb'] ?? '';
571 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
572 $datarray['author-name'] = $author['name'];
573 $datarray['author-link'] = $author['url'];
574 $datarray['author-avatar'] = $author['thumb'];
575 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
576 $datarray['created'] = DateTimeFormat::utcNow();
577 $datarray['edited'] = DateTimeFormat::utcNow();
578 $datarray['commented'] = DateTimeFormat::utcNow();
579 $datarray['received'] = DateTimeFormat::utcNow();
580 $datarray['changed'] = DateTimeFormat::utcNow();
581 $datarray['extid'] = $extid;
582 $datarray['guid'] = $guid;
583 $datarray['uri'] = $uri;
584 $datarray['title'] = $title;
585 $datarray['body'] = $body;
586 $datarray['app'] = $app;
587 $datarray['location'] = $location;
588 $datarray['coord'] = $coord;
589 $datarray['file'] = $categories;
590 $datarray['inform'] = $inform;
591 $datarray['verb'] = $verb;
592 $datarray['post-type'] = $posttype;
593 $datarray['object-type'] = $objecttype;
594 $datarray['allow_cid'] = $str_contact_allow;
595 $datarray['allow_gid'] = $str_group_allow;
596 $datarray['deny_cid'] = $str_contact_deny;
597 $datarray['deny_gid'] = $str_group_deny;
598 $datarray['private'] = $private;
599 $datarray['pubmail'] = $pubmail_enabled;
600 $datarray['attach'] = $attachments;
602 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
603 $datarray['parent-uri'] = $thr_parent_uri;
605 $datarray['postopts'] = $postopts;
606 $datarray['origin'] = $origin;
607 $datarray['moderated'] = false;
608 $datarray['object'] = $object;
611 * These fields are for the convenience of addons...
612 * 'self' if true indicates the owner is posting on their own wall
613 * If parent is 0 it is a top-level post.
615 $datarray['parent'] = $toplevel_item_id;
616 $datarray['self'] = $self;
618 // This triggers posts via API and the mirror functions
619 $datarray['api_source'] = $api_source;
621 // This field is for storing the raw conversation data
622 $datarray['protocol'] = Conversation::PARCEL_DFRN;
624 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
625 if (DBA::isResult($conversation)) {
626 if ($conversation['conversation-uri'] != '') {
627 $datarray['conversation-uri'] = $conversation['conversation-uri'];
629 if ($conversation['conversation-href'] != '') {
630 $datarray['conversation-href'] = $conversation['conversation-href'];
635 $datarray['edit'] = true;
637 // If this was a share, add missing data here
638 $datarray = Item::addShareDataFromOriginal($datarray);
640 $datarray['edit'] = false;
643 // Check for hashtags in the body and repair or add hashtag links
644 if ($preview || $orig_post) {
645 $datarray['body'] = Item::setHashtags($datarray['body']);
648 // preview mode - prepare the body for display and send it via json
650 // We set the datarray ID to -1 because in preview mode the dataray
651 // doesn't have an ID.
652 $datarray["id"] = -1;
653 $datarray["uri-id"] = -1;
654 $datarray["item_id"] = -1;
655 $datarray["author-network"] = Protocol::DFRN;
657 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
659 System::jsonExit(['preview' => $o]);
662 Hook::callAll('post_local',$datarray);
664 if (!empty($datarray['cancel'])) {
665 Logger::info('mod_item: post cancelled by addon.');
667 DI::baseUrl()->redirect($return_path);
670 $json = ['cancel' => 1];
671 if (!empty($_REQUEST['jsreload'])) {
672 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
675 System::jsonExit($json);
679 // Fill the cache field
680 // This could be done in Item::update as well - but we have to check for the existance of some fields.
681 Item::putInCache($datarray);
684 'title' => $datarray['title'],
685 'body' => $datarray['body'],
686 'attach' => $datarray['attach'],
687 'file' => $datarray['file'],
688 'rendered-html' => $datarray['rendered-html'],
689 'rendered-hash' => $datarray['rendered-hash'],
690 'edited' => DateTimeFormat::utcNow(),
691 'changed' => DateTimeFormat::utcNow()];
693 Item::update($fields, ['id' => $post_id]);
695 // update filetags in pconfig
696 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
698 info(DI::l10n()->t('Post updated.'));
700 DI::baseUrl()->redirect($return_path);
703 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
706 unset($datarray['edit']);
707 unset($datarray['self']);
708 unset($datarray['api_source']);
711 $signed = Diaspora::createCommentSignature($uid, $datarray);
712 if (!empty($signed)) {
713 $datarray['diaspora_signed_text'] = json_encode($signed);
717 $post_id = Item::insert($datarray);
720 info(DI::l10n()->t('Item wasn\'t stored.'));
722 DI::baseUrl()->redirect($return_path);
725 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
728 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
730 if (!DBA::isResult($datarray)) {
731 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
733 DI::baseUrl()->redirect($return_path);
736 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
739 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
741 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
742 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
745 // update filetags in pconfig
746 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
748 // These notifications are sent if someone else is commenting other your wall
749 if ($contact_record != $author) {
750 if ($toplevel_item_id) {
752 'type' => Type::COMMENT,
753 'notify_flags' => $user['notify-flags'],
754 'language' => $user['language'],
755 'to_name' => $user['username'],
756 'to_email' => $user['email'],
757 'uid' => $user['uid'],
759 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
760 'source_name' => $datarray['author-name'],
761 'source_link' => $datarray['author-link'],
762 'source_photo' => $datarray['author-avatar'],
763 'verb' => Activity::POST,
765 'parent' => $toplevel_item_id,
766 'parent_uri' => $toplevel_item['uri']
768 } elseif (empty($forum_contact)) {
770 'type' => Type::WALL,
771 'notify_flags' => $user['notify-flags'],
772 'language' => $user['language'],
773 'to_name' => $user['username'],
774 'to_email' => $user['email'],
775 'uid' => $user['uid'],
777 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
778 'source_name' => $datarray['author-name'],
779 'source_link' => $datarray['author-link'],
780 'source_photo' => $datarray['author-avatar'],
781 'verb' => Activity::POST,
787 Hook::callAll('post_local_end', $datarray);
789 if (strlen($emailcc) && $profile_uid == local_user()) {
790 $recipients = explode(',', $emailcc);
791 if (count($recipients)) {
792 foreach ($recipients as $recipient) {
793 $address = trim($recipient);
794 if (!strlen($address)) {
797 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
798 $datarray, $address, $author['thumb'] ?? ''));
803 // Insert an item entry for UID=0 for global entries.
804 // We now do it in the background to save some time.
805 // This is important in interactive environments like the frontend or the API.
806 // We don't fork a new process since this is done anyway with the following command
807 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
809 // When we are doing some forum posting via ! we have to start the notifier manually.
810 // These kind of posts don't initiate the notifier call in the item class.
811 if ($only_to_forum) {
812 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
815 Logger::info('post_complete');
821 info(DI::l10n()->t('Post published.'));
822 item_post_return(DI::baseUrl(), $api_source, $return_path);
826 function item_post_return($baseurl, $api_source, $return_path)
833 DI::baseUrl()->redirect($return_path);
836 $json = ['success' => 1];
837 if (!empty($_REQUEST['jsreload'])) {
838 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
841 Logger::info('post_json', ['json' => $json]);
843 System::jsonExit($json);
846 function item_content(App $a)
848 if (!Session::isAuthenticated()) {
854 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
855 if (DI::mode()->isAjax()) {
856 Item::deleteForUser(['id' => $a->argv[2]], local_user());
857 // ajax return: [<item id>, 0 (no perm) | <owner id>]
858 System::jsonExit([intval($a->argv[2]), local_user()]);
860 if (!empty($a->argv[3])) {
861 $o = drop_item($a->argv[2], $a->argv[3]);
864 $o = drop_item($a->argv[2]);
874 * @param string $return
876 * @throws HTTPException\InternalServerErrorException
878 function drop_item(int $id, string $return = '')
880 // locate item to be deleted
881 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
882 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
884 if (!DBA::isResult($item)) {
885 notice(DI::l10n()->t('Item not found.') . EOL);
886 DI::baseUrl()->redirect('network');
889 if ($item['deleted']) {
895 // check if logged in user is either the author or owner of this item
896 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
897 $contact_id = $item['contact-id'];
900 if ((local_user() == $item['uid']) || $contact_id) {
901 // Check if we should do HTML-based delete confirmation
902 if (!empty($_REQUEST['confirm'])) {
903 // <form> can't take arguments in its "action" parameter
904 // so add any arguments as hidden inputs
905 $query = explode_querystring(DI::args()->getQueryString());
908 foreach ($query['args'] as $arg) {
909 if (strpos($arg, 'confirm=') === false) {
910 $arg_parts = explode('=', $arg);
911 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
915 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
917 '$message' => DI::l10n()->t('Do you really want to delete this item?'),
918 '$extra_inputs' => $inputs,
919 '$confirm' => DI::l10n()->t('Yes'),
920 '$confirm_url' => $query['base'],
921 '$confirm_name' => 'confirmed',
922 '$cancel' => DI::l10n()->t('Cancel'),
925 // Now check how the user responded to the confirmation query
926 if (!empty($_REQUEST['canceled'])) {
927 DI::baseUrl()->redirect('display/' . $item['guid']);
930 $is_comment = $item['gravity'] == GRAVITY_COMMENT;
932 if (!empty($item['parent'])) {
934 $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
938 Item::deleteForUser(['id' => $item['id']], local_user());
940 $return_url = hex2bin($return);
942 // removes update_* from return_url to ignore Ajax refresh
943 $return_url = str_replace("update_", "", $return_url);
945 // Check if delete a comment
947 // Return to parent guid
948 if (!empty($parentitem)) {
949 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
951 } // In case something goes wrong
953 DI::baseUrl()->redirect('network');
957 // if unknown location or deleting top level post called from display
958 if (empty($return_url) || strpos($return_url, 'display') !== false) {
959 DI::baseUrl()->redirect('network');
962 DI::baseUrl()->redirect($return_url);
967 notice(DI::l10n()->t('Permission denied.'));
968 DI::baseUrl()->redirect('display/' . $item['guid']);