]> git.mxchange.org Git - friendica.git/blob - mod/item.php
808641132e2908da951291cd0ed7ee846e07e54b
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
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.
26  *
27  * All of these become an "item" which is our basic unit of
28  * information.
29  */
30
31 use Friendica\App;
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;
39 use Friendica\DI;
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;
50
51 function item_post(App $a) {
52         $uid = DI::userSession()->getLocalUserId();
53
54         if (!DI::userSession()->isAuthenticated() || !$uid) {
55                 throw new HTTPException\ForbiddenException();
56         }
57
58         if (!empty($_REQUEST['dropitems'])) {
59                 $arr_drop = explode(',', $_REQUEST['dropitems']);
60                 foreach ($arr_drop as $item) {
61                         Item::deleteForUser(['id' => $item], $uid);
62                 }
63
64                 $json = ['success' => 1];
65                 System::jsonExit($json);
66         }
67
68         Hook::callAll('post_local_start', $_REQUEST);
69
70         $return_path = $_REQUEST['return'] ?? '';
71         $preview     = intval($_REQUEST['preview'] ?? 0);
72
73         /*
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
77          */
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);
82                 } else {
83                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
84                 }
85         }
86
87         $post_id = intval($_REQUEST['post_id'] ?? 0);
88
89         // is this an edited post?
90         if ($post_id > 0) {
91                 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
92         } else {
93                 $orig_post = null;
94         }
95
96         $emailcc = trim($_REQUEST['emailcc']  ?? '');
97
98         $post = ['uid' => $uid];
99
100         $post = DI::contentItem()->initializePost($post);
101
102         $post['self']        = true;
103         $post['api_source']  = false;
104         $post['edit']        = $orig_post;
105         $post['file']        = '';
106         $post['attach']      = '';
107         $post['inform']      = '';
108         $post['postopts']    = '';
109
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'];
120         $post['app']         = '';
121
122         if ($post['parent']) {
123                 if ($post['parent']) {
124                         $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post['parent']]);
125                 }
126
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;
132
133                         if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
134                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
135                         }
136                 }
137
138                 if (!DBA::isResult($toplevel_item)) {
139                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
140                         if ($return_path) {
141                                 DI::baseUrl()->redirect($return_path);
142                         }
143                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
144                 }
145
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]);
151                         if ($stored) {
152                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
153                         }
154                 }
155
156                 $post['parent']      = $toplevel_item['id'];
157                 $post['gravity']     = Item::GRAVITY_COMMENT;
158                 $post['wall']        = $toplevel_item['wall'];
159         } else {
160                 $parent_item         = [];
161                 $post['parent']      = 0;
162                 $post['gravity']     = Item::GRAVITY_PARENT;
163                 $post['thr-parent']  = $post['uri'];
164         }
165
166         $post = DI::contentItem()->getACL($post, $parent_item, $_REQUEST);
167
168         $post['pubmail'] = $post['pubmail'] && !$post['private'];
169
170         if (!empty($orig_post)) {
171                 $post['uri']  = $orig_post['uri'];
172                 $post['file'] = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
173         }
174
175         $post = DI::contentItem()->addCategories($post, $_REQUEST['category'] ?? '');
176
177         if (!$preview) {
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;
180                 }
181
182                 $post = DI::contentItem()->moveAttachmentsFromBodyToAttach($post);
183         }
184
185         // Add the attachment to the body.
186         if (!empty($_REQUEST['has_attachment'])) {
187                 $post['body'] .= DI::contentItem()->storeAttachmentFromRequest($_REQUEST);
188         }
189
190         $post = DI::contentItem()->finalizePost($post);
191
192         if (!strlen($post['body'])) {
193                 if ($preview) {
194                         System::jsonExit(['preview' => '']);
195                 }
196
197                 DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
198                 if ($return_path) {
199                         DI::baseUrl()->redirect($return_path);
200                 }
201
202                 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
203         }
204
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']);
208         }
209
210         // preview mode - prepare the body for display and send it via json
211         if ($preview) {
212                 // We set the datarray ID to -1 because in preview mode the dataray
213                 // doesn't have an ID.
214                 $post['id'] = -1;
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;
225
226                 $o = DI::conversation()->create([$post], 'search', false, true);
227
228                 System::jsonExit(['preview' => $o]);
229         }
230
231         Hook::callAll('post_local',$post);
232
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']);
244
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);
247                 }
248         }
249
250         if (!empty($post['cancel'])) {
251                 Logger::info('mod_item: post cancelled by addon.');
252                 if ($return_path) {
253                         DI::baseUrl()->redirect($return_path);
254                 }
255
256                 $json = ['cancel' => 1];
257                 if (!empty($_REQUEST['jsreload'])) {
258                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
259                 }
260
261                 System::jsonExit($json);
262         }
263
264         $post['uri-id'] = ItemURI::getIdByURI($post['uri']);
265
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']);
270         }
271
272         if ($orig_post) {
273                 $fields = [
274                         'title'   => $post['title'],
275                         'body'    => $post['body'],
276                         'attach'  => $post['attach'],
277                         'file'    => $post['file'],
278                         'edited'  => DateTimeFormat::utcNow(),
279                         'changed' => DateTimeFormat::utcNow()
280                 ];
281
282                 Item::update($fields, ['id' => $post_id]);
283                 Item::updateDisplayCache($post['uri-id']);
284
285                 if ($return_path) {
286                         DI::baseUrl()->redirect($return_path);
287                 }
288
289                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
290         }
291
292         unset($post['edit']);
293         unset($post['self']);
294         unset($post['api_source']);
295
296         $post_id = Item::insert($post);
297         if (!$post_id) {
298                 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
299                 if ($return_path) {
300                         DI::baseUrl()->redirect($return_path);
301                 }
302
303                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
304         }
305
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]);
309                 if ($return_path) {
310                         DI::baseUrl()->redirect($return_path);
311                 }
312
313                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
314         }
315
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']);
318         }
319
320         Hook::callAll('post_local_end', $post);
321
322         $recipients = explode(',', $emailcc);
323         if (count($recipients)) {
324                 foreach ($recipients as $recipient) {
325                         $address = trim($recipient);
326                         if (!strlen($address)) {
327                                 continue;
328                         }
329
330                         $author = DBA::selectFirst('contact', ['thumb'], ['uid' => $uid, 'self' => true]);
331
332                         DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
333                                 $post, $address, $author['thumb'] ?? ''));
334                 }
335         }
336
337         Logger::debug('post_complete');
338
339         item_post_return(DI::baseUrl(), $return_path);
340         // NOTREACHED
341 }
342
343 function item_post_return($baseurl, $return_path)
344 {
345         if ($return_path) {
346                 DI::baseUrl()->redirect($return_path);
347         }
348
349         $json = ['success' => 1];
350         if (!empty($_REQUEST['jsreload'])) {
351                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
352         }
353
354         Logger::debug('post_json', ['json' => $json]);
355
356         System::jsonExit($json);
357 }
358
359 function item_content(App $a)
360 {
361         if (!DI::userSession()->isAuthenticated()) {
362                 throw new HTTPException\UnauthorizedException();
363         }
364
365         $args = DI::args();
366
367         if (!$args->has(3)) {
368                 throw new HTTPException\BadRequestException();
369         }
370
371         $o = '';
372         switch ($args->get(1)) {
373                 case 'drop':
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()]);
378                         } else {
379                                 if (!empty($args->get(3))) {
380                                         $o = drop_item($args->get(2), $args->get(3));
381                                 } else {
382                                         $o = drop_item($args->get(2));
383                                 }
384                         }
385                         break;
386
387                 case 'block':
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');
391                         }
392
393                         Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
394
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()]);
398                         } else {
399                                 item_redirect_after_action($item, $args->get(3));
400                         }
401                         break;
402         }
403
404         return $o;
405 }
406
407 /**
408  * @param int    $id
409  * @param string $return
410  * @return string
411  * @throws HTTPException\InternalServerErrorException
412  */
413 function drop_item(int $id, string $return = ''): string
414 {
415         // Locate item to be deleted
416         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
417
418         if (!DBA::isResult($item)) {
419                 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
420                 DI::baseUrl()->redirect('network');
421                 //NOTREACHED
422         }
423
424         if ($item['deleted']) {
425                 return '';
426         }
427
428         $contact_id = 0;
429
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'];
433         }
434
435         if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
436                 // delete the item
437                 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
438
439                 item_redirect_after_action($item, $return);
440                 //NOTREACHED
441         } else {
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']);
445                 //NOTREACHED
446         }
447
448         return '';
449 }
450
451 function item_redirect_after_action(array $item, string $returnUrlHex)
452 {
453         $return_url = hex2bin($returnUrlHex);
454
455         // removes update_* from return_url to ignore Ajax refresh
456         $return_url = str_replace('update_', '', $return_url);
457
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']]);
462                 }
463
464                 // Return to parent guid
465                 if (!empty($parentitem)) {
466                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
467                         //NOTREACHED
468                 } // In case something goes wrong
469                 else {
470                         DI::baseUrl()->redirect('network');
471                         //NOTREACHED
472                 }
473         } else {
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');
477                         //NOTREACHED
478                 } else {
479                         DI::baseUrl()->redirect($return_url);
480                         //NOTREACHED
481                 }
482         }
483 }