]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
show "parent unknown" when parent not federated
[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'];
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                 $responses = [];
339                 foreach ($response_verbs as $value => $verb) {
340                         $responses[$verb] = [
341                                 'self'   => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
342                                 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? DI::conversation()->formatActivity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
343                         ];
344                 }
345
346                 /*
347                  * We should avoid doing this all the time, but it depends on the conversation mode
348                  * And the conv mode may change when we change the conv, or it changes its mode
349                  * Maybe we should establish a way to be notified about conversation changes
350                  */
351                 $this->checkWallToWall();
352
353                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
354                         $osparkle = ' sparkle';
355                 }
356
357                 $tagger = '';
358
359                 if ($this->isToplevel()) {
360                         if (DI::userSession()->getLocalUserId()) {
361                                 $ignored_thread = PostModel\ThreadUser::getIgnored($item['uri-id'], DI::userSession()->getLocalUserId());
362                                 if ($item['mention'] || $ignored_thread) {
363                                         $ignore_thread = [
364                                                 'do'        => DI::l10n()->t('Ignore thread'),
365                                                 'undo'      => DI::l10n()->t('Unignore thread'),
366                                                 'toggle'    => DI::l10n()->t('Toggle ignore status'),
367                                                 'classdo'   => $ignored_thread ? 'hidden' : '',
368                                                 'classundo' => $ignored_thread ? '' : 'hidden',
369                                                 'ignored'   => DI::l10n()->t('Ignored'),
370                                         ];
371                                 }
372
373                                 $isstarred = (($item['starred']) ? 'starred' : 'unstarred');
374
375                                 $star = [
376                                         'do'        => DI::l10n()->t('Add star'),
377                                         'undo'      => DI::l10n()->t('Remove star'),
378                                         'toggle'    => DI::l10n()->t('Toggle star status'),
379                                         'classdo'   => $item['starred'] ? 'hidden' : '',
380                                         'classundo' => $item['starred'] ? '' : 'hidden',
381                                         'starred'   => DI::l10n()->t('Starred'),
382                                 ];
383
384                                 if ($conv->getProfileOwner() == DI::userSession()->getLocalUserId() && ($item['uid'] != 0)) {
385                                         if ($origin && in_array($item['private'], [Item::PUBLIC, Item::UNLISTED])) {
386                                                 $ispinned = ($item['featured'] ? 'pinned' : 'unpinned');
387
388                                                 $pin = [
389                                                         'do'        => DI::l10n()->t('Pin'),
390                                                         'undo'      => DI::l10n()->t('Unpin'),
391                                                         'toggle'    => DI::l10n()->t('Toggle pin status'),
392                                                         'classdo'   => $item['featured'] ? 'hidden' : '',
393                                                         'classundo' => $item['featured'] ? '' : 'hidden',
394                                                         'pinned'   => DI::l10n()->t('Pinned'),
395                                                 ];
396                                         }
397
398                                         $tagger = [
399                                                 'add'   => DI::l10n()->t('Add tag'),
400                                                 'class' => '',
401                                         ];
402                                 }
403                         }
404                 } else {
405                         $indent = 'comment';
406                 }
407
408                 if ($conv->isWritable()) {
409                         $buttons['like']    = [DI::l10n()->t("I like this \x28toggle\x29"), DI::l10n()->t('Like')];
410                         $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t('Dislike')];
411                         if ($shareable) {
412                                 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
413                         }
414                         if ($announceable) {
415                                 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
416                                 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
417                         }
418                 }
419
420                 if ($commentable) {
421                         $comment_html = $this->getCommentBox($indent);
422                 } else {
423                         $comment_html = '';
424                 }
425
426                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
427                         $shiny = 'shiny';
428                 }
429
430                 DI::contentItem()->localize($item);
431
432                 $body_html = Item::prepareBody($item, true);
433
434                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, DI::userSession()->getLocalUserId());
435
436                 if (!empty($item['title'])) {
437                         $title = $item['title'];
438                 } elseif (!empty($item['content-warning']) && DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false)) {
439                         $title = ucfirst($item['content-warning']);
440                 } else {
441                         $title = '';
442                 }
443
444                 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike')) {
445                         $buttons['dislike'] = false;
446                 }
447
448                 // Disable features that aren't available in several networks
449                 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
450                         if ($buttons['dislike']) {
451                                 $buttons['dislike'] = false;
452                         }
453
454                         $isevent = false;
455                         $tagger = '';
456                 }
457
458                 if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
459                         $buttons['like'] = false;
460                 }
461
462                 $tags = Tag::populateFromItem($item);
463
464                 $ago = Temporal::getRelativeDate($item['created']);
465                 $ago_received = Temporal::getRelativeDate($item['received']);
466                 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
467                         $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
468                 }
469
470                 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
471                 if (!DI::userSession()->getLocalUserId() && ($item['network'] != Protocol::DIASPORA) && !empty(DI::session()->get('remote_comment'))) {
472                         $remote_comment = [
473                                 DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('Remote comment'),
474                                 str_replace('{uri}', urlencode($item['uri']), DI::session()->get('remote_comment'))
475                         ];
476
477                         // Ensure to either display the remote comment or the local activities
478                         $buttons = [];
479                         $comment_html = '';
480                 } else {
481                         $remote_comment = '';
482                 }
483
484                 $direction = [];
485                 if (!empty($item['direction'])) {
486                         $direction = $item['direction'];
487                 }
488
489                 $languages = [];
490                 if (!empty($item['language'])) {
491                         $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
492                 }
493
494                 if (in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($item['network'], Protocol::FEDERATED)) {
495                         $browsershare = [DI::l10n()->t('Share via ...'), DI::l10n()->t('Share via external services')];
496                 } else {
497                         $browsershare = null;
498                 }
499
500                 $parent_guid     = $thread_parent[$item['thr-parent-id']]['guid'] ?? '';
501                 $parent_username = $thread_parent[$item['thr-parent-id']]['name'] ?? '';
502                 $parent_unknown  = $parent_username ? '' : DI::l10n()->t('parent unknown');
503
504                 $tmp_item = [
505                         'parentguid'      => $parent_guid,
506                         'isreplyto'       => DI::l10n()->t('is reply to %s', $parent_username),
507                         'isunknown'       => $parent_unknown,
508                         'isunknown_label' => DI::l10n()->t('parent is probably private or not federated'),
509                         'template'        => $this->getTemplate(),
510                         'type'            => implode('', array_slice(explode('/', $item['verb']), -1)),
511                         'comment_firstcollapsed' => false,
512                         'comment_lastcollapsed' => false,
513                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
514                         'tags'            => $tags['tags'],
515                         'hashtags'        => $tags['hashtags'],
516                         'mentions'        => $tags['mentions'],
517                         'implicit_mentions' => $tags['implicit_mentions'],
518                         'txt_cats'        => DI::l10n()->t('Categories:'),
519                         'txt_folders'     => DI::l10n()->t('Filed under:'),
520                         'has_cats'        => ((count($categories)) ? 'true' : ''),
521                         'has_folders'     => ((count($folders)) ? 'true' : ''),
522                         'categories'      => $categories,
523                         'folders'         => $folders,
524                         'body_html'       => $body_html,
525                         'text'            => strip_tags($body_html),
526                         'id'              => $this->getId(),
527                         'guid'            => urlencode($item['guid']),
528                         'isevent'         => $isevent,
529                         'attend'          => $attend,
530                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
531                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
532                         'to'              => DI::l10n()->t('to'),
533                         'via'             => DI::l10n()->t('via'),
534                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
535                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
536                         'profile_url'     => $profile_link,
537                         'name'            => $profile_name,
538                         'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
539                         'thumb'           => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)),
540                         'osparkle'        => $osparkle,
541                         'sparkle'         => $sparkle,
542                         'title'           => $title,
543                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
544                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
545                         'app'             => $item['app'],
546                         'created'         => $ago,
547                         'lock'            => $lock,
548                         'private'         => $item['private'],
549                         'privacy'         => $privacy,
550                         'connector'       => $connector,
551                         'location_html'   => $location_html,
552                         'indent'          => $indent,
553                         'shiny'           => $shiny,
554                         'owner_self'      => $item['author-link'] == DI::session()->get('my_url'),
555                         'owner_url'       => $this->getOwnerUrl(),
556                         'owner_photo'     => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)),
557                         'owner_name'      => $this->getOwnerName(),
558                         'plink'           => Item::getPlink($item),
559                         'browsershare'    => $browsershare,
560                         'edpost'          => $edpost,
561                         'ispinned'        => $ispinned,
562                         'pin'             => $pin,
563                         'pinned'          => $pinned,
564                         'isstarred'       => $isstarred,
565                         'star'            => $star,
566                         'ignore'          => $ignore_thread,
567                         'tagger'          => $tagger,
568                         'filer'           => $filer,
569                         'language'        => $languages,
570                         'drop'            => $drop,
571                         'block'           => $block,
572                         'ignore_author'   => $ignore,
573                         'collapse'        => $collapse,
574                         'report'          => $report,
575                         'ignore_server'     => $ignoreServer,
576                         'vote'            => $buttons,
577                         'like_html'       => $responses['like']['output'],
578                         'dislike_html'    => $responses['dislike']['output'],
579                         'emojis'          => $this->getEmojis($item),
580                         'responses'       => $responses,
581                         'switchcomment'   => DI::l10n()->t('Comment'),
582                         'reply_label'     => DI::l10n()->t('Reply to %s', $profile_name),
583                         'comment_html'    => $comment_html,
584                         'remote_comment'  => $remote_comment,
585                         'menu'            => DI::l10n()->t('More'),
586                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
587                         'wait'            => DI::l10n()->t('Please wait'),
588                         'thread_level'    => $thread_level,
589                         'edited'          => $edited,
590                         'author_gsid'     => $item['author-gsid'],
591                         'network'         => $item['network'],
592                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
593                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
594                         'received'        => $item['received'],
595                         'commented'       => $item['commented'],
596                         'created_date'    => $item['created'],
597                         'uriid'           => $item['uri-id'],
598                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
599                         'direction'       => $direction,
600                         'reshared'        => $item['reshared'] ?? '',
601                         'delivery'        => [
602                                 'queue_count'       => $item['delivery_queue_count'],
603                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
604                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
605                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
606                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
607                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
608                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
609                         ],
610                 ];
611
612                 $arr = ['item' => $item, 'output' => $tmp_item];
613                 Hook::callAll('display_item', $arr);
614
615                 $result = $arr['output'];
616
617                 $result['children'] = [];
618                 $children = $this->getChildren();
619                 $nb_children = count($children);
620                 if ($nb_children > 0) {
621                         $thread_parent[$item['uri-id']] = ['guid' => $item['guid'], 'name' => $item['author-name']];
622                         foreach ($children as $child) {
623                                 $thread_parent[$child->getDataValue('uri-id')] = ['guid' => $child->getDataValue('guid'), 'name' => $child->getDataValue('author-name')];
624                                 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1, $thread_parent);
625                         }
626
627                         // Collapse
628                         if (($nb_children > 2) || ($thread_level > 1)) {
629                                 $result['children'][0]['comment_firstcollapsed'] = true;
630                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
631                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
632                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
633                                 if ($thread_level > 1) {
634                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
635                                 } else {
636                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
637                                 }
638                         }
639                 }
640
641                 // Copy values/set defaults
642                 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
643                 $result['private']            = $item['private'];
644                 $result['toplevel']           = ($this->isToplevel() ? 'toplevel_item' : '');
645                 $result['flatten']            = !$this->isThreaded();
646                 $result['threaded']           = $this->isThreaded();
647
648                 return $result;
649         }
650
651         /**
652          * Fetch emojis
653          *
654          * @param array $item
655          * @return array
656          */
657         private function getEmojis(array $item): array
658         {
659                 if (empty($item['emojis'])) {
660                         return [];
661                 }
662
663                 $emojis = [];
664                 foreach ($item['emojis'] as $index => $element) {
665                         $actors = implode(', ', $element['title']);
666                         switch ($element['verb']) {
667                                 case Activity::ANNOUNCE:
668                                         $title = DI::l10n()->t('Reshared by: %s', $actors);
669                                         $icon  = ['fa' => 'fa-retweet', 'icon' => 'icon-retweet'];
670                                         break;
671
672                                 case Activity::VIEW:
673                                         $title = DI::l10n()->t('Viewed by: %s', $actors);
674                                         $icon  = ['fa' => 'fa-eye', 'icon' => 'icon-eye-open'];
675                                         break;
676
677                                 case Activity::LIKE:
678                                         $title = DI::l10n()->t('Liked by: %s', $actors);
679                                         $icon  = ['fa' => 'fa-thumbs-up', 'icon' => 'icon-thumbs-up'];
680                                         break;
681
682                                 case Activity::DISLIKE:
683                                         $title = DI::l10n()->t('Disliked by: %s', $actors);
684                                         $icon  = ['fa' => 'fa-thumbs-down', 'icon' => 'icon-thumbs-down'];
685                                         break;
686
687                                 case Activity::ATTEND:
688                                         $title = DI::l10n()->t('Attended by: %s', $actors);
689                                         $icon  = ['fa' => 'fa-check', 'icon' => 'icon-ok'];
690                                         break;
691
692                                 case Activity::ATTENDMAYBE:
693                                         $title = DI::l10n()->t('Maybe attended by: %s', $actors);
694                                         $icon  = ['fa' => 'fa-question', 'icon' => 'icon-question'];
695                                         break;
696
697                                 case Activity::ATTENDNO:
698                                         $title = DI::l10n()->t('Not attended by: %s', $actors);
699                                         $icon  = ['fa' => 'fa-times', 'icon' => 'icon-remove'];
700                                         break;
701
702                                 default:
703                                         $title = DI::l10n()->t('Reacted with %s by: %s', $element['emoji'], $actors);
704                                         $icon  = [];
705                                         break;
706                         }
707                         $emojis[$index] = ['emoji' => $element['emoji'], 'total' => $element['total'], 'title' => $title, 'icon' => $icon];
708                 }
709                 ksort($emojis);
710
711                 return $emojis;
712         }
713
714         /**
715          * @return integer
716          */
717         public function getId(): int
718         {
719                 return $this->getDataValue('id');
720         }
721
722         /**
723          * @return boolean
724          */
725         public function isThreaded(): bool
726         {
727                 return $this->threaded;
728         }
729
730         /**
731          * Add a child post
732          *
733          * @param Post $item The child post to add
734          *
735          * @return Post|bool Last Post object or bool on any error
736          * @throws \Exception
737          */
738         public function addChild(Post $item)
739         {
740                 if (!$item->getId()) {
741                         Logger::error('Post object has no id', ['post' => $item]);
742                         return false;
743                 } elseif ($this->getChild($item->getId())) {
744                         Logger::warning('Post object already exists', ['post' => $item]);
745                         return false;
746                 }
747
748                 /*
749                  * Only add what will be displayed
750                  */
751                 if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) {
752                         Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]);
753                         return false;
754                 } elseif (
755                         DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) ||
756                         DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE)
757                 ) {
758                         Logger::warning('Post objects is a like/dislike', ['post' => $item]);
759                         return false;
760                 }
761
762                 $item->setParent($this);
763                 $this->children[] = $item;
764
765                 return end($this->children);
766         }
767
768         /**
769          * Get a child by its ID
770          *
771          * @param integer $id The child id
772          * @return Thread|null Thread or NULL if not found
773          */
774         public function getChild(int $id)
775         {
776                 foreach ($this->getChildren() as $child) {
777                         if ($child->getId() == $id) {
778                                 return $child;
779                         }
780                 }
781
782                 return null;
783         }
784
785         /**
786          * Get all our children
787          *
788          * @return Post[]
789          */
790         public function getChildren(): array
791         {
792                 return $this->children;
793         }
794
795         /**
796          * Set our parent
797          *
798          * @param Post $item The item to set as parent
799          * @return void
800          */
801         protected function setParent(Post $item)
802         {
803                 $parent = $this->getParent();
804                 if ($parent) {
805                         $parent->removeChild($this);
806                 }
807
808                 $this->parent = $item;
809                 $this->setThread($item->getThread());
810         }
811
812         /**
813          * Remove our parent
814          *
815          * @return void
816          */
817         protected function removeParent()
818         {
819                 $this->parent = null;
820                 $this->thread = null;
821         }
822
823         /**
824          * Remove a child
825          *
826          * @param Post $item The child to be removed
827          * @return boolean Success or failure
828          * @throws \Exception
829          */
830         public function removeChild(Post $item): bool
831         {
832                 $id = $item->getId();
833                 foreach ($this->getChildren() as $key => $child) {
834                         if ($child->getId() == $id) {
835                                 $child->removeParent();
836                                 unset($this->children[$key]);
837                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
838                                 $this->children = array_values($this->children);
839                                 return true;
840                         }
841                 }
842
843                 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
844                 return false;
845         }
846
847         /**
848          * Get parent item
849          *
850          * @return object
851          */
852         protected function getParent()
853         {
854                 return $this->parent;
855         }
856
857         /**
858          * Set conversation thread
859          *
860          * @param Thread|null $thread
861          *
862          * @return void
863          */
864         public function setThread(Thread $thread = null)
865         {
866                 $this->thread = $thread;
867
868                 // Set it on our children too
869                 foreach ($this->getChildren() as $child) {
870                         $child->setThread($thread);
871                 }
872         }
873
874         /**
875          * Get conversation
876          *
877          * @return Thread|null
878          */
879         public function getThread()
880         {
881                 return $this->thread;
882         }
883
884         /**
885          * Get raw data
886          *
887          * We shouldn't need this
888          *
889          * @return array
890          */
891         public function getData(): array
892         {
893                 return $this->data;
894         }
895
896         /**
897          * Get a data value
898          *
899          * @param string $name key
900          *
901          * @return mixed value on success, false on failure
902          */
903         public function getDataValue(string $name)
904         {
905                 if (!isset($this->data[$name])) {
906                         // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
907                         return false;
908                 }
909
910                 return $this->data[$name];
911         }
912
913         /**
914          * Set template by name
915          *
916          * @param string $name Template name
917          *
918          * @return void
919          * @throws InvalidArgumentException
920          */
921         private function setTemplate(string $name)
922         {
923                 if (empty($this->available_templates[$name])) {
924                         // Throw exception
925                         throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
926                 }
927
928                 $this->template = $this->available_templates[$name];
929         }
930
931         /**
932          * Get template
933          *
934          * @return object
935          */
936         private function getTemplate()
937         {
938                 return $this->template;
939         }
940
941         /**
942          * Check if this is a toplevel post
943          *
944          * @return boolean
945          */
946         private function isToplevel(): bool
947         {
948                 return $this->toplevel;
949         }
950
951         /**
952          * Check if this is writable
953          *
954          * @return boolean
955          */
956         private function isWritable(): bool
957         {
958                 $conv = $this->getThread();
959
960                 if ($conv) {
961                         // This will allow us to comment on wall-to-wall items owned by our friends
962                         // and community groups even if somebody else wrote the post.
963                         // bug #517 - this fixes for conversation owner
964                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == DI::userSession()->getLocalUserId()) {
965                                 return true;
966                         }
967
968                         // this fixes for visitors
969                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
970                 }
971                 return $this->writable;
972         }
973
974         /**
975          * Count the total of our descendants
976          *
977          * @return integer
978          */
979         private function countDescendants(): int
980         {
981                 $children = $this->getChildren();
982                 $total = count($children);
983                 if ($total > 0) {
984                         foreach ($children as $child) {
985                                 $total += $child->countDescendants();
986                         }
987                 }
988
989                 return $total;
990         }
991
992         /**
993          * Get the template for the comment box
994          *
995          * @return string
996          */
997         private function getCommentBoxTemplate(): string
998         {
999                 return $this->comment_box_template;
1000         }
1001
1002         /**
1003          * Get default text for the comment box
1004          *
1005          * @return string
1006          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1007          */
1008         private function getDefaultText(): string
1009         {
1010                 $a = DI::app();
1011
1012                 if (!DI::userSession()->getLocalUserId()) {
1013                         return '';
1014                 }
1015
1016                 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1017                 $item = $this->getData();
1018
1019                 if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), 'add_abstract')) {
1020                         $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
1021                 } else {
1022                         $text = '';
1023                 }
1024
1025                 if (!Feature::isEnabled(DI::userSession()->getLocalUserId(), 'explicit_mentions')) {
1026                         return $text;
1027                 }
1028
1029                 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != Item::GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
1030                         $text .= '@' . $item['author-addr'] . ' ';
1031                 }
1032
1033                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1034                 foreach ($terms as $term) {
1035                         if (!$term['url']) {
1036                                 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
1037                                 continue;
1038                         }
1039
1040                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
1041                         if (
1042                                 !empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
1043                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])
1044                         ) {
1045                                 $text .= '@' . $profile['addr'] . ' ';
1046                         }
1047                 }
1048
1049                 return $text;
1050         }
1051
1052         /**
1053          * Get the comment box
1054          *
1055          * @param string $indent Indent value
1056          *
1057          * @return mixed The comment box string (empty if no comment box), false on failure
1058          * @throws \Exception
1059          * @todo return false is nowhere in this method?
1060          */
1061         private function getCommentBox(string $indent)
1062         {
1063                 $a = DI::app();
1064
1065                 $comment_box = '';
1066                 $conv = $this->getThread();
1067
1068                 if ($conv->isWritable() && $this->isWritable()) {
1069                         /*
1070                          * Hmmm, code depending on the presence of a particular addon?
1071                          * This should be better if done by a hook
1072                          */
1073                         $qcomment = null;
1074                         if (Addon::isEnabled('qcomment')) {
1075                                 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1076                                 $qcomment = $words ? explode("\n", $words) : [];
1077                         }
1078
1079                         // Fetch the user id from the parent when the owner user is empty
1080                         $uid = $conv->getProfileOwner();
1081                         $parent_uid = $this->getDataValue('uid');
1082
1083                         $owner = User::getOwnerDataById($a->getLoggedInUserId());
1084
1085                         $default_text = $this->getDefaultText();
1086
1087                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
1088                                 $uid = $parent_uid;
1089                         }
1090
1091                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
1092                         $comment_box = Renderer::replaceMacros($template, [
1093                                 '$return_path' => DI::args()->getQueryString(),
1094                                 '$threaded'    => $this->isThreaded(),
1095                                 '$jsreload'    => '',
1096                                 '$wall'        => ($conv->getMode() === 'profile'),
1097                                 '$id'          => $this->getId(),
1098                                 '$parent'      => $this->getId(),
1099                                 '$qcomment'    => $qcomment,
1100                                 '$default'     => $default_text,
1101                                 '$profile_uid' => $uid,
1102                                 '$mylink'      => DI::baseUrl()->remove($owner['url'] ?? ''),
1103                                 '$mytitle'     => DI::l10n()->t('This is you'),
1104                                 '$myphoto'     => DI::baseUrl()->remove($owner['thumb'] ?? ''),
1105                                 '$comment'     => DI::l10n()->t('Comment'),
1106                                 '$submit'      => DI::l10n()->t('Submit'),
1107                                 '$loading'     => DI::l10n()->t('Loading...'),
1108                                 '$edbold'      => DI::l10n()->t('Bold'),
1109                                 '$editalic'    => DI::l10n()->t('Italic'),
1110                                 '$eduline'     => DI::l10n()->t('Underline'),
1111                                 '$contentwarn' => DI::l10n()->t('Content Warning'),
1112                                 '$edquote'     => DI::l10n()->t('Quote'),
1113                                 '$edemojis'    => DI::l10n()->t('Add emojis'),
1114                                 '$edcode'      => DI::l10n()->t('Code'),
1115                                 '$edimg'       => DI::l10n()->t('Image'),
1116                                 '$edurl'       => DI::l10n()->t('Link'),
1117                                 '$edattach'    => DI::l10n()->t('Link or Media'),
1118                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1119                                 '$preview'     => DI::l10n()->t('Preview'),
1120                                 '$indent'      => $indent,
1121                                 '$rand_num'    => Crypto::randomDigits(12)
1122                         ]);
1123                 }
1124
1125                 return $comment_box;
1126         }
1127
1128         /**
1129          * @return string
1130          */
1131         private function getRedirectUrl(): string
1132         {
1133                 return $this->redirect_url;
1134         }
1135
1136         /**
1137          * Check if we are a wall to wall item and set the relevant properties
1138          *
1139          * @return void
1140          * @throws \Exception
1141          */
1142         protected function checkWallToWall()
1143         {
1144                 $a = DI::app();
1145                 $conv = $this->getThread();
1146                 $this->wall_to_wall = false;
1147
1148                 if ($this->isToplevel()) {
1149                         if ($conv->getMode() !== 'profile') {
1150                                 if ($this->getDataValue('owner-link')) {
1151                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1152                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1153                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1154
1155                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1156                                                 /*
1157                                                  * The author url doesn't match the owner (typically the contact)
1158                                                  * and also doesn't match the contact alias.
1159                                                  * The name match is a hack to catch several weird cases where URLs are
1160                                                  * all over the park. It can be tricked, but this prevents you from
1161                                                  * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1162                                                  * well that it's the same Bob Smith.
1163                                                  * But it could be somebody else with the same name. It just isn't highly likely.
1164                                                  */
1165                                                 $this->owner_name = $this->getDataValue('owner-name');
1166                                                 $this->wall_to_wall = true;
1167
1168                                                 $owner = [
1169                                                         'uid'     => 0,
1170                                                         'id'      => $this->getDataValue('owner-id'),
1171                                                         'network' => $this->getDataValue('owner-network'),
1172                                                         'url'     => $this->getDataValue('owner-link'),
1173                                                         'alias'   => $this->getDataValue('owner-alias'),
1174                                                 ];
1175                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1176                                         }
1177                                 }
1178                         }
1179                 }
1180
1181                 if (!$this->wall_to_wall) {
1182                         $this->setTemplate('wall');
1183                         $this->owner_url = '';
1184                         $this->owner_name = '';
1185                 }
1186         }
1187
1188         /**
1189          * @return boolean
1190          */
1191         private function isWallToWall(): bool
1192         {
1193                 return $this->wall_to_wall;
1194         }
1195
1196         /**
1197          * @return string
1198          */
1199         private function getOwnerUrl(): string
1200         {
1201                 return $this->owner_url;
1202         }
1203
1204         /**
1205          * @return string
1206          */
1207         private function getOwnerName(): string
1208         {
1209                 return $this->owner_name;
1210         }
1211
1212         /**
1213          * @return boolean
1214          */
1215         private function isVisiting(): bool
1216         {
1217                 return $this->visiting;
1218         }
1219 }