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