]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Merge pull request #12674 from nupplaphil/bug/config_typesafe
[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\Conversation;
33 use Friendica\Content\Text\BBCode;
34 use Friendica\Core\Hook;
35 use Friendica\Core\Logger;
36 use Friendica\Core\Protocol;
37 use Friendica\Core\System;
38 use Friendica\Core\Worker;
39 use Friendica\Database\DBA;
40 use Friendica\DI;
41 use Friendica\Model\Contact;
42 use Friendica\Model\Item;
43 use Friendica\Model\ItemURI;
44 use Friendica\Model\Photo;
45 use Friendica\Model\Post;
46 use Friendica\Network\HTTPException;
47 use Friendica\Protocol\Activity;
48 use Friendica\Util\DateTimeFormat;
49
50 function item_post(App $a) {
51         $uid = DI::userSession()->getLocalUserId();
52
53         if (!$uid) {
54                 throw new HTTPException\ForbiddenException();
55         }
56
57         if (!empty($_REQUEST['dropitems'])) {
58                 item_drop($uid, $_REQUEST['dropitems']);
59         }
60
61         Hook::callAll('post_local_start', $_REQUEST);
62
63         $return_path = $_REQUEST['return'] ?? '';
64         $preview     = intval($_REQUEST['preview'] ?? 0);
65
66         /*
67          * Check for doubly-submitted posts, and reject duplicates
68          * Note that we have to ignore previews, otherwise nothing will post
69          * after it's been previewed
70          */
71         if (!$preview && !empty($_REQUEST['post_id_random'])) {
72                 if (DI::session()->get('post-random') == $_REQUEST['post_id_random']) {
73                         Logger::warning('duplicate post');
74                         item_post_return(DI::baseUrl(), $return_path);
75                 } else {
76                         DI::session()->set('post-random', $_REQUEST['post_id_random']);
77                 }
78         }
79
80         if (empty($_REQUEST['post_id'])) {
81                 item_insert($uid, $_REQUEST, $preview, $return_path);
82         } else {
83                 item_edit($uid, $_REQUEST, $preview, $return_path);
84         }
85 }
86
87 function item_drop(int $uid, string $dropitems)
88 {
89         $arr_drop = explode(',', $dropitems);
90         foreach ($arr_drop as $item) {
91                 Item::deleteForUser(['id' => $item], $uid);
92         }
93
94         System::jsonExit(['success' => 1]);
95 }
96
97 function item_edit(int $uid, array $request, bool $preview, string $return_path)
98 {
99         $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $request['post_id'], 'uid' => $uid]);
100         if (!DBA::isResult($post)) {
101                 if ($return_path) {
102                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
103                         DI::baseUrl()->redirect($return_path);
104                 }
105                 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
106         }
107
108         $post['edit'] = $post;
109         $post['file'] = Post\Category::getTextByURIId($post['uri-id'], $post['uid']);   
110
111         $post = item_process($post, $request, $preview, $return_path);
112
113         $fields = [
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()
122         ];
123
124         $fields['body'] = Item::setHashtags($fields['body']);
125
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']);
130         }
131
132         Item::update($fields, ['id' => $post['id']]);
133         Item::updateDisplayCache($post['uri-id']);
134
135         if ($return_path) {
136                 DI::baseUrl()->redirect($return_path);
137         }
138
139         throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
140 }
141
142 function item_insert(int $uid, array $request, bool $preview, string $return_path)
143 {
144         $post = ['uid' => $uid];
145         $post = DI::contentItem()->initializePost($post);
146
147         $post['edit']      = null;
148         $post['post-type'] = $request['post_type'] ?? '';
149         $post['wall']      = $request['wall'] ?? true;
150         $post['pubmail']   = $request['pubmail_enable'] ?? false;
151         $post['created']   = $request['created_at'] ?? DateTimeFormat::utcNow();
152         $post['edited']    = $post['changed'] = $post['commented'] = $post['created'];
153         $post['app']       = '';
154         $post['inform']    = '';
155         $post['postopts']  = '';
156         $post['file']      = '';
157
158         if (!empty($request['parent'])) {
159                 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $request['parent']]);
160                 if ($parent_item) {
161                         // if this isn't the top-level parent of the conversation, find it
162                         if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
163                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
164                         } else {
165                                 $toplevel_item = $parent_item;
166                         }
167                 }
168
169                 if (empty($toplevel_item)) {
170                         if ($return_path) {
171                                 DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
172                                 DI::baseUrl()->redirect($return_path);
173                         }
174                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
175                 }
176
177                 // When commenting on a public post then store the post for the current user
178                 // This enables interaction like starring and saving into folders
179                 if ($toplevel_item['uid'] == 0) {
180                         $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]);
181                         Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]);
182                 }
183
184                 $post['parent']      = $toplevel_item['id'];
185                 $post['gravity']     = Item::GRAVITY_COMMENT;
186                 $post['thr-parent']  = $parent_item['uri'];
187                 $post['wall']        = $toplevel_item['wall'];
188         } else {
189                 $parent_item         = [];
190                 $post['parent']      = 0;
191                 $post['gravity']     = Item::GRAVITY_PARENT;
192                 $post['thr-parent']  = $post['uri'];
193         }
194
195         $post = DI::contentItem()->getACL($post, $parent_item, $request);
196
197         $post['pubmail'] = $post['pubmail'] && !$post['private'];
198
199         $post = item_process($post, $request, $preview, $return_path);
200
201         $post_id = Item::insert($post);
202         if (!$post_id) {
203                 if ($return_path) {
204                         DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
205                         DI::baseUrl()->redirect($return_path);
206                 }
207
208                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
209         }
210
211         $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
212         if (!$post) {
213                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
214                 if ($return_path) {
215                         DI::baseUrl()->redirect($return_path);
216                 }
217
218                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
219         }
220
221         $recipients = explode(',', $request['emailcc'] ?? '');
222
223         DI::contentItem()->postProcessPost($post, $recipients);
224
225         Logger::debug('post_complete');
226
227         item_post_return(DI::baseUrl(), $return_path);
228         // NOTREACHED
229 }
230
231 function item_process(array $post, array $request, bool $preview, string $return_path): array
232 {
233         $post['self']       = true;
234         $post['api_source'] = false;
235         $post['attach']     = '';
236         $post['title']      = trim($request['title'] ?? '');
237         $post['body']       = $request['body'] ?? '';
238         $post['location']   = trim($request['location'] ?? '');
239         $post['coord']      = trim($request['coord'] ?? '');
240
241         $post = DI::contentItem()->addCategories($post, $request['category'] ?? '');
242
243         // Add the attachment to the body.
244         if (!empty($request['has_attachment'])) {
245                 $post['body'] .= DI::contentItem()->storeAttachmentFromRequest($request);
246         }
247
248         $post = DI::contentItem()->finalizePost($post);
249
250         if (!strlen($post['body'])) {
251                 if ($preview) {
252                         System::jsonExit(['preview' => '']);
253                 }
254
255                 if ($return_path) {
256                         DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
257                         DI::baseUrl()->redirect($return_path);
258                 }
259
260                 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
261         }
262
263         // preview mode - prepare the body for display and send it via json
264         if ($preview) {
265                 // We have to preset some fields, so that the conversation can be displayed
266                 $post['id']             = -1;
267                 $post['uri-id']         = -1;
268                 $post['author-network'] = Protocol::DFRN;
269                 $post['author-updated'] = '';
270                 $post['author-gsid']    = 0;
271                 $post['author-uri-id']  = ItemURI::getIdByURI($post['author-link']);
272                 $post['owner-updated']  = '';
273                 $post['has-media']      = false;
274                 $post['quote-uri-id']   = Item::getQuoteUriId($post['body'], $post['uid']);
275                 $post['body']           = BBCode::removeSharedData(Item::setHashtags($post['body']));
276                 $post['writable']       = true;
277
278                 $o = DI::conversation()->create([$post], Conversation::MODE_SEARCH, false, true);
279
280                 System::jsonExit(['preview' => $o]);
281         }
282
283         Hook::callAll('post_local',$post);
284
285         unset($post['edit']);
286         unset($post['self']);
287         unset($post['api_source']);
288
289         if (!empty($request['scheduled_at'])) {
290                 $scheduled_at = DateTimeFormat::convert($request['scheduled_at'], 'UTC', DI::app()->getTimeZone());
291                 if ($scheduled_at > DateTimeFormat::utcNow()) {
292                         unset($post['created']);
293                         unset($post['edited']);
294                         unset($post['commented']);
295                         unset($post['received']);
296                         unset($post['changed']);
297
298                         Post\Delayed::add($post['uri'], $post, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
299                         item_post_return(DI::baseUrl(), $return_path);
300                 }
301         }
302
303         if (!empty($post['cancel'])) {
304                 Logger::info('mod_item: post cancelled by addon.');
305                 if ($return_path) {
306                         DI::baseUrl()->redirect($return_path);
307                 }
308
309                 $json = ['cancel' => 1];
310                 if (!empty($request['jsreload'])) {
311                         $json['reload'] = DI::baseUrl() . '/' . $request['jsreload'];
312                 }
313
314                 System::jsonExit($json);
315         }
316
317         return $post;
318 }
319
320 function item_post_return($baseurl, $return_path)
321 {
322         if ($return_path) {
323                 DI::baseUrl()->redirect($return_path);
324         }
325
326         $json = ['success' => 1];
327         if (!empty($_REQUEST['jsreload'])) {
328                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
329         }
330
331         Logger::debug('post_json', ['json' => $json]);
332
333         System::jsonExit($json);
334 }
335
336 function item_content(App $a)
337 {
338         if (!DI::userSession()->isAuthenticated()) {
339                 throw new HTTPException\UnauthorizedException();
340         }
341
342         $args = DI::args();
343
344         if (!$args->has(3)) {
345                 throw new HTTPException\BadRequestException();
346         }
347
348         $o = '';
349         switch ($args->get(1)) {
350                 case 'drop':
351                         if (DI::mode()->isAjax()) {
352                                 Item::deleteForUser(['id' => $args->get(2)], DI::userSession()->getLocalUserId());
353                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
354                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
355                         } else {
356                                 if (!empty($args->get(3))) {
357                                         $o = drop_item($args->get(2), $args->get(3));
358                                 } else {
359                                         $o = drop_item($args->get(2));
360                                 }
361                         }
362                         break;
363
364                 case 'block':
365                         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
366                         if (empty($item['author-id'])) {
367                                 throw new HTTPException\NotFoundException('Item not found');
368                         }
369
370                         Contact\User::setBlocked($item['author-id'], DI::userSession()->getLocalUserId(), true);
371
372                         if (DI::mode()->isAjax()) {
373                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
374                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
375                         } else {
376                                 item_redirect_after_action($item, $args->get(3));
377                         }
378                         break;
379
380                 case 'ignore':
381                         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
382                         if (empty($item['author-id'])) {
383                                 throw new HTTPException\NotFoundException('Item not found');
384                         }
385
386                         Contact\User::setIgnored($item['author-id'], DI::userSession()->getLocalUserId(), true);
387
388                         if (DI::mode()->isAjax()) {
389                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
390                                 System::jsonExit([intval($args->get(2)), DI::userSession()->getLocalUserId()]);
391                         } else {
392                                 item_redirect_after_action($item, $args->get(3));
393                         }
394                         break;
395         }
396
397         return $o;
398 }
399
400 /**
401  * @param int    $id
402  * @param string $return
403  * @return string
404  * @throws HTTPException\InternalServerErrorException
405  */
406 function drop_item(int $id, string $return = ''): string
407 {
408         // Locate item to be deleted
409         $item = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
410
411         if (!DBA::isResult($item)) {
412                 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
413                 DI::baseUrl()->redirect('network');
414                 //NOTREACHED
415         }
416
417         if ($item['deleted']) {
418                 return '';
419         }
420
421         $contact_id = 0;
422
423         // check if logged in user is either the author or owner of this item
424         if (DI::userSession()->getRemoteContactID($item['uid']) == $item['contact-id']) {
425                 $contact_id = $item['contact-id'];
426         }
427
428         if ((DI::userSession()->getLocalUserId() == $item['uid']) || $contact_id) {
429                 // delete the item
430                 Item::deleteForUser(['id' => $item['id']], DI::userSession()->getLocalUserId());
431
432                 item_redirect_after_action($item, $return);
433                 //NOTREACHED
434         } else {
435                 Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
436                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
437                 DI::baseUrl()->redirect('display/' . $item['guid']);
438                 //NOTREACHED
439         }
440
441         return '';
442 }
443
444 function item_redirect_after_action(array $item, string $returnUrlHex)
445 {
446         $return_url = hex2bin($returnUrlHex);
447
448         // removes update_* from return_url to ignore Ajax refresh
449         $return_url = str_replace('update_', '', $return_url);
450
451         // Check if delete a comment
452         if ($item['gravity'] == Item::GRAVITY_COMMENT) {
453                 if (!empty($item['parent'])) {
454                         $parentitem = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), ['guid'], ['id' => $item['parent']]);
455                 }
456
457                 // Return to parent guid
458                 if (!empty($parentitem)) {
459                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
460                         //NOTREACHED
461                 } // In case something goes wrong
462                 else {
463                         DI::baseUrl()->redirect('network');
464                         //NOTREACHED
465                 }
466         } else {
467                 // if unknown location or deleting top level post called from display
468                 if (empty($return_url) || strpos($return_url, 'display') !== false) {
469                         DI::baseUrl()->redirect('network');
470                         //NOTREACHED
471                 } else {
472                         DI::baseUrl()->redirect($return_url);
473                         //NOTREACHED
474                 }
475         }
476 }