]> git.mxchange.org Git - friendica.git/blob - src/Module/Item/Display.php
Merge remote-tracking branch 'upstream/develop' into lemmy
[friendica.git] / src / Module / Item / Display.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  */
21
22 namespace Friendica\Module\Item;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Content\Conversation;
27 use Friendica\Content\Item as ContentItem;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Core\Config\Capability\IManageConfigValues;
30 use Friendica\Core\L10n;
31 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
32 use Friendica\Core\Renderer;
33 use Friendica\Core\Session\Capability\IHandleUserSessions;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\Profile;
38 use Friendica\Model\User;
39 use Friendica\Module\Response;
40 use Friendica\Module\Special\DisplayNotFound;
41 use Friendica\Navigation\Notifications\Repository\Notification;
42 use Friendica\Navigation\Notifications\Repository\Notify;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\Network;
45 use Friendica\Util\Profiler;
46 use Friendica\Network\HTTPException;
47 use Friendica\Content\Widget;
48 use Psr\Log\LoggerInterface;
49
50 /**
51  * Controller to display one item and its conversation
52  */
53 class Display extends BaseModule
54 {
55         /** @var App\Page */
56         protected $page;
57         /** @var IManageConfigValues */
58         protected $config;
59         /** @var IManagePersonalConfigValues */
60         protected $pConfig;
61         /** @var IHandleUserSessions */
62         protected $session;
63         /** @var App */
64         protected $app;
65         /** @var ContentItem */
66         protected $contentItem;
67         /** @var Conversation */
68         protected $conversation;
69         /** @var Notification */
70         protected $notification;
71         /** @var Notify */
72         protected $notify;
73
74         public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, IHandleUserSessions $session, App $app, App\Page $page, ContentItem $contentItem, Conversation $conversation, Notification $notification, Notify $notify, array $server, array $parameters = [])
75         {
76                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
77
78                 $this->page         = $page;
79                 $this->config       = $config;
80                 $this->pConfig      = $pConfig;
81                 $this->session      = $session;
82                 $this->app          = $app;
83                 $this->contentItem  = $contentItem;
84                 $this->conversation = $conversation;
85                 $this->notification = $notification;
86                 $this->notify       = $notify;
87         }
88
89         protected function content(array $request = []): string
90         {
91                 if (ActivityPub::isRequest()) {
92                         $this->baseUrl->redirect(str_replace('display/', 'objects/', $this->args->getQueryString()));
93                 }
94
95                 if ($this->config->get('system', 'block_public') && !$this->session->isAuthenticated()) {
96                         throw new HTTPException\UnauthorizedException($this->t('Access denied.'));
97                 }
98
99                 $guid = $this->parameters['guid'] ?? 0;
100
101                 $item    = null;
102                 $itemUid = $this->session->getLocalUserId();
103
104                 $fields = ['uri-id', 'parent-uri-id', 'author-id', 'author-link', 'body', 'uid', 'guid', 'gravity'];
105
106                 // Does the local user have this item?
107                 if ($this->session->getLocalUserId()) {
108                         $item = Post::selectFirstForUser($this->session->getLocalUserId(), $fields, [
109                                 'guid' => $guid,
110                                 'uid'  => $this->session->getLocalUserId()
111                         ]);
112                 }
113
114                 // Is this item private but could be visible to the remove visitor?
115                 if (empty($item) && $this->session->getRemoteUserId()) {
116                         $item = Post::selectFirst($fields, ['guid' => $guid, 'private' => Item::PRIVATE, 'origin' => true]);
117                         if (!empty($item)) {
118                                 if (!Contact::isFollower($this->session->getRemoteUserId(), $item['uid'])) {
119                                         $item = null;
120                                 } else {
121                                         $itemUid = $item['uid'];
122                                 }
123                         }
124                 }
125
126                 // Is it an item with uid = 0?
127                 if (empty($item)) {
128                         $item = Post::selectFirstForUser($this->session->getLocalUserId(), $fields, [
129                                 'guid'    => $guid,
130                                 'private' => [Item::PUBLIC, Item::UNLISTED],
131                                 'uid'     => 0
132                         ]);
133                 }
134
135                 if (empty($item)) {
136                         throw new HTTPException\NotFoundException($this->t('The requested item doesn\'t exist or has been deleted.'));
137                 }
138
139                 if ($item['gravity'] != Item::GRAVITY_PARENT) {
140                         $parent = Post::selectFirst($fields, [
141                                 'uid'    => [0, $itemUid],
142                                 'uri-id' => $item['parent-uri-id']
143                         ], ['order' => ['uid' => true]]);
144
145                         $item = $parent ?: $item;
146                 }
147
148                 if (!$this->pConfig->get($this->session->getLocalUserId(), 'system', 'detailed_notif')) {
149                         $this->notification->setAllSeenForUser($this->session->getLocalUserId(), ['parent-uri-id' => $item['parent-uri-id']]);
150                         $this->notify->setAllSeenForUser($this->session->getLocalUserId(), ['parent-uri-id' => $item['parent-uri-id']]);
151                 }
152
153                 $this->displaySidebar($item);
154                 $this->displayHead($item['uri-id'], $item['parent-uri-id']);
155
156                 $output = '';
157
158                 // add the uri-id to the update_display parameter
159                 if ($this->session->getLocalUserId()) {
160                         $output .= "<script> var netargs = '?uri_id=" . $item['uri-id'] . "'; </script>";
161                 }
162
163                 $output .= $this->getDisplayData($item);
164
165                 return $output;
166         }
167
168         /**
169          * Loads the content for the sidebar of the display page
170          *
171          * @param array $item The current item
172          *
173          * @return void
174          * @throws HTTPException\InternalServerErrorException
175          * @throws HTTPException\NotFoundException
176          * @throws \ImagickException
177          */
178         protected function displaySidebar(array $item)
179         {
180                 $shared = $this->contentItem->getSharedPost($item, ['author-link']);
181                 if (!empty($shared) && empty($shared['comment'])) {
182                         $author = Contact::getByURLForUser($shared['post']['author-link'], $this->session->getLocalUserId());
183                 }
184
185                 if (empty($contact)) {
186                         $author = Contact::getById($item['author-id']);
187                 }
188
189                 if (Network::isLocalLink($author['url'])) {
190                         Profile::load($this->app, $author['nick'], false);
191                 } else {
192                         $this->page['aside'] = Widget\VCard::getHTML($author);
193                 }
194
195                 $this->app->setProfileOwner($item['uid']);
196         }
197
198         protected function getDisplayData(array $item, bool $update = false, int $updateUid = 0, bool $force = false): string
199         {
200                 $itemUid = $this->session->getLocalUserId();
201
202                 $parent = null;
203                 if (!$this->session->getLocalUserId() && !empty($item['parent-uri-id'])) {
204                         $parent = Post::selectFirst(['uid'], ['uri-id' => $item['parent-uri-id'], 'wall' => true]);
205                 }
206
207                 if (!empty($parent)) {
208                         $pageUid         = $parent['uid'];
209                         if ($this->session->getRemoteContactID($pageUid)) {
210                                 $itemUid = $parent['uid'];
211                         }
212                 } else {
213                         $pageUid = $item['uid'];
214                 }
215
216                 if (!empty($pageUid) && ($pageUid != $this->session->getLocalUserId())) {
217                         $page_user = User::getById($pageUid, ['nickname', 'hidewall']);
218                 }
219
220                 if (!empty($page_user['hidewall']) && !$this->session->isAuthenticated()) {
221                         $this->baseUrl->redirect('profile/' . $page_user['nickname'] . '/restricted');
222                 }
223
224                 $sql_extra = Item::getPermissionsSQLByUserId($pageUid);
225
226                 if ($this->session->getLocalUserId() && ($this->session->getLocalUserId() == $pageUid)) {
227                         $unseen = Post::exists([
228                                 'parent-uri-id' => $item['parent-uri-id'],
229                                 'uid'           => $this->session->getLocalUserId(),
230                                 'unseen'        => true
231                         ]);
232                 } else {
233                         $unseen = false;
234                 }
235
236                 if ($update && !$unseen && !$force) {
237                         return '';
238                 }
239
240                 $condition = ["`uri-id` = ? AND `uid` IN (0, ?) " . $sql_extra, $item['uri-id'], $itemUid];
241                 $fields    = [
242                         'parent-uri-id', 'body', 'title', 'author-name', 'author-avatar', 'plink', 'author-id',
243                         'owner-id', 'contact-id'
244                 ];
245
246                 $item = Post::selectFirstForUser($pageUid, $fields, $condition);
247
248                 if (empty($item)) {
249                         $this->page['aside'] = '';
250                         $displayNotFound = new DisplayNotFound($this->l10n, $this->baseUrl, $this->args, $this->logger, $this->profiler, $this->response, $this->server, $this->parameters);
251                         return $displayNotFound->content();
252                 }
253
254                 $item['uri-id'] = $item['parent-uri-id'];
255
256                 if ($unseen) {
257                         $condition = [
258                                 'parent-uri-id' => $item['parent-uri-id'],
259                                 'uid'           => $this->session->getLocalUserId(),
260                                 'unseen'        => true
261                         ];
262                         Item::update(['unseen' => false], $condition);
263                 }
264
265                 $this->addMetaTags($item);
266
267                 $output = '';
268
269                 $is_owner = $this->session->getLocalUserId() && (in_array($pageUid, [$this->session->getLocalUserId(), 0]));
270
271                 // We need the editor here to be able to reshare an item.
272                 if ($is_owner && !$update) {
273                         $output .= $this->conversation->statusEditor([], 0, true);
274                 }
275
276                 $output .= $this->conversation->create([$item], Conversation::MODE_DISPLAY, $updateUid, false, 'commented', $itemUid);
277
278                 return $output;
279         }
280
281         // We are displaying an "alternate" link if that post was public. See issue 2864
282         protected function displayHead(string $uriId, string $parentUriId)
283         {
284                 if (Post::exists(['uri-id' => $uriId, 'private' => [Item::PUBLIC, Item::UNLISTED]])) {
285                         // For the atom feed the nickname doesn't matter at all, we only need the item id.
286                         $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('display-head.tpl'), [
287                                 '$alternate'    => sprintf('display/feed-item/%s.atom', $uriId),
288                                 '$conversation' => sprintf('display/feed-item/%s/conversation.atom', $parentUriId)
289                         ]);
290                 }
291         }
292
293         /**
294          * Adds <meta> tags to the HTML output based on an item
295          *
296          * @param array $item The item with the information for the <meta> tags
297          *
298          * @return void
299          * @throws \Exception
300          */
301         protected function addMetaTags(array $item)
302         {
303                 // Preparing the meta header
304                 $description = trim(BBCode::toPlaintext($item['body']));
305                 $title       = trim(BBCode::toPlaintext($item['title'] ?? ''));
306                 $author_name = $item['author-name'];
307
308                 $image = $this->baseUrl->remove($item['author-avatar']);
309
310                 if ($title === '') {
311                         $title = $author_name;
312                 }
313
314                 // Limit the description to 160 characters
315                 if (strlen($description) > 160) {
316                         $description = substr($description, 0, 157) . '...';
317                 }
318
319                 $description = htmlspecialchars($description, ENT_COMPAT, 'UTF-8', true); // allow double encoding here
320                 $title       = htmlspecialchars($title, ENT_COMPAT, 'UTF-8', true); // allow double encoding here
321                 $author_name = htmlspecialchars($author_name, ENT_COMPAT, 'UTF-8', true); // allow double encoding here
322
323                 $page = $this->page;
324
325                 if (Contact::exists([
326                         'unsearchable' => true, 'id' => [$item['contact-id'], $item['author-id'], $item['owner-id']]
327                 ])) {
328                         $page['htmlhead'] .= "<meta content=\"noindex, noarchive\" name=\"robots\" />\n";
329                 }
330
331                 $page['htmlhead'] .= sprintf("<meta name=\"author\" content=\"%s\" />\n", $author_name);
332                 $page['htmlhead'] .= sprintf("<meta name=\"title\" content=\"%s\" />\n", $title);
333                 $page['htmlhead'] .= sprintf("<meta name=\"fulltitle\" content=\"%s\" />\n", $title);
334                 $page['htmlhead'] .= sprintf("<meta name=\"description\" content=\"%s\" />\n", $description);
335
336                 // Schema.org microdata
337                 $page['htmlhead'] .= sprintf("<meta itemprop=\"name\" content=\"%s\" />\n", $title);
338                 $page['htmlhead'] .= sprintf("<meta itemprop=\"description\" content=\"%s\" />\n", $description);
339                 $page['htmlhead'] .= sprintf("<meta itemprop=\"image\" content=\"%s\" />\n", $image);
340                 $page['htmlhead'] .= sprintf("<meta itemprop=\"author\" content=\"%s\" />\n", $author_name);
341
342                 // Twitter cards
343                 $page['htmlhead'] .= "<meta name=\"twitter:card\" content=\"summary\" />\n";
344                 $page['htmlhead'] .= sprintf("<meta name=\"twitter:title\" content=\"%s\" />\n", $title);
345                 $page['htmlhead'] .= sprintf("<meta name=\"twitter:description\" content=\"%s\" />\n", $description);
346                 $page['htmlhead'] .= sprintf("<meta name=\"twitter:image\" content=\"%s/%s\" />\n", $this->baseUrl, $image);
347                 $page['htmlhead'] .= sprintf("<meta name=\"twitter:url\" content=\"%s\" />\n", $item["plink"]);
348
349                 // Dublin Core
350                 $page['htmlhead'] .= sprintf("<meta name=\"DC.title\" content=\"%s\" />\n", $title);
351                 $page['htmlhead'] .= sprintf("<meta name=\"DC.description\" content=\"%s\" />\n", $description);
352
353                 // Open Graph
354                 $page['htmlhead'] .= "<meta property=\"og:type\" content=\"website\" />\n";
355                 $page['htmlhead'] .= sprintf("<meta property=\"og:title\" content=\"%s\" />\n", $title);
356                 $page['htmlhead'] .= sprintf("<meta property=\"og:image\" content=\"%s/%s\" />\n", $this->baseUrl, $image);
357                 $page['htmlhead'] .= sprintf("<meta property=\"og:url\" content=\"%s\" />\n", $item["plink"]);
358                 $page['htmlhead'] .= sprintf("<meta property=\"og:description\" content=\"%s\" />\n", $description);
359                 $page['htmlhead'] .= sprintf("<meta name=\"og:article:author\" content=\"%s\" />\n", $author_name);
360                 // article:tag
361         }
362 }