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