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