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