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