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