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