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