]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Fixed spelling
[friendica.git] / src / Object / Post.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\Object;
23
24 use Friendica\Content\ContactSelector;
25 use Friendica\Content\Feature;
26 use Friendica\Core\Addon;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\DI;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Item;
34 use Friendica\Model\Post as PostModel;
35 use Friendica\Model\Tag;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Util\Crypto;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Strings;
41 use Friendica\Util\Temporal;
42 use GuzzleHttp\Psr7\Uri;
43 use InvalidArgumentException;
44
45 /**
46  * An item
47  */
48 class Post
49 {
50         private $data = [];
51         private $template = null;
52         private $available_templates = [
53                 'wall' => 'wall_thread.tpl',
54                 'wall2wall' => 'wallwall_thread.tpl'
55         ];
56         private $comment_box_template = 'comment_item.tpl';
57         private $toplevel = false;
58         private $writable = false;
59         /**
60          * @var Post[]
61          */
62         private $children = [];
63         private $parent = null;
64
65         /**
66          * @var Thread
67          */
68         private $thread = null;
69         private $redirect_url = null;
70         private $owner_url = '';
71         private $owner_name = '';
72         private $wall_to_wall = false;
73         private $threaded = false;
74         private $visiting = false;
75
76         /**
77          * Constructor
78          *
79          * @param array $data data array
80          * @throws \Exception
81          */
82         public function __construct(array $data)
83         {
84                 $this->data = $data;
85                 $this->setTemplate('wall');
86                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
87
88                 if (!empty(DI::userSession()->getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
89                         $this->visiting = true;
90                 }
91
92                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
93                 $author = [
94                         'uid'     => 0,
95                         'id'      => $this->getDataValue('author-id'),
96                         'network' => $this->getDataValue('author-network'),
97                         'url'     => $this->getDataValue('author-link'),
98                         'alias'   => $this->getDataValue('author-alias')
99                 ];
100                 $this->redirect_url = Contact::magicLinkByContact($author);
101                 if (!$this->isToplevel()) {
102                         $this->threaded = true;
103                 }
104
105                 // Prepare the children
106                 if (!empty($data['children'])) {
107                         foreach ($data['children'] as $item) {
108                                 // Only add will be displayed
109                                 if ($item['network'] === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item['uid']) {
110                                         continue;
111                                 } elseif (!DI::contentItem()->isVisibleActivity($item)) {
112                                         continue;
113                                 }
114
115                                 // You can always comment on Diaspora and OStatus items
116                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (DI::userSession()->getLocalUserId() == $item['uid'])) {
117                                         $item['writable'] = true;
118                                 }
119
120                                 $item['pagedrop'] = $data['pagedrop'];
121                                 $child = new Post($item);
122                                 $this->addChild($child);
123                         }
124                 }
125         }
126
127         /**
128          * Fetch the privacy of the post
129          *
130          * @param array $item Item record
131          * @return string Item privacy message
132          * @throws InvalidArgumentException If $item['private'] is unknown
133          */
134         private function fetchPrivacy(array $item): string
135         {
136                 switch ($item['private']) {
137                         case Item::PRIVATE:
138                                 $output = DI::l10n()->t('Private Message');
139                                 break;
140
141                         case Item::PUBLIC:
142                                 $output = DI::l10n()->t('Public Message');
143                                 break;
144
145                         case Item::UNLISTED:
146                                 $output = DI::l10n()->t('Unlisted Message');
147                                 break;
148
149                         default:
150                                 throw new InvalidArgumentException('Item privacy ' . $item['privacy'] . ' is unsupported');
151                 }
152
153                 return $output;
154         }
155
156         /**
157          * Get data in a form usable by a conversation template
158          *
159          * @param array   $conv_responses    conversation responses
160          * @param string  $formSecurityToken A security Token to avoid CSF attacks
161          * @param integer $thread_level      default = 1
162          * @param array   $thread_parent     Array of parent guid and parent author names
163          *
164          * @return mixed The data requested on success, false on failure
165          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
166          * @throws \ImagickException
167          */
168         public function getTemplateData(array $conv_responses, string $formSecurityToken, int $thread_level = 1, array $thread_parent = [])
169         {
170                 $item = $this->getData();
171                 $edited = false;
172
173                 /*
174                  * If the time between "created" and "edited" differs we add
175                  * a notice that the post was edited.
176                  * Note: In some networks reshared items seem to have (sometimes) a difference
177                  * between creation time and edit time of a second. Thats why we add the notice
178                  * only if the difference is more than 1 second.
179                  */
180                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
181                         $edited = [
182                                 'label'    => DI::l10n()->t('This entry was edited'),
183                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
184                                 'relative' => Temporal::getRelativeDate($item['edited']),
185                         ];
186                 }
187                 $sparkle = '';
188                 $buttons = [
189                         'like'     => null,
190                         'dislike'  => null,
191                         'share'    => null,
192                         'announce' => null,
193                 ];
194                 $dropping = false;
195                 $pinned = '';
196                 $pin = false;
197                 $star = false;
198                 $ignore_thread = false;
199                 $ispinned = 'unpinned';
200                 $isstarred = 'unstarred';
201                 $indent = '';
202                 $shiny = '';
203                 $osparkle = '';
204                 $total_children = $this->countDescendants();
205
206                 $conv = $this->getThread();
207
208                 $privacy   = $this->fetchPrivacy($item);
209                 $lock      = ($item['private'] == Item::PRIVATE) ? $privacy : false;
210                 $connector = !in_array($item['network'], Protocol::NATIVE_SUPPORT) ? DI::l10n()->t('Connector Message') : false;
211
212                 $shareable    = in_array($conv->getProfileOwner(), [0, DI::userSession()->getLocalUserId()]) && $item['private'] != Item::PRIVATE;
213                 $announceable = $shareable && in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::TWITTER, Protocol::TUMBLR, Protocol::BLUESKY]);
214                 $commentable  = ($item['network'] != Protocol::TUMBLR);
215
216                 // On Diaspora only toplevel posts can be reshared
217                 if ($announceable && ($item['network'] == Protocol::DIASPORA) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
218                         $announceable = false;
219                 }
220
221                 $edpost = false;
222
223                 if (DI::userSession()->getLocalUserId()) {
224                         if (Strings::compareLink(DI::session()->get('my_url'), $item['author-link'])) {
225                                 if ($item['event-id'] != 0) {
226                                         $edpost = ['calendar/event/edit/' . $item['event-id'], DI::l10n()->t('Edit')];
227                                 } else {
228                                         $edpost = [sprintf('post/%s/edit', $item['id']), DI::l10n()->t('Edit')];
229                                 }
230                         }
231                         $dropping = in_array($item['uid'], [0, DI::userSession()->getLocalUserId()]);
232                 }
233
234                 // Editing on items of not subscribed users isn't currently possible
235                 // There are some issues on editing that prevent this.
236                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
237                 if ($item['uid'] == 0) {
238                         $edpost = false;
239                 }
240
241                 if (($this->getDataValue('uid') == DI::userSession()->getLocalUserId()) || $this->isVisiting()) {
242                         $dropping = true;
243                 }
244
245                 $origin = $item['origin'] || $item['parent-origin'];
246
247                 if (!empty($item['featured'])) {
248                         $pinned = DI::l10n()->t('Pinned item');
249                 }
250
251                 $drop         = false;
252                 $block        = false;
253                 $ignore       = false;
254                 $collapse     = false;
255                 $report       = false;
256                 $ignoreServer = false;
257                 if (DI::userSession()->getLocalUserId()) {
258                         $drop = [
259                                 'dropping' => $dropping,
260                                 'pagedrop' => $item['pagedrop'],
261                                 'select' => DI::l10n()->t('Select'),
262                                 'label' => $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally'),
263                         ];
264                 }
265
266                 if (!$item['self'] && DI::userSession()->getLocalUserId()) {
267                         $block = [
268                                 'blocking'  => true,
269                                 'label'     => DI::l10n()->t('Block %s', $item['author-name']),
270                                 'author_id' => $item['author-id'],
271                         ];
272                         $ignore = [
273                                 'ignoring'  => true,
274                                 'label'     => DI::l10n()->t('Ignore %s', $item['author-name']),
275                                 'author_id' => $item['author-id'],
276                         ];
277                         $collapse = [
278                                 'collapsing' => true,
279                                 'label'      => DI::l10n()->t('Collapse %s', $item['author-name']),
280                                 'author_id'  => $item['author-id'],
281                         ];
282                         $report = [
283                                 'label' => DI::l10n()->t('Report post'),
284                                 'href'  => 'moderation/report/create?' . http_build_query(['cid' => $item['author-id'], 'uri-ids' => [$item['uri-id']]]),
285                         ];
286                         $authorBaseUri = new Uri($item['author-baseurl'] ?? '');
287                         if ($authorBaseUri->getHost() && !DI::baseUrl()->isLocalUrl($authorBaseUri)) {
288                                 $ignoreServer = [
289                                         'label' => DI::l10n()->t("Ignore %s server", $authorBaseUri->getHost()),
290                                 ];
291                         }
292                 }
293
294                 $filer = DI::userSession()->getLocalUserId() ? DI::l10n()->t('Save to folder') : false;
295
296                 $profile_name = $item['author-name'];
297                 if (!empty($item['author-link']) && empty($item['author-name'])) {
298                         $profile_name = $item['author-link'];
299                 }
300
301                 if (DI::userSession()->isAuthenticated()) {
302                         $author = [
303                                 'uid'     => 0,
304                                 'id'      => $item['author-id'],
305                                 'network' => $item['author-network'],
306                                 'url'     => $item['author-link'],
307                                 'alias'   => $item['author-alias'],
308                         ];
309                         $profile_link = Contact::magicLinkByContact($author);
310                 } else {
311                         $profile_link = $item['author-link'];
312                 }
313
314                 if (strpos($profile_link, 'contact/redir/') === 0) {
315                         $sparkle = ' sparkle';
316                 }
317
318                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
319                 Hook::callAll('render_location', $locate);
320                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
321
322                 // process action responses - e.g. like/dislike/attend/agree/whatever
323                 $response_verbs = ['like', 'dislike', 'announce', 'comment'];
324
325                 $isevent = false;
326                 $attend = [];
327                 if ($item['object-type'] === Activity\ObjectType::EVENT) {
328                         $response_verbs[] = 'attendyes';
329                         $response_verbs[] = 'attendno';
330                         $response_verbs[] = 'attendmaybe';
331
332                         if ($conv->isWritable()) {
333                                 $isevent = true;
334                                 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
335                         }
336                 }
337
338                 $emojis = $this->getEmojis($item);
339
340                 $verbs = [
341                         'like'        => Activity::LIKE,
342                         'dislike'     => Activity::DISLIKE,
343                         'announce'    => Activity::ANNOUNCE,
344                         'comment'     => Activity::POST,
345                         'attendyes'   => Activity::ATTEND,
346                         'attendno'    => Activity::ATTENDNO,
347                         'attendmaybe' => Activity::ATTENDMAYBE,
348                 ];
349                 $reactions = $emojis;
350                 $responses = [];
351                 foreach ($response_verbs as $value => $verb) {
352                         $responses[$verb] = [
353                                 'self'   => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
354                                 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? DI::conversation()->formatActivity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
355                                 'total'  => $emojis[$verbs[$verb]]['total'] ?? '',
356                                 'title'  => $emojis[$verbs[$verb]]['title'] ?? '',
357                         ];
358                         unset($reactions[$verbs[$verb]]);
359                 }
360
361                 unset($emojis[Activity::POST]);
362
363                 /*
364                  * We should avoid doing this all the time, but it depends on the conversation mode
365                  * And the conv mode may change when we change the conv, or it changes its mode
366                  * Maybe we should establish a way to be notified about conversation changes
367                  */
368                 $this->checkWallToWall();
369
370                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
371                         $osparkle = ' sparkle';
372                 }
373
374                 $tagger = '';
375
376                 if ($this->isToplevel()) {
377                         if (DI::userSession()->getLocalUserId()) {
378                                 $ignored_thread = PostModel\ThreadUser::getIgnored($item['uri-id'], DI::userSession()->getLocalUserId());
379                                 if ($item['mention'] || $ignored_thread) {
380                                         $ignore_thread = [
381                                                 'do'        => DI::l10n()->t('Ignore thread'),
382                                                 'undo'      => DI::l10n()->t('Unignore thread'),
383                                                 'toggle'    => DI::l10n()->t('Toggle ignore status'),
384                                                 'classdo'   => $ignored_thread ? 'hidden' : '',
385                                                 'classundo' => $ignored_thread ? '' : 'hidden',
386                                                 'ignored'   => DI::l10n()->t('Ignored'),
387                                         ];
388                                 }
389
390                                 $isstarred = (($item['starred']) ? 'starred' : 'unstarred');
391
392                                 $star = [
393                                         'do'        => DI::l10n()->t('Add star'),
394                                         'undo'      => DI::l10n()->t('Remove star'),
395                                         'toggle'    => DI::l10n()->t('Toggle star status'),
396                                         'classdo'   => $item['starred'] ? 'hidden' : '',
397                                         'classundo' => $item['starred'] ? '' : 'hidden',
398                                         'starred'   => DI::l10n()->t('Starred'),
399                                 ];
400
401                                 if ($conv->getProfileOwner() == DI::userSession()->getLocalUserId() && ($item['uid'] != 0)) {
402                                         if ($origin && in_array($item['private'], [Item::PUBLIC, Item::UNLISTED])) {
403                                                 $ispinned = ($item['featured'] ? 'pinned' : 'unpinned');
404
405                                                 $pin = [
406                                                         'do'        => DI::l10n()->t('Pin'),
407                                                         'undo'      => DI::l10n()->t('Unpin'),
408                                                         'toggle'    => DI::l10n()->t('Toggle pin status'),
409                                                         'classdo'   => $item['featured'] ? 'hidden' : '',
410                                                         'classundo' => $item['featured'] ? '' : 'hidden',
411                                                         'pinned'   => DI::l10n()->t('Pinned'),
412                                                 ];
413                                         }
414
415                                         $tagger = [
416                                                 'add'   => DI::l10n()->t('Add tag'),
417                                                 'class' => '',
418                                         ];
419                                 }
420                         }
421                 } else {
422                         $indent = 'comment';
423                 }
424
425                 if ($conv->isWritable()) {
426                         $buttons['like']    = [DI::l10n()->t("I like this \x28toggle\x29"), DI::l10n()->t('Like')];
427                         $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t('Dislike')];
428                         if ($shareable) {
429                                 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
430                         }
431                         if ($announceable) {
432                                 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
433                                 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
434                         }
435                 }
436
437                 if ($commentable) {
438                         $comment_html = $this->getCommentBox($indent);
439                 } else {
440                         $comment_html = '';
441                 }
442
443                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
444                         $shiny = 'shiny';
445                 }
446
447                 DI::contentItem()->localize($item);
448
449                 $body_html = Item::prepareBody($item, true);
450
451                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, DI::userSession()->getLocalUserId());
452
453                 if (!empty($item['title'])) {
454                         $title = $item['title'];
455                 } elseif (!empty($item['content-warning']) && DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false)) {
456                         $title = ucfirst($item['content-warning']);
457                 } else {
458                         $title = '';
459                 }
460
461                 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike')) {
462                         $buttons['dislike'] = false;
463                 }
464
465                 // Disable features that aren't available in several networks
466                 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
467                         if ($buttons['dislike']) {
468                                 $buttons['dislike'] = false;
469                         }
470
471                         $isevent = false;
472                         $tagger = '';
473                 }
474
475                 if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
476                         $buttons['like'] = false;
477                 }
478
479                 $tags = Tag::populateFromItem($item);
480
481                 $ago = Temporal::getRelativeDate($item['created']);
482                 $ago_received = Temporal::getRelativeDate($item['received']);
483                 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
484                         $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
485                 }
486
487                 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
488                 if (!DI::userSession()->getLocalUserId() && ($item['network'] != Protocol::DIASPORA) && !empty(DI::session()->get('remote_comment'))) {
489                         $remote_comment = [
490                                 DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('Remote comment'),
491                                 str_replace('{uri}', urlencode($item['uri']), DI::session()->get('remote_comment'))
492                         ];
493
494                         // Ensure to either display the remote comment or the local activities
495                         $buttons = [];
496                         $comment_html = '';
497                 } else {
498                         $remote_comment = '';
499                 }
500
501                 $direction = [];
502                 if (!empty($item['direction'])) {
503                         $direction = $item['direction'];
504                 }
505
506                 $languages = [];
507                 if (!empty($item['language'])) {
508                         $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
509                 }
510
511                 if (in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($item['network'], Protocol::FEDERATED)) {
512                         $browsershare = [DI::l10n()->t('Share via ...'), DI::l10n()->t('Share via external services')];
513                 } else {
514                         $browsershare = null;
515                 }
516
517                 $parent_guid     = $thread_parent[$item['thr-parent-id']]['guid'] ?? '';
518                 $parent_username = $thread_parent[$item['thr-parent-id']]['name'] ?? '';
519                 $parent_unknown  = $parent_username ? '' : DI::l10n()->t('Unknown parent');
520
521                 $tmp_item = [
522                         'parentguid'      => $parent_guid,
523                         'inreplyto'       => DI::l10n()->t('in reply to %s', $parent_username),
524                         'isunknown'       => $parent_unknown,
525                         'isunknown_label' => DI::l10n()->t('Parent is probably private or not federated.'),
526                         'template'        => $this->getTemplate(),
527                         'type'            => implode('', array_slice(explode('/', $item['verb']), -1)),
528                         'comment_firstcollapsed' => false,
529                         'comment_lastcollapsed' => false,
530                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
531                         'tags'            => $tags['tags'],
532                         'hashtags'        => $tags['hashtags'],
533                         'mentions'        => $tags['mentions'],
534                         'implicit_mentions' => $tags['implicit_mentions'],
535                         'txt_cats'        => DI::l10n()->t('Categories:'),
536                         'txt_folders'     => DI::l10n()->t('Filed under:'),
537                         'has_cats'        => ((count($categories)) ? 'true' : ''),
538                         'has_folders'     => ((count($folders)) ? 'true' : ''),
539                         'categories'      => $categories,
540                         'folders'         => $folders,
541                         'body_html'       => $body_html,
542                         'text'            => strip_tags($body_html),
543                         'id'              => $this->getId(),
544                         'guid'            => urlencode($item['guid']),
545                         'isevent'         => $isevent,
546                         'attend'          => $attend,
547                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
548                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
549                         'to'              => DI::l10n()->t('to'),
550                         'via'             => DI::l10n()->t('via'),
551                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
552                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
553                         'profile_url'     => $profile_link,
554                         'name'            => $profile_name,
555                         'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
556                         'thumb'           => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)),
557                         'osparkle'        => $osparkle,
558                         'sparkle'         => $sparkle,
559                         'title'           => $title,
560                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
561                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
562                         'app'             => $item['app'],
563                         'created'         => $ago,
564                         'lock'            => $lock,
565                         'private'         => $item['private'],
566                         'privacy'         => $privacy,
567                         'connector'       => $connector,
568                         'location_html'   => $location_html,
569                         'indent'          => $indent,
570                         'shiny'           => $shiny,
571                         'owner_self'      => $item['author-link'] == DI::session()->get('my_url'),
572                         'owner_url'       => $this->getOwnerUrl(),
573                         'owner_photo'     => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)),
574                         'owner_name'      => $this->getOwnerName(),
575                         'plink'           => Item::getPlink($item),
576                         'browsershare'    => $browsershare,
577                         'edpost'          => $edpost,
578                         'ispinned'        => $ispinned,
579                         'pin'             => $pin,
580                         'pinned'          => $pinned,
581                         'isstarred'       => $isstarred,
582                         'star'            => $star,
583                         'ignore'          => $ignore_thread,
584                         'tagger'          => $tagger,
585                         'filer'           => $filer,
586                         'language'        => $languages,
587                         'drop'            => $drop,
588                         'block'           => $block,
589                         'ignore_author'   => $ignore,
590                         'collapse'        => $collapse,
591                         'report'          => $report,
592                         'ignore_server'     => $ignoreServer,
593                         'vote'            => $buttons,
594                         'like_html'       => $responses['like']['output'],
595                         'dislike_html'    => $responses['dislike']['output'],
596                         'emojis'          => $emojis,
597                         'quoteshares'     => $this->getQuoteShares($item['quoteshares']),
598                         'reactions'       => $reactions,
599                         'responses'       => $responses,
600                         'switchcomment'   => DI::l10n()->t('Comment'),
601                         'reply_label'     => DI::l10n()->t('Reply to %s', $profile_name),
602                         'comment_html'    => $comment_html,
603                         'remote_comment'  => $remote_comment,
604                         'menu'            => DI::l10n()->t('More'),
605                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
606                         'wait'            => DI::l10n()->t('Please wait'),
607                         'thread_level'    => $thread_level,
608                         'edited'          => $edited,
609                         'author_gsid'     => $item['author-gsid'],
610                         'network'         => $item['network'],
611                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
612                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
613                         'received'        => $item['received'],
614                         'commented'       => $item['commented'],
615                         'created_date'    => $item['created'],
616                         'uriid'           => $item['uri-id'],
617                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
618                         'direction'       => $direction,
619                         'reshared'        => $item['reshared'] ?? '',
620                         'delivery'        => [
621                                 'queue_count'       => $item['delivery_queue_count'],
622                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
623                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
624                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
625                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
626                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
627                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
628                         ],
629                 ];
630
631                 $arr = ['item' => $item, 'output' => $tmp_item];
632                 Hook::callAll('display_item', $arr);
633
634                 $result = $arr['output'];
635
636                 $result['children'] = [];
637                 $children = $this->getChildren();
638                 $nb_children = count($children);
639                 if ($nb_children > 0) {
640                         $thread_parent[$item['uri-id']] = ['guid' => $item['guid'], 'name' => $item['author-name']];
641                         foreach ($children as $child) {
642                                 $thread_parent[$child->getDataValue('uri-id')] = ['guid' => $child->getDataValue('guid'), 'name' => $child->getDataValue('author-name')];
643                                 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1, $thread_parent);
644                         }
645
646                         // Collapse
647                         if (($nb_children > 2) || ($thread_level > 1)) {
648                                 $result['children'][0]['comment_firstcollapsed'] = true;
649                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
650                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
651                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
652                                 if ($thread_level > 1) {
653                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
654                                 } else {
655                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
656                                 }
657                         }
658                 }
659
660                 // Copy values/set defaults
661                 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
662                 $result['private']            = $item['private'];
663                 $result['toplevel']           = ($this->isToplevel() ? 'toplevel_item' : '');
664                 $result['flatten']            = !$this->isThreaded();
665                 $result['threaded']           = $this->isThreaded();
666
667                 return $result;
668         }
669
670         /**
671          * Fetch emojis
672          *
673          * @param array $item
674          * @return array
675          */
676         private function getEmojis(array $item): array
677         {
678                 if (empty($item['emojis'])) {
679                         return [];
680                 }
681
682                 $emojis = [];
683                 foreach ($item['emojis'] as $index => $element) {
684                         $actors = implode(', ', $element['title']);
685                         switch ($element['verb']) {
686                                 case Activity::ANNOUNCE:
687                                         $title = DI::l10n()->t('Reshared by: %s', $actors);
688                                         $icon  = ['fa' => 'fa-retweet', 'icon' => 'icon-retweet'];
689                                         $verb  = Activity::ANNOUNCE;
690                                         break;
691
692                                 case Activity::VIEW:
693                                         $title = DI::l10n()->t('Viewed by: %s', $actors);
694                                         $icon  = ['fa' => 'fa-eye', 'icon' => 'icon-eye-open'];
695                                         $verb  = Activity::VIEW;
696                                         break;
697
698                                 case Activity::LIKE:
699                                         $title = DI::l10n()->t('Liked by: %s', $actors);
700                                         $icon  = ['fa' => 'fa-thumbs-up', 'icon' => 'icon-thumbs-up'];
701                                         $verb  = Activity::LIKE;
702                                         break;
703
704                                 case Activity::DISLIKE:
705                                         $title = DI::l10n()->t('Disliked by: %s', $actors);
706                                         $icon  = ['fa' => 'fa-thumbs-down', 'icon' => 'icon-thumbs-down'];
707                                         $verb  = Activity::DISLIKE;
708                                         break;
709
710                                 case Activity::ATTEND:
711                                         $title = DI::l10n()->t('Attended by: %s', $actors);
712                                         $icon  = ['fa' => 'fa-check', 'icon' => 'icon-ok'];
713                                         $verb  = Activity::ATTEND;
714                                         break;
715
716                                 case Activity::ATTENDMAYBE:
717                                         $title = DI::l10n()->t('Maybe attended by: %s', $actors);
718                                         $icon  = ['fa' => 'fa-question', 'icon' => 'icon-question'];
719                                         $verb  = Activity::ATTENDMAYBE;
720                                         break;
721
722                                 case Activity::ATTENDNO:
723                                         $title = DI::l10n()->t('Not attended by: %s', $actors);
724                                         $icon  = ['fa' => 'fa-times', 'icon' => 'icon-remove'];
725                                         $verb  = Activity::ATTENDNO;
726                                         break;
727
728                                 case Activity::POST:
729                                         $title = DI::l10n()->t('Commented by: %s', $actors);
730                                         $icon  = ['fa' => 'fa-commenting', 'icon' => 'icon-remove'];
731                                         $verb  = Activity::POST;
732                                         break;
733         
734                                 default:
735                                         $title = DI::l10n()->t('Reacted with %s by: %s', $element['emoji'], $actors);
736                                         $icon  = [];
737                                         $verb  = $element['emoji'];
738                                         break;
739                         }
740                         $emojis[$verb] = ['emoji' => $element['emoji'], 'total' => $element['total'], 'title' => $title, 'icon' => $icon];
741                 }
742
743                 return $emojis;
744         }
745
746         /**
747          * Fetch quote shares
748          *
749          * @param array $quoteshares
750          * @return array
751          */
752         private function getQuoteShares($quoteshares)
753         {
754                 if (empty($quoteshares)) {
755                         return [];
756                 }
757
758                 return ['total' => $quoteshares['total'], 'title' => DI::l10n()->t('Quote shared by: %s', implode(', ', $quoteshares['title']))];
759         }
760
761         /**
762          * @return integer
763          */
764         public function getId(): int
765         {
766                 return $this->getDataValue('id');
767         }
768
769         /**
770          * @return boolean
771          */
772         public function isThreaded(): bool
773         {
774                 return $this->threaded;
775         }
776
777         /**
778          * Add a child post
779          *
780          * @param Post $item The child post to add
781          *
782          * @return Post|bool Last Post object or bool on any error
783          * @throws \Exception
784          */
785         public function addChild(Post $item)
786         {
787                 if (!$item->getId()) {
788                         Logger::error('Post object has no id', ['post' => $item]);
789                         return false;
790                 } elseif ($this->getChild($item->getId())) {
791                         Logger::warning('Post object already exists', ['post' => $item]);
792                         return false;
793                 }
794
795                 /*
796                  * Only add what will be displayed
797                  */
798                 if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) {
799                         Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]);
800                         return false;
801                 } elseif (
802                         DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) ||
803                         DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE)
804                 ) {
805                         Logger::warning('Post objects is a like/dislike', ['post' => $item]);
806                         return false;
807                 }
808
809                 $item->setParent($this);
810                 $this->children[] = $item;
811
812                 return end($this->children);
813         }
814
815         /**
816          * Get a child by its ID
817          *
818          * @param integer $id The child id
819          * @return Thread|null Thread or NULL if not found
820          */
821         public function getChild(int $id)
822         {
823                 foreach ($this->getChildren() as $child) {
824                         if ($child->getId() == $id) {
825                                 return $child;
826                         }
827                 }
828
829                 return null;
830         }
831
832         /**
833          * Get all our children
834          *
835          * @return Post[]
836          */
837         public function getChildren(): array
838         {
839                 return $this->children;
840         }
841
842         /**
843          * Set our parent
844          *
845          * @param Post $item The item to set as parent
846          * @return void
847          */
848         protected function setParent(Post $item)
849         {
850                 $parent = $this->getParent();
851                 if ($parent) {
852                         $parent->removeChild($this);
853                 }
854
855                 $this->parent = $item;
856                 $this->setThread($item->getThread());
857         }
858
859         /**
860          * Remove our parent
861          *
862          * @return void
863          */
864         protected function removeParent()
865         {
866                 $this->parent = null;
867                 $this->thread = null;
868         }
869
870         /**
871          * Remove a child
872          *
873          * @param Post $item The child to be removed
874          * @return boolean Success or failure
875          * @throws \Exception
876          */
877         public function removeChild(Post $item): bool
878         {
879                 $id = $item->getId();
880                 foreach ($this->getChildren() as $key => $child) {
881                         if ($child->getId() == $id) {
882                                 $child->removeParent();
883                                 unset($this->children[$key]);
884                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
885                                 $this->children = array_values($this->children);
886                                 return true;
887                         }
888                 }
889
890                 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
891                 return false;
892         }
893
894         /**
895          * Get parent item
896          *
897          * @return object
898          */
899         protected function getParent()
900         {
901                 return $this->parent;
902         }
903
904         /**
905          * Set conversation thread
906          *
907          * @param Thread|null $thread
908          *
909          * @return void
910          */
911         public function setThread(Thread $thread = null)
912         {
913                 $this->thread = $thread;
914
915                 // Set it on our children too
916                 foreach ($this->getChildren() as $child) {
917                         $child->setThread($thread);
918                 }
919         }
920
921         /**
922          * Get conversation
923          *
924          * @return Thread|null
925          */
926         public function getThread()
927         {
928                 return $this->thread;
929         }
930
931         /**
932          * Get raw data
933          *
934          * We shouldn't need this
935          *
936          * @return array
937          */
938         public function getData(): array
939         {
940                 return $this->data;
941         }
942
943         /**
944          * Get a data value
945          *
946          * @param string $name key
947          *
948          * @return mixed value on success, false on failure
949          */
950         public function getDataValue(string $name)
951         {
952                 if (!isset($this->data[$name])) {
953                         // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
954                         return false;
955                 }
956
957                 return $this->data[$name];
958         }
959
960         /**
961          * Set template by name
962          *
963          * @param string $name Template name
964          *
965          * @return void
966          * @throws InvalidArgumentException
967          */
968         private function setTemplate(string $name)
969         {
970                 if (empty($this->available_templates[$name])) {
971                         // Throw exception
972                         throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
973                 }
974
975                 $this->template = $this->available_templates[$name];
976         }
977
978         /**
979          * Get template
980          *
981          * @return object
982          */
983         private function getTemplate()
984         {
985                 return $this->template;
986         }
987
988         /**
989          * Check if this is a toplevel post
990          *
991          * @return boolean
992          */
993         private function isToplevel(): bool
994         {
995                 return $this->toplevel;
996         }
997
998         /**
999          * Check if this is writable
1000          *
1001          * @return boolean
1002          */
1003         private function isWritable(): bool
1004         {
1005                 $conv = $this->getThread();
1006
1007                 if ($conv) {
1008                         // This will allow us to comment on wall-to-wall items owned by our friends
1009                         // and community groups even if somebody else wrote the post.
1010                         // bug #517 - this fixes for conversation owner
1011                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == DI::userSession()->getLocalUserId()) {
1012                                 return true;
1013                         }
1014
1015                         // this fixes for visitors
1016                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
1017                 }
1018                 return $this->writable;
1019         }
1020
1021         /**
1022          * Count the total of our descendants
1023          *
1024          * @return integer
1025          */
1026         private function countDescendants(): int
1027         {
1028                 $children = $this->getChildren();
1029                 $total = count($children);
1030                 if ($total > 0) {
1031                         foreach ($children as $child) {
1032                                 $total += $child->countDescendants();
1033                         }
1034                 }
1035
1036                 return $total;
1037         }
1038
1039         /**
1040          * Get the template for the comment box
1041          *
1042          * @return string
1043          */
1044         private function getCommentBoxTemplate(): string
1045         {
1046                 return $this->comment_box_template;
1047         }
1048
1049         /**
1050          * Get default text for the comment box
1051          *
1052          * @return string
1053          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1054          */
1055         private function getDefaultText(): string
1056         {
1057                 $a = DI::app();
1058
1059                 if (!DI::userSession()->getLocalUserId()) {
1060                         return '';
1061                 }
1062
1063                 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1064                 $item = $this->getData();
1065
1066                 if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), 'add_abstract')) {
1067                         $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
1068                 } else {
1069                         $text = '';
1070                 }
1071
1072                 if (!Feature::isEnabled(DI::userSession()->getLocalUserId(), 'explicit_mentions')) {
1073                         return $text;
1074                 }
1075
1076                 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != Item::GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
1077                         $text .= '@' . $item['author-addr'] . ' ';
1078                 }
1079
1080                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1081                 foreach ($terms as $term) {
1082                         if (!$term['url']) {
1083                                 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
1084                                 continue;
1085                         }
1086
1087                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
1088                         if (
1089                                 !empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
1090                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])
1091                         ) {
1092                                 $text .= '@' . $profile['addr'] . ' ';
1093                         }
1094                 }
1095
1096                 return $text;
1097         }
1098
1099         /**
1100          * Get the comment box
1101          *
1102          * @param string $indent Indent value
1103          *
1104          * @return mixed The comment box string (empty if no comment box), false on failure
1105          * @throws \Exception
1106          * @todo return false is nowhere in this method?
1107          */
1108         private function getCommentBox(string $indent)
1109         {
1110                 $a = DI::app();
1111
1112                 $comment_box = '';
1113                 $conv = $this->getThread();
1114
1115                 if ($conv->isWritable() && $this->isWritable()) {
1116                         /*
1117                          * Hmmm, code depending on the presence of a particular addon?
1118                          * This should be better if done by a hook
1119                          */
1120                         $qcomment = null;
1121                         if (Addon::isEnabled('qcomment')) {
1122                                 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1123                                 $qcomment = $words ? explode("\n", $words) : [];
1124                         }
1125
1126                         // Fetch the user id from the parent when the owner user is empty
1127                         $uid = $conv->getProfileOwner();
1128                         $parent_uid = $this->getDataValue('uid');
1129
1130                         $owner = User::getOwnerDataById($a->getLoggedInUserId());
1131
1132                         $default_text = $this->getDefaultText();
1133
1134                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
1135                                 $uid = $parent_uid;
1136                         }
1137
1138                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
1139                         $comment_box = Renderer::replaceMacros($template, [
1140                                 '$return_path' => DI::args()->getQueryString(),
1141                                 '$threaded'    => $this->isThreaded(),
1142                                 '$jsreload'    => '',
1143                                 '$wall'        => ($conv->getMode() === 'profile'),
1144                                 '$id'          => $this->getId(),
1145                                 '$parent'      => $this->getId(),
1146                                 '$qcomment'    => $qcomment,
1147                                 '$default'     => $default_text,
1148                                 '$profile_uid' => $uid,
1149                                 '$mylink'      => DI::baseUrl()->remove($owner['url'] ?? ''),
1150                                 '$mytitle'     => DI::l10n()->t('This is you'),
1151                                 '$myphoto'     => DI::baseUrl()->remove($owner['thumb'] ?? ''),
1152                                 '$comment'     => DI::l10n()->t('Comment'),
1153                                 '$submit'      => DI::l10n()->t('Submit'),
1154                                 '$loading'     => DI::l10n()->t('Loading...'),
1155                                 '$edbold'      => DI::l10n()->t('Bold'),
1156                                 '$editalic'    => DI::l10n()->t('Italic'),
1157                                 '$eduline'     => DI::l10n()->t('Underline'),
1158                                 '$contentwarn' => DI::l10n()->t('Content Warning'),
1159                                 '$edquote'     => DI::l10n()->t('Quote'),
1160                                 '$edemojis'    => DI::l10n()->t('Add emojis'),
1161                                 '$edcode'      => DI::l10n()->t('Code'),
1162                                 '$edimg'       => DI::l10n()->t('Image'),
1163                                 '$edurl'       => DI::l10n()->t('Link'),
1164                                 '$edattach'    => DI::l10n()->t('Link or Media'),
1165                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1166                                 '$preview'     => DI::l10n()->t('Preview'),
1167                                 '$indent'      => $indent,
1168                                 '$rand_num'    => Crypto::randomDigits(12)
1169                         ]);
1170                 }
1171
1172                 return $comment_box;
1173         }
1174
1175         /**
1176          * @return string
1177          */
1178         private function getRedirectUrl(): string
1179         {
1180                 return $this->redirect_url;
1181         }
1182
1183         /**
1184          * Check if we are a wall to wall item and set the relevant properties
1185          *
1186          * @return void
1187          * @throws \Exception
1188          */
1189         protected function checkWallToWall()
1190         {
1191                 $a = DI::app();
1192                 $conv = $this->getThread();
1193                 $this->wall_to_wall = false;
1194
1195                 if ($this->isToplevel()) {
1196                         if ($conv->getMode() !== 'profile') {
1197                                 if ($this->getDataValue('owner-link')) {
1198                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1199                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1200                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1201
1202                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1203                                                 /*
1204                                                  * The author url doesn't match the owner (typically the contact)
1205                                                  * and also doesn't match the contact alias.
1206                                                  * The name match is a hack to catch several weird cases where URLs are
1207                                                  * all over the park. It can be tricked, but this prevents you from
1208                                                  * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1209                                                  * well that it's the same Bob Smith.
1210                                                  * But it could be somebody else with the same name. It just isn't highly likely.
1211                                                  */
1212                                                 $this->owner_name = $this->getDataValue('owner-name');
1213                                                 $this->wall_to_wall = true;
1214
1215                                                 $owner = [
1216                                                         'uid'     => 0,
1217                                                         'id'      => $this->getDataValue('owner-id'),
1218                                                         'network' => $this->getDataValue('owner-network'),
1219                                                         'url'     => $this->getDataValue('owner-link'),
1220                                                         'alias'   => $this->getDataValue('owner-alias'),
1221                                                 ];
1222                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1223                                         }
1224                                 }
1225                         }
1226                 }
1227
1228                 if (!$this->wall_to_wall) {
1229                         $this->setTemplate('wall');
1230                         $this->owner_url = '';
1231                         $this->owner_name = '';
1232                 }
1233         }
1234
1235         /**
1236          * @return boolean
1237          */
1238         private function isWallToWall(): bool
1239         {
1240                 return $this->wall_to_wall;
1241         }
1242
1243         /**
1244          * @return string
1245          */
1246         private function getOwnerUrl(): string
1247         {
1248                 return $this->owner_url;
1249         }
1250
1251         /**
1252          * @return string
1253          */
1254         private function getOwnerName(): string
1255         {
1256                 return $this->owner_name;
1257         }
1258
1259         /**
1260          * @return boolean
1261          */
1262         private function isVisiting(): bool
1263         {
1264                 return $this->visiting;
1265         }
1266 }