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\Network\HTTPException;
46 use Friendica\Protocol\Activity;
47 use Friendica\Util\DateTimeFormat;
49 function item_post(App $a) {
50 $uid = DI::userSession()->getLocalUserId();
52 if (!DI::userSession()->isAuthenticated() || !$uid) {
53 throw new HTTPException\ForbiddenException();
56 if (!empty($_REQUEST['dropitems'])) {
57 item_drop($uid, $_REQUEST['dropitems']);
60 Hook::callAll('post_local_start', $_REQUEST);
62 $return_path = $_REQUEST['return'] ?? '';
63 $preview = intval($_REQUEST['preview'] ?? 0);
66 * Check for doubly-submitted posts, and reject duplicates
67 * Note that we have to ignore previews, otherwise nothing will post
68 * after it's been previewed
70 if (!$preview && !empty($_REQUEST['post_id_random'])) {
71 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
72 Logger::warning('duplicate post');
73 item_post_return(DI::baseUrl(), $return_path);
75 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
79 if (empty($_REQUEST['post_id'])) {
80 item_insert($uid, $_REQUEST, $preview, $return_path);
82 item_edit($uid, $_REQUEST, $preview, $return_path);
86 function item_drop(int $uid, string $dropitems)
88 $arr_drop = explode(',', $dropitems);
89 foreach ($arr_drop as $item) {
90 Item::deleteForUser(['id' => $item], $uid);
93 $json = ['success' => 1];
94 System::jsonExit($json);
97 function item_edit(int $uid, array $request, bool $preview, string $return_path)
99 $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $request['post_id'], 'uid' => $uid]);
100 if (!DBA::isResult($post)) {
101 DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
103 DI::baseUrl()->redirect($return_path);
105 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
108 $post['edit'] = $post;
109 $post['file'] = Post\Category::getTextByURIId($post['uri-id'], $post['uid']);
111 $post = item_process($post, $request, $preview, $return_path);
114 'title' => $post['title'],
115 'body' => $post['body'],
116 'attach' => $post['attach'],
117 'file' => $post['file'],
118 'location' => $post['location'],
119 'coord' => $post['coord'],
120 'edited' => DateTimeFormat::utcNow(),
121 'changed' => DateTimeFormat::utcNow()
124 $fields['body'] = Item::setHashtags($fields['body']);
126 $quote_uri_id = Item::getQuoteUriId($fields['body'], $post['uid']);
127 if (!empty($quote_uri_id)) {
128 $fields['quote-uri-id'] = $quote_uri_id;
129 $fields['body'] = BBCode::removeSharedData($post['body']);
132 Item::update($fields, ['id' => $post['id']]);
133 Item::updateDisplayCache($post['uri-id']);
136 DI::baseUrl()->redirect($return_path);
139 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
142 function item_insert(int $uid, array $request, bool $preview, string $return_path)
144 $emailcc = trim($request['emailcc'] ?? '');
145 $parent_id = intval($request['parent'] ?? 0);
147 $post = ['uid' => $uid];
148 $post = DI::contentItem()->initializePost($post);
150 $post['edit'] = null;
151 $post['post-type'] = $request['post_type'] ?? '';
152 $post['wall'] = $request['wall'] ?? true;
153 $post['pubmail'] = $request['pubmail_enable'] ?? false;
154 $post['created'] = $request['created_at'] ?? DateTimeFormat::utcNow();
155 $post['edited'] = $post['changed'] = $post['commented'] = $post['created'];
157 $post['inform'] = '';
158 $post['postopts'] = '';
162 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_id]);
163 if (DBA::isResult($parent_item)) {
164 // if this isn't the top-level parent of the conversation, find it
165 if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
166 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
168 $toplevel_item = $parent_item;
172 if (empty($toplevel_item)) {
173 DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
175 DI::baseUrl()->redirect($return_path);
177 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
180 // When commenting on a public post then store the post for the current user
181 // This enables interaction like starring and saving into folders
182 if ($toplevel_item['uid'] == 0) {
183 $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]);
184 Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]);
187 $post['gravity'] = Item::GRAVITY_COMMENT;
188 $post['thr-parent'] = $parent_item['uri'];
189 $post['wall'] = $toplevel_item['wall'];
192 $post['gravity'] = Item::GRAVITY_PARENT;
193 $post['thr-parent'] = $post['uri'];
196 $post = DI::contentItem()->getACL($post, $parent_item, $request);
198 $post['pubmail'] = $post['pubmail'] && !$post['private'];
200 $post = item_process($post, $request, $preview, $return_path);
202 $post_id = Item::insert($post);
204 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
206 DI::baseUrl()->redirect($return_path);
209 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
212 $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
213 if (!DBA::isResult($post)) {
214 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
216 DI::baseUrl()->redirect($return_path);
219 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
222 $recipients = explode(',', $emailcc);
224 DI::contentItem()->postProcessPost($post, $recipients);
226 Logger::debug('post_complete');
228 item_post_return(DI::baseUrl(), $return_path);
232 function item_process(array $post, array $request, bool $preview, string $return_path): array
234 $post['self'] = true;
235 $post['api_source'] = false;
236 $post['attach'] = '';
237 $post['title'] = trim($request['title'] ?? '');
238 $post['body'] = $request['body'] ?? '';
239 $post['location'] = trim($request['location'] ?? '');
240 $post['coord'] = trim($request['coord'] ?? '');
242 $post = DI::contentItem()->addCategories($post, $request['category'] ?? '');
245 if (Photo::setPermissionFromBody($post['body'], $post['uid'], $post['contact-id'], $post['allow_cid'], $post['allow_gid'], $post['deny_cid'], $post['deny_gid'])) {
246 $post['object-type'] = Activity\ObjectType::IMAGE;
249 $post = DI::contentItem()->moveAttachmentsFromBodyToAttach($post);
252 // Add the attachment to the body.
253 if (!empty($request['has_attachment'])) {
254 $post['body'] .= DI::contentItem()->storeAttachmentFromRequest($request);
257 $post = DI::contentItem()->finalizePost($post);
259 if (!strlen($post['body'])) {
261 System::jsonExit(['preview' => '']);
264 DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
266 DI::baseUrl()->redirect($return_path);
269 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
272 // preview mode - prepare the body for display and send it via json
274 // We have to preset some fields, so that the conversation can be displayed
276 $post['uri-id'] = -1;
277 $post['author-network'] = Protocol::DFRN;
278 $post['author-updated'] = '';
279 $post['author-gsid'] = 0;
280 $post['author-uri-id'] = ItemURI::getIdByURI($post['author-link']);
281 $post['owner-updated'] = '';
282 $post['has-media'] = false;
283 $post['quote-uri-id'] = Item::getQuoteUriId($post['body'], $post['uid']);
284 $post['body'] = BBCode::removeSharedData(Item::setHashtags($post['body']));
285 $post['writable'] = true;
287 $o = DI::conversation()->create([$post], 'search', false, true);
289 System::jsonExit(['preview' => $o]);
292 Hook::callAll('post_local',$post);
294 unset($post['edit']);
295 unset($post['self']);
296 unset($post['api_source']);
298 if (!empty($request['scheduled_at'])) {
299 $scheduled_at = DateTimeFormat::convert($request['scheduled_at'], 'UTC', DI::app()->getTimeZone());
300 if ($scheduled_at > DateTimeFormat::utcNow()) {
301 unset($post['created']);
302 unset($post['edited']);
303 unset($post['commented']);
304 unset($post['received']);
305 unset($post['changed']);
307 Post\Delayed::add($post['uri'], $post, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
308 item_post_return(DI::baseUrl(), $return_path);
312 if (!empty($post['cancel'])) {
313 Logger::info('mod_item: post cancelled by addon.');
315 DI::baseUrl()->redirect($return_path);
318 $json = ['cancel' => 1];
319 if (!empty($request['jsreload'])) {
320 $json['reload'] = DI::baseUrl() . '/' . $request['jsreload'];
323 System::jsonExit($json);
329 function item_post_return($baseurl, $return_path)
332 DI::baseUrl()->redirect($return_path);
335 $json = ['success' => 1];
336 if (!empty($_REQUEST['jsreload'])) {
337 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
340 Logger::debug('post_json', ['json' => $json]);
342 System::jsonExit($json);
345 function item_content(App $a)
347 if (!DI::userSession()->isAuthenticated()) {
348 throw new HTTPException\UnauthorizedException();
353 if (!$args->has(3)) {
354 throw new HTTPException\BadRequestException();
358 switch ($args->get(1)) {
360 if (DI::mode()->isAjax()) {
361 Item::deleteForUser(['id' => $args->get(2)], DI::userSession()->getLocalUserId());
362 // ajax return: [<item id>, 0 (no perm) | <owner id>]
363 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
365 if (!empty($args->get(3))) {
366 $o = drop_item($args->get(2), $args->get(3));
368 $o = drop_item($args->get(2));
374 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
375 if (empty($item['author-id'])) {
376 throw new HTTPException\NotFoundException('Item not found');
379 Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
381 if (DI::mode()->isAjax()) {
382 // ajax return: [<item id>, 0 (no perm) | <owner id>]
383 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
385 item_redirect_after_action($item, $args->get(3));
395 * @param string $return
397 * @throws HTTPException\InternalServerErrorException
399 function drop_item(int $id, string $return = ''): string
401 // Locate item to be deleted
402 $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
404 if (!DBA::isResult($item)) {
405 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
406 DI::baseUrl()->redirect('network');
410 if ($item['deleted']) {
416 // check if logged in user is either the author or owner of this item
417 if (DI::userSession()->getRemoteContactID($item['uid']) == $item['contact-id']) {
418 $contact_id = $item['contact-id'];
421 if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
423 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
425 item_redirect_after_action($item, $return);
428 Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
429 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
430 DI::baseUrl()->redirect('display/' . $item['guid']);
437 function item_redirect_after_action(array $item, string $returnUrlHex)
439 $return_url = hex2bin($returnUrlHex);
441 // removes update_* from return_url to ignore Ajax refresh
442 $return_url = str_replace('update_', '', $return_url);
444 // Check if delete a comment
445 if ($item['gravity'] == Item::GRAVITY_COMMENT) {
446 if (!empty($item['parent'])) {
447 $parentitem = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid'], ['id' => $item['parent']]);
450 // Return to parent guid
451 if (!empty($parentitem)) {
452 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
454 } // In case something goes wrong
456 DI::baseUrl()->redirect('network');
460 // if unknown location or deleting top level post called from display
461 if (empty($return_url) || strpos($return_url, 'display') !== false) {
462 DI::baseUrl()->redirect('network');
465 DI::baseUrl()->redirect($return_url);