]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Merge pull request #13288 from MrPetovan/task/user-server-block
[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\Network;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45 use InvalidArgumentException;
46
47 /**
48  * An item
49  */
50 class Post
51 {
52         private $data = [];
53         private $template = null;
54         private $available_templates = [
55                 'wall' => 'wall_thread.tpl',
56                 'wall2wall' => 'wallwall_thread.tpl'
57         ];
58         private $comment_box_template = 'comment_item.tpl';
59         private $toplevel = false;
60         private $writable = false;
61         /**
62          * @var Post[]
63          */
64         private $children = [];
65         private $parent = null;
66
67         /**
68          * @var Thread
69          */
70         private $thread = null;
71         private $redirect_url = null;
72         private $owner_url = '';
73         private $owner_name = '';
74         private $wall_to_wall = false;
75         private $threaded = false;
76         private $visiting = false;
77
78         /**
79          * Constructor
80          *
81          * @param array $data data array
82          * @throws \Exception
83          */
84         public function __construct(array $data)
85         {
86                 $this->data = $data;
87                 $this->setTemplate('wall');
88                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
89
90                 if (!empty(DI::userSession()->getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
91                         $this->visiting = true;
92                 }
93
94                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
95                 $author = [
96                         'uid'     => 0,
97                         'id'      => $this->getDataValue('author-id'),
98                         'network' => $this->getDataValue('author-network'),
99                         'url'     => $this->getDataValue('author-link'),
100                         'alias'   => $this->getDataValue('author-alias')
101                 ];
102                 $this->redirect_url = Contact::magicLinkByContact($author);
103                 if (!$this->isToplevel()) {
104                         $this->threaded = true;
105                 }
106
107                 // Prepare the children
108                 if (!empty($data['children'])) {
109                         foreach ($data['children'] as $item) {
110                                 // Only add will be displayed
111                                 if ($item['network'] === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item['uid']) {
112                                         continue;
113                                 } elseif (!DI::contentItem()->isVisibleActivity($item)) {
114                                         continue;
115                                 }
116
117                                 // You can always comment on Diaspora and OStatus items
118                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (DI::userSession()->getLocalUserId() == $item['uid'])) {
119                                         $item['writable'] = true;
120                                 }
121
122                                 $item['pagedrop'] = $data['pagedrop'];
123                                 $child = new Post($item);
124                                 $this->addChild($child);
125                         }
126                 }
127         }
128
129         /**
130          * Fetch the privacy of the post
131          *
132          * @param array $item Item record
133          * @return string Item privacy message
134          * @throws InvalidArgumentException If $item['private'] is unknown
135          */
136         private function fetchPrivacy(array $item): string
137         {
138                 switch ($item['private']) {
139                         case Item::PRIVATE:
140                                 $output = DI::l10n()->t('Private Message');
141                                 break;
142
143                         case Item::PUBLIC:
144                                 $output = DI::l10n()->t('Public Message');
145                                 break;
146
147                         case Item::UNLISTED:
148                                 $output = DI::l10n()->t('Unlisted Message');
149                                 break;
150
151                         default:
152                                 throw new InvalidArgumentException('Item privacy ' . $item['privacy'] . ' is unsupported');
153                 }
154
155                 return $output;
156         }
157
158         /**
159          * Get data in a form usable by a conversation template
160          *
161          * @param array   $conv_responses conversation responses
162          * @param string $formSecurityToken A security Token to avoid CSF attacks
163          * @param integer $thread_level   default = 1
164          *
165          * @return mixed The data requested on success, false on failure
166          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
167          * @throws \ImagickException
168          */
169         public function getTemplateData(array $conv_responses, string $formSecurityToken, int $thread_level = 1)
170         {
171                 $item = $this->getData();
172                 $edited = false;
173
174                 /*
175                  * If the time between "created" and "edited" differs we add
176                  * a notice that the post was edited.
177                  * Note: In some networks reshared items seem to have (sometimes) a difference
178                  * between creation time and edit time of a second. Thats why we add the notice
179                  * only if the difference is more than 1 second.
180                  */
181                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
182                         $edited = [
183                                 'label'    => DI::l10n()->t('This entry was edited'),
184                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
185                                 'relative' => Temporal::getRelativeDate($item['edited']),
186                         ];
187                 }
188                 $sparkle = '';
189                 $buttons = [
190                         'like'     => null,
191                         'dislike'  => null,
192                         'share'    => null,
193                         'announce' => null,
194                 ];
195                 $dropping = false;
196                 $pinned = '';
197                 $pin = false;
198                 $star = false;
199                 $ignore_thread = false;
200                 $ispinned = 'unpinned';
201                 $isstarred = 'unstarred';
202                 $indent = '';
203                 $shiny = '';
204                 $osparkle = '';
205                 $total_children = $this->countDescendants();
206
207                 $conv = $this->getThread();
208
209                 $privacy   = $this->fetchPrivacy($item);
210                 $lock      = ($item['private'] == Item::PRIVATE) ? $privacy : false;
211                 $connector = !in_array($item['network'], Protocol::NATIVE_SUPPORT) ? DI::l10n()->t('Connector Message') : false;
212
213                 $shareable    = in_array($conv->getProfileOwner(), [0, DI::userSession()->getLocalUserId()]) && $item['private'] != Item::PRIVATE;
214                 $announceable = $shareable && in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::TWITTER, Protocol::TUMBLR, Protocol::BLUESKY]);
215                 $commentable  = ($item['network'] != Protocol::TUMBLR);
216
217                 // On Diaspora only toplevel posts can be reshared
218                 if ($announceable && ($item['network'] == Protocol::DIASPORA) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
219                         $announceable = false;
220                 }
221
222                 $edpost = false;
223
224                 if (DI::userSession()->getLocalUserId()) {
225                         if (Strings::compareLink(DI::session()->get('my_url'), $item['author-link'])) {
226                                 if ($item['event-id'] != 0) {
227                                         $edpost = ['calendar/event/edit/' . $item['event-id'], DI::l10n()->t('Edit')];
228                                 } else {
229                                         $edpost = [sprintf('post/%s/edit', $item['id']), DI::l10n()->t('Edit')];
230                                 }
231                         }
232                         $dropping = in_array($item['uid'], [0, DI::userSession()->getLocalUserId()]);
233                 }
234
235                 // Editing on items of not subscribed users isn't currently possible
236                 // There are some issues on editing that prevent this.
237                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
238                 if ($item['uid'] == 0) {
239                         $edpost = false;
240                 }
241
242                 if (($this->getDataValue('uid') == DI::userSession()->getLocalUserId()) || $this->isVisiting()) {
243                         $dropping = true;
244                 }
245
246                 $origin = $item['origin'] || $item['parent-origin'];
247
248                 if (!empty($item['featured'])) {
249                         $pinned = DI::l10n()->t('Pinned item');
250                 }
251
252                 $drop         = false;
253                 $block        = false;
254                 $ignore       = false;
255                 $collapse     = false;
256                 $report       = false;
257                 $ignoreServer = false;
258                 if (DI::userSession()->getLocalUserId()) {
259                         $drop = [
260                                 'dropping' => $dropping,
261                                 'pagedrop' => $item['pagedrop'],
262                                 'select' => DI::l10n()->t('Select'),
263                                 'label' => $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally'),
264                         ];
265                 }
266
267                 if (!$item['self'] && DI::userSession()->getLocalUserId()) {
268                         $block = [
269                                 'blocking'  => true,
270                                 'label'     => DI::l10n()->t('Block %s', $item['author-name']),
271                                 'author_id' => $item['author-id'],
272                         ];
273                         $ignore = [
274                                 'ignoring'  => true,
275                                 'label'     => DI::l10n()->t('Ignore %s', $item['author-name']),
276                                 'author_id' => $item['author-id'],
277                         ];
278                         $collapse = [
279                                 'collapsing' => true,
280                                 'label'      => DI::l10n()->t('Collapse %s', $item['author-name']),
281                                 'author_id'  => $item['author-id'],
282                         ];
283                         $report = [
284                                 'label' => DI::l10n()->t('Report post'),
285                                 'href'  => 'moderation/report/create?' . http_build_query(['cid' => $item['author-id'], 'uri-ids' => [$item['uri-id']]]),
286                         ];
287                         if (!Network::isLocalLink($item['plink'])) {
288                                 $ignoreServer = [
289                                         'label' => DI::l10n()->t("Ignore %s's server", $item['author-name']),
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                 $tmp_item = [
501                         'template'        => $this->getTemplate(),
502                         'type'            => implode('', array_slice(explode('/', $item['verb']), -1)),
503                         'comment_firstcollapsed' => false,
504                         'comment_lastcollapsed' => false,
505                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
506                         'tags'            => $tags['tags'],
507                         'hashtags'        => $tags['hashtags'],
508                         'mentions'        => $tags['mentions'],
509                         'implicit_mentions' => $tags['implicit_mentions'],
510                         'txt_cats'        => DI::l10n()->t('Categories:'),
511                         'txt_folders'     => DI::l10n()->t('Filed under:'),
512                         'has_cats'        => ((count($categories)) ? 'true' : ''),
513                         'has_folders'     => ((count($folders)) ? 'true' : ''),
514                         'categories'      => $categories,
515                         'folders'         => $folders,
516                         'body_html'       => $body_html,
517                         'text'            => strip_tags($body_html),
518                         'id'              => $this->getId(),
519                         'guid'            => urlencode($item['guid']),
520                         'isevent'         => $isevent,
521                         'attend'          => $attend,
522                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
523                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
524                         'to'              => DI::l10n()->t('to'),
525                         'via'             => DI::l10n()->t('via'),
526                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
527                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
528                         'profile_url'     => $profile_link,
529                         'name'            => $profile_name,
530                         'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
531                         'thumb'           => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)),
532                         'osparkle'        => $osparkle,
533                         'sparkle'         => $sparkle,
534                         'title'           => $title,
535                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
536                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
537                         'app'             => $item['app'],
538                         'created'         => $ago,
539                         'lock'            => $lock,
540                         'private'         => $item['private'],
541                         'privacy'         => $privacy,
542                         'connector'       => $connector,
543                         'location_html'   => $location_html,
544                         'indent'          => $indent,
545                         'shiny'           => $shiny,
546                         'owner_self'      => $item['author-link'] == DI::session()->get('my_url'),
547                         'owner_url'       => $this->getOwnerUrl(),
548                         'owner_photo'     => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)),
549                         'owner_name'      => $this->getOwnerName(),
550                         'plink'           => Item::getPlink($item),
551                         'browsershare'    => $browsershare,
552                         'edpost'          => $edpost,
553                         'ispinned'        => $ispinned,
554                         'pin'             => $pin,
555                         'pinned'          => $pinned,
556                         'isstarred'       => $isstarred,
557                         'star'            => $star,
558                         'ignore'          => $ignore_thread,
559                         'tagger'          => $tagger,
560                         'filer'           => $filer,
561                         'language'        => $languages,
562                         'drop'            => $drop,
563                         'block'           => $block,
564                         'ignore_author'   => $ignore,
565                         'collapse'        => $collapse,
566                         'report'          => $report,
567                         'ignore_server'     => $ignoreServer,
568                         'vote'            => $buttons,
569                         'like_html'       => $responses['like']['output'],
570                         'dislike_html'    => $responses['dislike']['output'],
571                         'emojis'          => $this->getEmojis($item),
572                         'responses'       => $responses,
573                         'switchcomment'   => DI::l10n()->t('Comment'),
574                         'reply_label'     => DI::l10n()->t('Reply to %s', $profile_name),
575                         'comment_html'    => $comment_html,
576                         'remote_comment'  => $remote_comment,
577                         'menu'            => DI::l10n()->t('More'),
578                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
579                         'wait'            => DI::l10n()->t('Please wait'),
580                         'thread_level'    => $thread_level,
581                         'edited'          => $edited,
582                         'author_gsid'     => $item['author-gsid'],
583                         'network'         => $item['network'],
584                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
585                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
586                         'received'        => $item['received'],
587                         'commented'       => $item['commented'],
588                         'created_date'    => $item['created'],
589                         'uriid'           => $item['uri-id'],
590                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
591                         'direction'       => $direction,
592                         'reshared'        => $item['reshared'] ?? '',
593                         'delivery'        => [
594                                 'queue_count'       => $item['delivery_queue_count'],
595                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
596                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
597                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
598                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
599                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
600                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
601                         ],
602                 ];
603
604                 $arr = ['item' => $item, 'output' => $tmp_item];
605                 Hook::callAll('display_item', $arr);
606
607                 $result = $arr['output'];
608
609                 $result['children'] = [];
610                 $children = $this->getChildren();
611                 $nb_children = count($children);
612                 if ($nb_children > 0) {
613                         foreach ($children as $child) {
614                                 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1);
615                         }
616
617                         // Collapse
618                         if (($nb_children > 2) || ($thread_level > 1)) {
619                                 $result['children'][0]['comment_firstcollapsed'] = true;
620                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
621                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
622                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
623                                 if ($thread_level > 1) {
624                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
625                                 } else {
626                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
627                                 }
628                         }
629                 }
630
631                 // Copy values/set defaults
632                 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
633                 $result['private']            = $item['private'];
634                 $result['toplevel']           = ($this->isToplevel() ? 'toplevel_item' : '');
635                 $result['flatten']            = !$this->isThreaded();
636                 $result['threaded']           = $this->isThreaded();
637
638                 return $result;
639         }
640
641         /**
642          * Fetch emojis
643          *
644          * @param array $item
645          * @return array
646          */
647         private function getEmojis(array $item): array
648         {
649                 if (empty($item['emojis'])) {
650                         return [];
651                 }
652
653                 $emojis = [];
654                 foreach ($item['emojis'] as $index => $element) {
655                         $actors = implode(', ', $element['title']);
656                         switch ($element['verb']) {
657                                 case Activity::ANNOUNCE:
658                                         $title = DI::l10n()->t('Reshared by: %s', $actors);
659                                         $icon  = ['fa' => 'fa-retweet', 'icon' => 'icon-retweet'];
660                                         break;
661
662                                 case Activity::VIEW:
663                                         $title = DI::l10n()->t('Viewed by: %s', $actors);
664                                         $icon  = ['fa' => 'fa-eye', 'icon' => 'icon-eye-open'];
665                                         break;
666
667                                 case Activity::LIKE:
668                                         $title = DI::l10n()->t('Liked by: %s', $actors);
669                                         $icon  = ['fa' => 'fa-thumbs-up', 'icon' => 'icon-thumbs-up'];
670                                         break;
671
672                                 case Activity::DISLIKE:
673                                         $title = DI::l10n()->t('Disliked by: %s', $actors);
674                                         $icon  = ['fa' => 'fa-thumbs-down', 'icon' => 'icon-thumbs-down'];
675                                         break;
676
677                                 case Activity::ATTEND:
678                                         $title = DI::l10n()->t('Attended by: %s', $actors);
679                                         $icon  = ['fa' => 'fa-check', 'icon' => 'icon-ok'];
680                                         break;
681
682                                 case Activity::ATTENDMAYBE:
683                                         $title = DI::l10n()->t('Maybe attended by: %s', $actors);
684                                         $icon  = ['fa' => 'fa-question', 'icon' => 'icon-question'];
685                                         break;
686
687                                 case Activity::ATTENDNO:
688                                         $title = DI::l10n()->t('Not attended by: %s', $actors);
689                                         $icon  = ['fa' => 'fa-times', 'icon' => 'icon-remove'];
690                                         break;
691
692                                 default:
693                                         $title = DI::l10n()->t('Reacted with %s by: %s', $element['emoji'], $actors);
694                                         $icon  = [];
695                                         break;
696                         }
697                         $emojis[$index] = ['emoji' => $element['emoji'], 'total' => $element['total'], 'title' => $title, 'icon' => $icon];
698                 }
699                 ksort($emojis);
700
701                 return $emojis;
702         }
703
704         /**
705          * @return integer
706          */
707         public function getId(): int
708         {
709                 return $this->getDataValue('id');
710         }
711
712         /**
713          * @return boolean
714          */
715         public function isThreaded(): bool
716         {
717                 return $this->threaded;
718         }
719
720         /**
721          * Add a child post
722          *
723          * @param Post $item The child post to add
724          *
725          * @return Post|bool Last Post object or bool on any error
726          * @throws \Exception
727          */
728         public function addChild(Post $item)
729         {
730                 if (!$item->getId()) {
731                         Logger::error('Post object has no id', ['post' => $item]);
732                         return false;
733                 } elseif ($this->getChild($item->getId())) {
734                         Logger::warning('Post object already exists', ['post' => $item]);
735                         return false;
736                 }
737
738                 /*
739                  * Only add what will be displayed
740                  */
741                 if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) {
742                         Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]);
743                         return false;
744                 } elseif (
745                         DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) ||
746                         DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE)
747                 ) {
748                         Logger::warning('Post objects is a like/dislike', ['post' => $item]);
749                         return false;
750                 }
751
752                 $item->setParent($this);
753                 $this->children[] = $item;
754
755                 return end($this->children);
756         }
757
758         /**
759          * Get a child by its ID
760          *
761          * @param integer $id The child id
762          * @return Thread|null Thread or NULL if not found
763          */
764         public function getChild(int $id)
765         {
766                 foreach ($this->getChildren() as $child) {
767                         if ($child->getId() == $id) {
768                                 return $child;
769                         }
770                 }
771
772                 return null;
773         }
774
775         /**
776          * Get all our children
777          *
778          * @return Post[]
779          */
780         public function getChildren(): array
781         {
782                 return $this->children;
783         }
784
785         /**
786          * Set our parent
787          *
788          * @param Post $item The item to set as parent
789          * @return void
790          */
791         protected function setParent(Post $item)
792         {
793                 $parent = $this->getParent();
794                 if ($parent) {
795                         $parent->removeChild($this);
796                 }
797
798                 $this->parent = $item;
799                 $this->setThread($item->getThread());
800         }
801
802         /**
803          * Remove our parent
804          *
805          * @return void
806          */
807         protected function removeParent()
808         {
809                 $this->parent = null;
810                 $this->thread = null;
811         }
812
813         /**
814          * Remove a child
815          *
816          * @param Post $item The child to be removed
817          * @return boolean Success or failure
818          * @throws \Exception
819          */
820         public function removeChild(Post $item): bool
821         {
822                 $id = $item->getId();
823                 foreach ($this->getChildren() as $key => $child) {
824                         if ($child->getId() == $id) {
825                                 $child->removeParent();
826                                 unset($this->children[$key]);
827                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
828                                 $this->children = array_values($this->children);
829                                 return true;
830                         }
831                 }
832
833                 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
834                 return false;
835         }
836
837         /**
838          * Get parent item
839          *
840          * @return object
841          */
842         protected function getParent()
843         {
844                 return $this->parent;
845         }
846
847         /**
848          * Set conversation thread
849          *
850          * @param Thread|null $thread
851          *
852          * @return void
853          */
854         public function setThread(Thread $thread = null)
855         {
856                 $this->thread = $thread;
857
858                 // Set it on our children too
859                 foreach ($this->getChildren() as $child) {
860                         $child->setThread($thread);
861                 }
862         }
863
864         /**
865          * Get conversation
866          *
867          * @return Thread|null
868          */
869         public function getThread()
870         {
871                 return $this->thread;
872         }
873
874         /**
875          * Get raw data
876          *
877          * We shouldn't need this
878          *
879          * @return array
880          */
881         public function getData(): array
882         {
883                 return $this->data;
884         }
885
886         /**
887          * Get a data value
888          *
889          * @param string $name key
890          *
891          * @return mixed value on success, false on failure
892          */
893         public function getDataValue(string $name)
894         {
895                 if (!isset($this->data[$name])) {
896                         // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
897                         return false;
898                 }
899
900                 return $this->data[$name];
901         }
902
903         /**
904          * Set template by name
905          *
906          * @param string $name Template name
907          *
908          * @return void
909          * @throws InvalidArgumentException
910          */
911         private function setTemplate(string $name)
912         {
913                 if (empty($this->available_templates[$name])) {
914                         // Throw exception
915                         throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
916                 }
917
918                 $this->template = $this->available_templates[$name];
919         }
920
921         /**
922          * Get template
923          *
924          * @return object
925          */
926         private function getTemplate()
927         {
928                 return $this->template;
929         }
930
931         /**
932          * Check if this is a toplevel post
933          *
934          * @return boolean
935          */
936         private function isToplevel(): bool
937         {
938                 return $this->toplevel;
939         }
940
941         /**
942          * Check if this is writable
943          *
944          * @return boolean
945          */
946         private function isWritable(): bool
947         {
948                 $conv = $this->getThread();
949
950                 if ($conv) {
951                         // This will allow us to comment on wall-to-wall items owned by our friends
952                         // and community groups even if somebody else wrote the post.
953                         // bug #517 - this fixes for conversation owner
954                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == DI::userSession()->getLocalUserId()) {
955                                 return true;
956                         }
957
958                         // this fixes for visitors
959                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
960                 }
961                 return $this->writable;
962         }
963
964         /**
965          * Count the total of our descendants
966          *
967          * @return integer
968          */
969         private function countDescendants(): int
970         {
971                 $children = $this->getChildren();
972                 $total = count($children);
973                 if ($total > 0) {
974                         foreach ($children as $child) {
975                                 $total += $child->countDescendants();
976                         }
977                 }
978
979                 return $total;
980         }
981
982         /**
983          * Get the template for the comment box
984          *
985          * @return string
986          */
987         private function getCommentBoxTemplate(): string
988         {
989                 return $this->comment_box_template;
990         }
991
992         /**
993          * Get default text for the comment box
994          *
995          * @return string
996          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
997          */
998         private function getDefaultText(): string
999         {
1000                 $a = DI::app();
1001
1002                 if (!DI::userSession()->getLocalUserId()) {
1003                         return '';
1004                 }
1005
1006                 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1007                 $item = $this->getData();
1008
1009                 if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), 'add_abstract')) {
1010                         $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
1011                 } else {
1012                         $text = '';
1013                 }
1014
1015                 if (!Feature::isEnabled(DI::userSession()->getLocalUserId(), 'explicit_mentions')) {
1016                         return $text;
1017                 }
1018
1019                 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != Item::GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
1020                         $text .= '@' . $item['author-addr'] . ' ';
1021                 }
1022
1023                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1024                 foreach ($terms as $term) {
1025                         if (!$term['url']) {
1026                                 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
1027                                 continue;
1028                         }
1029
1030                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
1031                         if (
1032                                 !empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
1033                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])
1034                         ) {
1035                                 $text .= '@' . $profile['addr'] . ' ';
1036                         }
1037                 }
1038
1039                 return $text;
1040         }
1041
1042         /**
1043          * Get the comment box
1044          *
1045          * @param string $indent Indent value
1046          *
1047          * @return mixed The comment box string (empty if no comment box), false on failure
1048          * @throws \Exception
1049          * @todo return false is nowhere in this method?
1050          */
1051         private function getCommentBox(string $indent)
1052         {
1053                 $a = DI::app();
1054
1055                 $comment_box = '';
1056                 $conv = $this->getThread();
1057
1058                 if ($conv->isWritable() && $this->isWritable()) {
1059                         /*
1060                          * Hmmm, code depending on the presence of a particular addon?
1061                          * This should be better if done by a hook
1062                          */
1063                         $qcomment = null;
1064                         if (Addon::isEnabled('qcomment')) {
1065                                 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1066                                 $qcomment = $words ? explode("\n", $words) : [];
1067                         }
1068
1069                         // Fetch the user id from the parent when the owner user is empty
1070                         $uid = $conv->getProfileOwner();
1071                         $parent_uid = $this->getDataValue('uid');
1072
1073                         $owner = User::getOwnerDataById($a->getLoggedInUserId());
1074
1075                         $default_text = $this->getDefaultText();
1076
1077                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
1078                                 $uid = $parent_uid;
1079                         }
1080
1081                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
1082                         $comment_box = Renderer::replaceMacros($template, [
1083                                 '$return_path' => DI::args()->getQueryString(),
1084                                 '$threaded'    => $this->isThreaded(),
1085                                 '$jsreload'    => '',
1086                                 '$wall'        => ($conv->getMode() === 'profile'),
1087                                 '$id'          => $this->getId(),
1088                                 '$parent'      => $this->getId(),
1089                                 '$qcomment'    => $qcomment,
1090                                 '$default'     => $default_text,
1091                                 '$profile_uid' => $uid,
1092                                 '$mylink'      => DI::baseUrl()->remove($owner['url'] ?? ''),
1093                                 '$mytitle'     => DI::l10n()->t('This is you'),
1094                                 '$myphoto'     => DI::baseUrl()->remove($owner['thumb'] ?? ''),
1095                                 '$comment'     => DI::l10n()->t('Comment'),
1096                                 '$submit'      => DI::l10n()->t('Submit'),
1097                                 '$loading'     => DI::l10n()->t('Loading...'),
1098                                 '$edbold'      => DI::l10n()->t('Bold'),
1099                                 '$editalic'    => DI::l10n()->t('Italic'),
1100                                 '$eduline'     => DI::l10n()->t('Underline'),
1101                                 '$contentwarn' => DI::l10n()->t('Content Warning'),
1102                                 '$edquote'     => DI::l10n()->t('Quote'),
1103                                 '$edemojis'    => DI::l10n()->t('Add emojis'),
1104                                 '$edcode'      => DI::l10n()->t('Code'),
1105                                 '$edimg'       => DI::l10n()->t('Image'),
1106                                 '$edurl'       => DI::l10n()->t('Link'),
1107                                 '$edattach'    => DI::l10n()->t('Link or Media'),
1108                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1109                                 '$preview'     => DI::l10n()->t('Preview'),
1110                                 '$indent'      => $indent,
1111                                 '$rand_num'    => Crypto::randomDigits(12)
1112                         ]);
1113                 }
1114
1115                 return $comment_box;
1116         }
1117
1118         /**
1119          * @return string
1120          */
1121         private function getRedirectUrl(): string
1122         {
1123                 return $this->redirect_url;
1124         }
1125
1126         /**
1127          * Check if we are a wall to wall item and set the relevant properties
1128          *
1129          * @return void
1130          * @throws \Exception
1131          */
1132         protected function checkWallToWall()
1133         {
1134                 $a = DI::app();
1135                 $conv = $this->getThread();
1136                 $this->wall_to_wall = false;
1137
1138                 if ($this->isToplevel()) {
1139                         if ($conv->getMode() !== 'profile') {
1140                                 if ($this->getDataValue('owner-link')) {
1141                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1142                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1143                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1144
1145                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1146                                                 /*
1147                                                  * The author url doesn't match the owner (typically the contact)
1148                                                  * and also doesn't match the contact alias.
1149                                                  * The name match is a hack to catch several weird cases where URLs are
1150                                                  * all over the park. It can be tricked, but this prevents you from
1151                                                  * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1152                                                  * well that it's the same Bob Smith.
1153                                                  * But it could be somebody else with the same name. It just isn't highly likely.
1154                                                  */
1155                                                 $this->owner_name = $this->getDataValue('owner-name');
1156                                                 $this->wall_to_wall = true;
1157
1158                                                 $owner = [
1159                                                         'uid'     => 0,
1160                                                         'id'      => $this->getDataValue('owner-id'),
1161                                                         'network' => $this->getDataValue('owner-network'),
1162                                                         'url'     => $this->getDataValue('owner-link'),
1163                                                         'alias'   => $this->getDataValue('owner-alias'),
1164                                                 ];
1165                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1166                                         }
1167                                 }
1168                         }
1169                 }
1170
1171                 if (!$this->wall_to_wall) {
1172                         $this->setTemplate('wall');
1173                         $this->owner_url = '';
1174                         $this->owner_name = '';
1175                 }
1176         }
1177
1178         /**
1179          * @return boolean
1180          */
1181         private function isWallToWall(): bool
1182         {
1183                 return $this->wall_to_wall;
1184         }
1185
1186         /**
1187          * @return string
1188          */
1189         private function getOwnerUrl(): string
1190         {
1191                 return $this->owner_url;
1192         }
1193
1194         /**
1195          * @return string
1196          */
1197         private function getOwnerName(): string
1198         {
1199                 return $this->owner_name;
1200         }
1201
1202         /**
1203          * @return boolean
1204          */
1205         private function isVisiting(): bool
1206         {
1207                 return $this->visiting;
1208         }
1209 }