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