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