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