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