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