3 * @copyright Copyright (C) 2010-2023, 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\Text\BBCode;
33 use Friendica\Core\Hook;
34 use Friendica\Core\Logger;
35 use Friendica\Core\Protocol;
36 use Friendica\Core\System;
37 use Friendica\Core\Worker;
38 use Friendica\Database\DBA;
40 use Friendica\Model\Contact;
41 use Friendica\Model\Item;
42 use Friendica\Model\ItemURI;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\Tag;
46 use Friendica\Network\HTTPException;
47 use Friendica\Object\EMail\ItemCCEMail;
48 use Friendica\Protocol\Activity;
49 use Friendica\Util\DateTimeFormat;
51 function item_post(App $a) {
52 $uid = DI::userSession()->getLocalUserId();
54 if (!DI::userSession()->isAuthenticated() || !$uid) {
55 throw new HTTPException\ForbiddenException();
58 if (!empty($_REQUEST['dropitems'])) {
59 $arr_drop = explode(',', $_REQUEST['dropitems']);
60 foreach ($arr_drop as $item) {
61 Item::deleteForUser(['id' => $item], $uid);
64 $json = ['success' => 1];
65 System::jsonExit($json);
68 Hook::callAll('post_local_start', $_REQUEST);
70 $return_path = $_REQUEST['return'] ?? '';
71 $preview = intval($_REQUEST['preview'] ?? 0);
74 * Check for doubly-submitted posts, and reject duplicates
75 * Note that we have to ignore previews, otherwise nothing will post
76 * after it's been previewed
78 if (!$preview && !empty($_REQUEST['post_id_random'])) {
79 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
80 Logger::warning('duplicate post');
81 item_post_return(DI::baseUrl(), $return_path);
83 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
87 $post_id = intval($_REQUEST['post_id'] ?? 0);
89 // is this an edited post?
91 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
96 $emailcc = trim($_REQUEST['emailcc'] ?? '');
98 $post = ['uid' => $uid];
100 $post = DI::contentItem()->initializePost($post);
102 $post['self'] = true;
103 $post['api_source'] = false;
104 $post['edit'] = $orig_post;
106 $post['attach'] = '';
107 $post['inform'] = '';
108 $post['postopts'] = '';
110 $post['wall'] = $_REQUEST['wall'] ?? true;
111 $post['post-type'] = $_REQUEST['post_type'] ?? '';
112 $post['title'] = trim($_REQUEST['title'] ?? '');
113 $post['body'] = $_REQUEST['body'] ?? '';
114 $post['location'] = trim($_REQUEST['location'] ?? '');
115 $post['coord'] = trim($_REQUEST['coord'] ?? '');
116 $post['parent'] = intval($_REQUEST['parent'] ?? 0);
117 $post['pubmail'] = $_REQUEST['pubmail_enable'] ?? false;
118 $post['created'] = $_REQUEST['created_at'] ?? DateTimeFormat::utcNow();
119 $post['edited'] = $post['changed'] = $post['commented'] = $post['created'];
122 if ($post['parent']) {
123 if ($post['parent']) {
124 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post['parent']]);
127 // if this isn't the top-level parent of the conversation, find it
128 if (DBA::isResult($parent_item)) {
129 // The URI and the contact is taken from the direct parent which needn't to be the top parent
130 $post['thr-parent'] = $parent_item['uri'];
131 $toplevel_item = $parent_item;
133 if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
134 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
138 if (!DBA::isResult($toplevel_item)) {
139 DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
141 DI::baseUrl()->redirect($return_path);
143 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
146 // When commenting on a public post then store the post for the current user
147 // This enables interaction like starring and saving into folders
148 if ($toplevel_item['uid'] == 0) {
149 $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]);
150 Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]);
152 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
156 $post['parent'] = $toplevel_item['id'];
157 $post['gravity'] = Item::GRAVITY_COMMENT;
158 $post['wall'] = $toplevel_item['wall'];
162 $post['gravity'] = Item::GRAVITY_PARENT;
163 $post['thr-parent'] = $post['uri'];
166 $post = DI::contentItem()->getACL($post, $parent_item, $_REQUEST);
168 $post['pubmail'] = $post['pubmail'] && !$post['private'];
170 if (!empty($orig_post)) {
171 $post['uri'] = $orig_post['uri'];
172 $post['file'] = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
175 $post = DI::contentItem()->addCategories($post, $_REQUEST['category'] ?? '');
178 if (Photo::setPermissionFromBody($post['body'], $post['uid'], $post['contact-id'], $post['allow_cid'], $post['allow_gid'], $post['deny_cid'], $post['deny_gid'])) {
179 $post['object-type'] = Activity\ObjectType::IMAGE;
182 $post = DI::contentItem()->moveAttachmentsFromBodyToAttach($post);
185 // Add the attachment to the body.
186 if (!empty($_REQUEST['has_attachment'])) {
187 $post['body'] .= DI::contentItem()->storeAttachmentFromRequest($_REQUEST);
190 $post = DI::contentItem()->finalizePost($post);
192 if (!strlen($post['body'])) {
194 System::jsonExit(['preview' => '']);
197 DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
199 DI::baseUrl()->redirect($return_path);
202 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
205 // Check for hashtags in the body and repair or add hashtag links
206 if ($preview || $orig_post) {
207 $post['body'] = Item::setHashtags($post['body']);
210 // preview mode - prepare the body for display and send it via json
212 // We set the datarray ID to -1 because in preview mode the dataray
213 // doesn't have an ID.
215 $post['uri-id'] = -1;
216 $post['author-network'] = Protocol::DFRN;
217 $post['author-updated'] = '';
218 $post['author-gsid'] = 0;
219 $post['author-uri-id'] = ItemURI::getIdByURI($post['author-link']);
220 $post['owner-updated'] = '';
221 $post['has-media'] = false;
222 $post['quote-uri-id'] = Item::getQuoteUriId($post['body'], $post['uid']);
223 $post['body'] = BBCode::removeSharedData($post['body']);
224 $post['writable'] = true;
226 $o = DI::conversation()->create([$post], 'search', false, true);
228 System::jsonExit(['preview' => $o]);
231 Hook::callAll('post_local',$post);
233 if (!empty($_REQUEST['scheduled_at'])) {
234 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
235 if ($scheduled_at > DateTimeFormat::utcNow()) {
236 unset($post['created']);
237 unset($post['edited']);
238 unset($post['commented']);
239 unset($post['received']);
240 unset($post['changed']);
241 unset($post['edit']);
242 unset($post['self']);
243 unset($post['api_source']);
245 Post\Delayed::add($post['uri'], $post, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
246 item_post_return(DI::baseUrl(), $return_path);
250 if (!empty($post['cancel'])) {
251 Logger::info('mod_item: post cancelled by addon.');
253 DI::baseUrl()->redirect($return_path);
256 $json = ['cancel' => 1];
257 if (!empty($_REQUEST['jsreload'])) {
258 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
261 System::jsonExit($json);
264 $post['uri-id'] = ItemURI::getIdByURI($post['uri']);
266 $quote_uri_id = Item::getQuoteUriId($post['body'], $post['uid']);
267 if (!empty($quote_uri_id)) {
268 $post['quote-uri-id'] = $quote_uri_id;
269 $post['body'] = BBCode::removeSharedData($post['body']);
274 'title' => $post['title'],
275 'body' => $post['body'],
276 'attach' => $post['attach'],
277 'file' => $post['file'],
278 'edited' => DateTimeFormat::utcNow(),
279 'changed' => DateTimeFormat::utcNow()
282 Item::update($fields, ['id' => $post_id]);
283 Item::updateDisplayCache($post['uri-id']);
286 DI::baseUrl()->redirect($return_path);
289 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
292 unset($post['edit']);
293 unset($post['self']);
294 unset($post['api_source']);
296 $post_id = Item::insert($post);
298 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
300 DI::baseUrl()->redirect($return_path);
303 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
306 $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
307 if (!DBA::isResult($post)) {
308 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
310 DI::baseUrl()->redirect($return_path);
313 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
316 if (!\Friendica\Content\Feature::isEnabled($post['uid'], 'explicit_mentions') && ($post['gravity'] == Item::GRAVITY_COMMENT)) {
317 Tag::createImplicitMentions($post['uri-id'], $post['thr-parent-id']);
320 Hook::callAll('post_local_end', $post);
322 $recipients = explode(',', $emailcc);
323 if (count($recipients)) {
324 foreach ($recipients as $recipient) {
325 $address = trim($recipient);
326 if (!strlen($address)) {
330 $author = DBA::selectFirst('contact', ['thumb'], ['uid' => $uid, 'self' => true]);
332 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
333 $post, $address, $author['thumb'] ?? ''));
337 Logger::debug('post_complete');
339 item_post_return(DI::baseUrl(), $return_path);
343 function item_post_return($baseurl, $return_path)
346 DI::baseUrl()->redirect($return_path);
349 $json = ['success' => 1];
350 if (!empty($_REQUEST['jsreload'])) {
351 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
354 Logger::debug('post_json', ['json' => $json]);
356 System::jsonExit($json);
359 function item_content(App $a)
361 if (!DI::userSession()->isAuthenticated()) {
362 throw new HTTPException\UnauthorizedException();
367 if (!$args->has(3)) {
368 throw new HTTPException\BadRequestException();
372 switch ($args->get(1)) {
374 if (DI::mode()->isAjax()) {
375 Item::deleteForUser(['id' => $args->get(2)], DI::userSession()->getLocalUserId());
376 // ajax return: [<item id>, 0 (no perm) | <owner id>]
377 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
379 if (!empty($args->get(3))) {
380 $o = drop_item($args->get(2), $args->get(3));
382 $o = drop_item($args->get(2));
388 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
389 if (empty($item['author-id'])) {
390 throw new HTTPException\NotFoundException('Item not found');
393 Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
395 if (DI::mode()->isAjax()) {
396 // ajax return: [<item id>, 0 (no perm) | <owner id>]
397 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
399 item_redirect_after_action($item, $args->get(3));
409 * @param string $return
411 * @throws HTTPException\InternalServerErrorException
413 function drop_item(int $id, string $return = ''): string
415 // Locate item to be deleted
416 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
418 if (!DBA::isResult($item)) {
419 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
420 DI::baseUrl()->redirect('network');
424 if ($item['deleted']) {
430 // check if logged in user is either the author or owner of this item
431 if (DI::userSession()->getRemoteContactID($item['uid']) == $item['contact-id']) {
432 $contact_id = $item['contact-id'];
435 if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
437 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
439 item_redirect_after_action($item, $return);
442 Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
443 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
444 DI::baseUrl()->redirect('display/' . $item['guid']);
451 function item_redirect_after_action(array $item, string $returnUrlHex)
453 $return_url = hex2bin($returnUrlHex);
455 // removes update_* from return_url to ignore Ajax refresh
456 $return_url = str_replace('update_', '', $return_url);
458 // Check if delete a comment
459 if ($item['gravity'] == Item::GRAVITY_COMMENT) {
460 if (!empty($item['parent'])) {
461 $parentitem = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid'], ['id' => $item['parent']]);
464 // Return to parent guid
465 if (!empty($parentitem)) {
466 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
468 } // In case something goes wrong
470 DI::baseUrl()->redirect('network');
474 // if unknown location or deleting top level post called from display
475 if (empty($return_url) || strpos($return_url, 'display') !== false) {
476 DI::baseUrl()->redirect('network');
479 DI::baseUrl()->redirect($return_url);