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