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