3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Object;
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;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Item;
34 use Friendica\Model\Photo;
35 use Friendica\Model\Post as PostModel;
36 use Friendica\Model\Tag;
37 use Friendica\Model\User;
38 use Friendica\Protocol\Activity;
39 use Friendica\Util\Crypto;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45 use InvalidArgumentException;
53 private $template = null;
54 private $available_templates = [
55 'wall' => 'wall_thread.tpl',
56 'wall2wall' => 'wallwall_thread.tpl'
58 private $comment_box_template = 'comment_item.tpl';
59 private $toplevel = false;
60 private $writable = false;
64 private $children = [];
65 private $parent = null;
70 private $thread = null;
71 private $redirect_url = null;
72 private $owner_url = '';
73 private $owner_name = '';
74 private $wall_to_wall = false;
75 private $threaded = false;
76 private $visiting = false;
81 * @param array $data data array
84 public function __construct(array $data)
87 $this->setTemplate('wall');
88 $this->toplevel = $this->getId() == $this->getDataValue('parent');
90 if (!empty(DI::userSession()->getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
91 $this->visiting = true;
94 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
97 'id' => $this->getDataValue('author-id'),
98 'network' => $this->getDataValue('author-network'),
99 'url' => $this->getDataValue('author-link'),
100 'alias' => $this->getDataValue('author-alias')
102 $this->redirect_url = Contact::magicLinkByContact($author);
103 if (!$this->isToplevel()) {
104 $this->threaded = true;
107 // Prepare the children
108 if (!empty($data['children'])) {
109 foreach ($data['children'] as $item) {
110 // Only add will be displayed
111 if ($item['network'] === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item['uid']) {
113 } elseif (!DI::contentItem()->isVisibleActivity($item)) {
117 // You can always comment on Diaspora and OStatus items
118 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (DI::userSession()->getLocalUserId() == $item['uid'])) {
119 $item['writable'] = true;
122 $item['pagedrop'] = $data['pagedrop'];
123 $child = new Post($item);
124 $this->addChild($child);
130 * Fetch the privacy of the post
132 * @param array $item Item record
133 * @return string Item privacy message
134 * @throws InvalidArgumentException If $item['private'] is unknown
136 private function fetchPrivacy(array $item): string
138 switch ($item['private']) {
140 $output = DI::l10n()->t('Private Message');
144 $output = DI::l10n()->t('Public Message');
148 $output = DI::l10n()->t('Unlisted Message');
152 throw new InvalidArgumentException('Item privacy ' . $item['privacy'] . ' is unsupported');
159 * Get data in a form usable by a conversation template
161 * @param array $conv_responses conversation responses
162 * @param string $formSecurityToken A security Token to avoid CSF attacks
163 * @param integer $thread_level default = 1
165 * @return mixed The data requested on success, false on failure
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
167 * @throws \ImagickException
169 public function getTemplateData(array $conv_responses, string $formSecurityToken, int $thread_level = 1)
171 $item = $this->getData();
175 * If the time between "created" and "edited" differs we add
176 * a notice that the post was edited.
177 * Note: In some networks reshared items seem to have (sometimes) a difference
178 * between creation time and edit time of a second. Thats why we add the notice
179 * only if the difference is more than 1 second.
181 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
183 'label' => DI::l10n()->t('This entry was edited'),
184 'date' => DateTimeFormat::local($item['edited'], 'r'),
185 'relative' => Temporal::getRelativeDate($item['edited']),
199 $ignore_thread = false;
200 $ispinned = 'unpinned';
201 $isstarred = 'unstarred';
205 $total_children = $this->countDescendants();
207 $conv = $this->getThread();
209 $privacy = $this->fetchPrivacy($item);
210 $lock = ($item['private'] == Item::PRIVATE) ? $privacy : false;
211 $connector = !in_array($item['network'], Protocol::NATIVE_SUPPORT) ? DI::l10n()->t('Connector Message') : false;
213 $shareable = in_array($conv->getProfileOwner(), [0, DI::userSession()->getLocalUserId()]) && $item['private'] != Item::PRIVATE;
214 $announceable = $shareable && in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::TWITTER, Protocol::TUMBLR, Protocol::BLUESKY]);
215 $commentable = ($item['network'] != Protocol::TUMBLR);
217 // On Diaspora only toplevel posts can be reshared
218 if ($announceable && ($item['network'] == Protocol::DIASPORA) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
219 $announceable = false;
224 if (DI::userSession()->getLocalUserId()) {
225 if (Strings::compareLink(DI::session()->get('my_url'), $item['author-link'])) {
226 if ($item['event-id'] != 0) {
227 $edpost = ['calendar/event/edit/' . $item['event-id'], DI::l10n()->t('Edit')];
229 $edpost = [sprintf('post/%s/edit', $item['id']), DI::l10n()->t('Edit')];
232 $dropping = in_array($item['uid'], [0, DI::userSession()->getLocalUserId()]);
235 // Editing on items of not subscribed users isn't currently possible
236 // There are some issues on editing that prevent this.
237 // But also it is an issue of the supported protocols that doesn't allow editing at all.
238 if ($item['uid'] == 0) {
242 if (($this->getDataValue('uid') == DI::userSession()->getLocalUserId()) || $this->isVisiting()) {
246 $origin = $item['origin'] || $item['parent-origin'];
248 if (!empty($item['featured'])) {
249 $pinned = DI::l10n()->t('Pinned item');
257 $ignoreServer = false;
258 if (DI::userSession()->getLocalUserId()) {
260 'dropping' => $dropping,
261 'pagedrop' => $item['pagedrop'],
262 'select' => DI::l10n()->t('Select'),
263 'label' => $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally'),
267 if (!$item['self'] && DI::userSession()->getLocalUserId()) {
270 'label' => DI::l10n()->t('Block %s', $item['author-name']),
271 'author_id' => $item['author-id'],
275 'label' => DI::l10n()->t('Ignore %s', $item['author-name']),
276 'author_id' => $item['author-id'],
279 'collapsing' => true,
280 'label' => DI::l10n()->t('Collapse %s', $item['author-name']),
281 'author_id' => $item['author-id'],
284 'label' => DI::l10n()->t('Report post'),
285 'href' => 'moderation/report/create?' . http_build_query(['cid' => $item['author-id'], 'uri-ids' => [$item['uri-id']]]),
287 if (!Network::isLocalLink($item['plink'])) {
289 'label' => DI::l10n()->t("Ignore %s's server", $item['author-name']),
294 $filer = DI::userSession()->getLocalUserId() ? DI::l10n()->t('Save to folder') : false;
296 $profile_name = $item['author-name'];
297 if (!empty($item['author-link']) && empty($item['author-name'])) {
298 $profile_name = $item['author-link'];
301 if (DI::userSession()->isAuthenticated()) {
304 'id' => $item['author-id'],
305 'network' => $item['author-network'],
306 'url' => $item['author-link'],
307 'alias' => $item['author-alias'],
309 $profile_link = Contact::magicLinkByContact($author);
311 $profile_link = $item['author-link'];
314 if (strpos($profile_link, 'contact/redir/') === 0) {
315 $sparkle = ' sparkle';
318 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
319 Hook::callAll('render_location', $locate);
320 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
322 // process action responses - e.g. like/dislike/attend/agree/whatever
323 $response_verbs = ['like', 'dislike', 'announce'];
327 if ($item['object-type'] === Activity\ObjectType::EVENT) {
328 $response_verbs[] = 'attendyes';
329 $response_verbs[] = 'attendno';
330 $response_verbs[] = 'attendmaybe';
332 if ($conv->isWritable()) {
334 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
339 foreach ($response_verbs as $value => $verb) {
340 $responses[$verb] = [
341 'self' => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
342 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? DI::conversation()->formatActivity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
347 * We should avoid doing this all the time, but it depends on the conversation mode
348 * And the conv mode may change when we change the conv, or it changes its mode
349 * Maybe we should establish a way to be notified about conversation changes
351 $this->checkWallToWall();
353 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
354 $osparkle = ' sparkle';
359 if ($this->isToplevel()) {
360 if (DI::userSession()->getLocalUserId()) {
361 $ignored_thread = PostModel\ThreadUser::getIgnored($item['uri-id'], DI::userSession()->getLocalUserId());
362 if ($item['mention'] || $ignored_thread) {
364 'do' => DI::l10n()->t('Ignore thread'),
365 'undo' => DI::l10n()->t('Unignore thread'),
366 'toggle' => DI::l10n()->t('Toggle ignore status'),
367 'classdo' => $ignored_thread ? 'hidden' : '',
368 'classundo' => $ignored_thread ? '' : 'hidden',
369 'ignored' => DI::l10n()->t('Ignored'),
373 $isstarred = (($item['starred']) ? 'starred' : 'unstarred');
376 'do' => DI::l10n()->t('Add star'),
377 'undo' => DI::l10n()->t('Remove star'),
378 'toggle' => DI::l10n()->t('Toggle star status'),
379 'classdo' => $item['starred'] ? 'hidden' : '',
380 'classundo' => $item['starred'] ? '' : 'hidden',
381 'starred' => DI::l10n()->t('Starred'),
384 if ($conv->getProfileOwner() == DI::userSession()->getLocalUserId() && ($item['uid'] != 0)) {
385 if ($origin && in_array($item['private'], [Item::PUBLIC, Item::UNLISTED])) {
386 $ispinned = ($item['featured'] ? 'pinned' : 'unpinned');
389 'do' => DI::l10n()->t('Pin'),
390 'undo' => DI::l10n()->t('Unpin'),
391 'toggle' => DI::l10n()->t('Toggle pin status'),
392 'classdo' => $item['featured'] ? 'hidden' : '',
393 'classundo' => $item['featured'] ? '' : 'hidden',
394 'pinned' => DI::l10n()->t('Pinned'),
399 'add' => DI::l10n()->t('Add tag'),
408 if ($conv->isWritable()) {
409 $buttons['like'] = [DI::l10n()->t("I like this \x28toggle\x29"), DI::l10n()->t('Like')];
410 $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t('Dislike')];
412 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
415 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
416 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
421 $comment_html = $this->getCommentBox($indent);
426 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
430 DI::contentItem()->localize($item);
432 $body_html = Item::prepareBody($item, true);
434 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, DI::userSession()->getLocalUserId());
436 if (!empty($item['title'])) {
437 $title = $item['title'];
438 } elseif (!empty($item['content-warning']) && DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false)) {
439 $title = ucfirst($item['content-warning']);
444 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike')) {
445 $buttons['dislike'] = false;
448 // Disable features that aren't available in several networks
449 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
450 if ($buttons['dislike']) {
451 $buttons['dislike'] = false;
458 if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
459 $buttons['like'] = false;
462 $tags = Tag::populateFromItem($item);
464 $ago = Temporal::getRelativeDate($item['created']);
465 $ago_received = Temporal::getRelativeDate($item['received']);
466 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
467 $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
470 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
471 if (!DI::userSession()->getLocalUserId() && ($item['network'] != Protocol::DIASPORA) && !empty(DI::session()->get('remote_comment'))) {
473 DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('Remote comment'),
474 str_replace('{uri}', urlencode($item['uri']), DI::session()->get('remote_comment'))
477 // Ensure to either display the remote comment or the local activities
481 $remote_comment = '';
485 if (!empty($item['direction'])) {
486 $direction = $item['direction'];
490 if (!empty($item['language'])) {
491 $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
494 if (in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($item['network'], Protocol::FEDERATED)) {
495 $browsershare = [DI::l10n()->t('Share via ...'), DI::l10n()->t('Share via external services')];
497 $browsershare = null;
501 'template' => $this->getTemplate(),
502 'type' => implode('', array_slice(explode('/', $item['verb']), -1)),
503 'comment_firstcollapsed' => false,
504 'comment_lastcollapsed' => false,
505 'suppress_tags' => DI::config()->get('system', 'suppress_tags'),
506 'tags' => $tags['tags'],
507 'hashtags' => $tags['hashtags'],
508 'mentions' => $tags['mentions'],
509 'implicit_mentions' => $tags['implicit_mentions'],
510 'txt_cats' => DI::l10n()->t('Categories:'),
511 'txt_folders' => DI::l10n()->t('Filed under:'),
512 'has_cats' => ((count($categories)) ? 'true' : ''),
513 'has_folders' => ((count($folders)) ? 'true' : ''),
514 'categories' => $categories,
515 'folders' => $folders,
516 'body_html' => $body_html,
517 'text' => strip_tags($body_html),
518 'id' => $this->getId(),
519 'guid' => urlencode($item['guid']),
520 'isevent' => $isevent,
522 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
523 'olinktitle' => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
524 'to' => DI::l10n()->t('to'),
525 'via' => DI::l10n()->t('via'),
526 'wall' => DI::l10n()->t('Wall-to-Wall'),
527 'vwall' => DI::l10n()->t('via Wall-To-Wall:'),
528 'profile_url' => $profile_link,
529 'name' => $profile_name,
530 'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
531 'thumb' => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)),
532 'osparkle' => $osparkle,
533 'sparkle' => $sparkle,
535 'localtime' => DateTimeFormat::local($item['created'], 'r'),
536 'ago' => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
537 'app' => $item['app'],
540 'private' => $item['private'],
541 'privacy' => $privacy,
542 'connector' => $connector,
543 'location_html' => $location_html,
546 'owner_self' => $item['author-link'] == DI::session()->get('my_url'),
547 'owner_url' => $this->getOwnerUrl(),
548 'owner_photo' => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)),
549 'owner_name' => $this->getOwnerName(),
550 'plink' => Item::getPlink($item),
551 'browsershare' => $browsershare,
553 'ispinned' => $ispinned,
556 'isstarred' => $isstarred,
558 'ignore' => $ignore_thread,
561 'language' => $languages,
564 'ignore_author' => $ignore,
565 'collapse' => $collapse,
567 'ignore_server' => $ignoreServer,
569 'like_html' => $responses['like']['output'],
570 'dislike_html' => $responses['dislike']['output'],
571 'emojis' => $this->getEmojis($item),
572 'responses' => $responses,
573 'switchcomment' => DI::l10n()->t('Comment'),
574 'reply_label' => DI::l10n()->t('Reply to %s', $profile_name),
575 'comment_html' => $comment_html,
576 'remote_comment' => $remote_comment,
577 'menu' => DI::l10n()->t('More'),
578 'previewing' => $conv->isPreview() ? ' preview ' : '',
579 'wait' => DI::l10n()->t('Please wait'),
580 'thread_level' => $thread_level,
582 'author_gsid' => $item['author-gsid'],
583 'network' => $item['network'],
584 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
585 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
586 'received' => $item['received'],
587 'commented' => $item['commented'],
588 'created_date' => $item['created'],
589 'uriid' => $item['uri-id'],
590 'return' => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
591 'direction' => $direction,
592 'reshared' => $item['reshared'] ?? '',
594 'queue_count' => $item['delivery_queue_count'],
595 'queue_done' => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
596 'notifier_pending' => DI::l10n()->t('Notifier task is pending'),
597 'delivery_pending' => DI::l10n()->t('Delivery to remote servers is pending'),
598 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
599 'delivery_almost' => DI::l10n()->t('Delivery to remote servers is mostly done'),
600 'delivery_done' => DI::l10n()->t('Delivery to remote servers is done'),
604 $arr = ['item' => $item, 'output' => $tmp_item];
605 Hook::callAll('display_item', $arr);
607 $result = $arr['output'];
609 $result['children'] = [];
610 $children = $this->getChildren();
611 $nb_children = count($children);
612 if ($nb_children > 0) {
613 foreach ($children as $child) {
614 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1);
618 if (($nb_children > 2) || ($thread_level > 1)) {
619 $result['children'][0]['comment_firstcollapsed'] = true;
620 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
621 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
622 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
623 if ($thread_level > 1) {
624 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
626 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
631 // Copy values/set defaults
632 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
633 $result['private'] = $item['private'];
634 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
635 $result['flatten'] = !$this->isThreaded();
636 $result['threaded'] = $this->isThreaded();
647 private function getEmojis(array $item): array
649 if (empty($item['emojis'])) {
654 foreach ($item['emojis'] as $index => $element) {
655 $actors = implode(', ', $element['title']);
656 switch ($element['verb']) {
657 case Activity::ANNOUNCE:
658 $title = DI::l10n()->t('Reshared by: %s', $actors);
659 $icon = ['fa' => 'fa-retweet', 'icon' => 'icon-retweet'];
663 $title = DI::l10n()->t('Viewed by: %s', $actors);
664 $icon = ['fa' => 'fa-eye', 'icon' => 'icon-eye-open'];
668 $title = DI::l10n()->t('Liked by: %s', $actors);
669 $icon = ['fa' => 'fa-thumbs-up', 'icon' => 'icon-thumbs-up'];
672 case Activity::DISLIKE:
673 $title = DI::l10n()->t('Disliked by: %s', $actors);
674 $icon = ['fa' => 'fa-thumbs-down', 'icon' => 'icon-thumbs-down'];
677 case Activity::ATTEND:
678 $title = DI::l10n()->t('Attended by: %s', $actors);
679 $icon = ['fa' => 'fa-check', 'icon' => 'icon-ok'];
682 case Activity::ATTENDMAYBE:
683 $title = DI::l10n()->t('Maybe attended by: %s', $actors);
684 $icon = ['fa' => 'fa-question', 'icon' => 'icon-question'];
687 case Activity::ATTENDNO:
688 $title = DI::l10n()->t('Not attended by: %s', $actors);
689 $icon = ['fa' => 'fa-times', 'icon' => 'icon-remove'];
693 $title = DI::l10n()->t('Reacted with %s by: %s', $element['emoji'], $actors);
697 $emojis[$index] = ['emoji' => $element['emoji'], 'total' => $element['total'], 'title' => $title, 'icon' => $icon];
707 public function getId(): int
709 return $this->getDataValue('id');
715 public function isThreaded(): bool
717 return $this->threaded;
723 * @param Post $item The child post to add
725 * @return Post|bool Last Post object or bool on any error
728 public function addChild(Post $item)
730 if (!$item->getId()) {
731 Logger::error('Post object has no id', ['post' => $item]);
733 } elseif ($this->getChild($item->getId())) {
734 Logger::warning('Post object already exists', ['post' => $item]);
739 * Only add what will be displayed
741 if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) {
742 Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]);
745 DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) ||
746 DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE)
748 Logger::warning('Post objects is a like/dislike', ['post' => $item]);
752 $item->setParent($this);
753 $this->children[] = $item;
755 return end($this->children);
759 * Get a child by its ID
761 * @param integer $id The child id
762 * @return Thread|null Thread or NULL if not found
764 public function getChild(int $id)
766 foreach ($this->getChildren() as $child) {
767 if ($child->getId() == $id) {
776 * Get all our children
780 public function getChildren(): array
782 return $this->children;
788 * @param Post $item The item to set as parent
791 protected function setParent(Post $item)
793 $parent = $this->getParent();
795 $parent->removeChild($this);
798 $this->parent = $item;
799 $this->setThread($item->getThread());
807 protected function removeParent()
809 $this->parent = null;
810 $this->thread = null;
816 * @param Post $item The child to be removed
817 * @return boolean Success or failure
820 public function removeChild(Post $item): bool
822 $id = $item->getId();
823 foreach ($this->getChildren() as $key => $child) {
824 if ($child->getId() == $id) {
825 $child->removeParent();
826 unset($this->children[$key]);
827 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
828 $this->children = array_values($this->children);
833 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
842 protected function getParent()
844 return $this->parent;
848 * Set conversation thread
850 * @param Thread|null $thread
854 public function setThread(Thread $thread = null)
856 $this->thread = $thread;
858 // Set it on our children too
859 foreach ($this->getChildren() as $child) {
860 $child->setThread($thread);
867 * @return Thread|null
869 public function getThread()
871 return $this->thread;
877 * We shouldn't need this
881 public function getData(): array
889 * @param string $name key
891 * @return mixed value on success, false on failure
893 public function getDataValue(string $name)
895 if (!isset($this->data[$name])) {
896 // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
900 return $this->data[$name];
904 * Set template by name
906 * @param string $name Template name
909 * @throws InvalidArgumentException
911 private function setTemplate(string $name)
913 if (empty($this->available_templates[$name])) {
915 throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
918 $this->template = $this->available_templates[$name];
926 private function getTemplate()
928 return $this->template;
932 * Check if this is a toplevel post
936 private function isToplevel(): bool
938 return $this->toplevel;
942 * Check if this is writable
946 private function isWritable(): bool
948 $conv = $this->getThread();
951 // This will allow us to comment on wall-to-wall items owned by our friends
952 // and community groups even if somebody else wrote the post.
953 // bug #517 - this fixes for conversation owner
954 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == DI::userSession()->getLocalUserId()) {
958 // this fixes for visitors
959 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
961 return $this->writable;
965 * Count the total of our descendants
969 private function countDescendants(): int
971 $children = $this->getChildren();
972 $total = count($children);
974 foreach ($children as $child) {
975 $total += $child->countDescendants();
983 * Get the template for the comment box
987 private function getCommentBoxTemplate(): string
989 return $this->comment_box_template;
993 * Get default text for the comment box
996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
998 private function getDefaultText(): string
1002 if (!DI::userSession()->getLocalUserId()) {
1006 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1007 $item = $this->getData();
1009 if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), 'add_abstract')) {
1010 $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
1015 if (!Feature::isEnabled(DI::userSession()->getLocalUserId(), 'explicit_mentions')) {
1019 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != Item::GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
1020 $text .= '@' . $item['author-addr'] . ' ';
1023 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1024 foreach ($terms as $term) {
1025 if (!$term['url']) {
1026 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
1030 $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
1032 !empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
1033 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])
1035 $text .= '@' . $profile['addr'] . ' ';
1043 * Get the comment box
1045 * @param string $indent Indent value
1047 * @return mixed The comment box string (empty if no comment box), false on failure
1048 * @throws \Exception
1049 * @todo return false is nowhere in this method?
1051 private function getCommentBox(string $indent)
1056 $conv = $this->getThread();
1058 if ($conv->isWritable() && $this->isWritable()) {
1060 * Hmmm, code depending on the presence of a particular addon?
1061 * This should be better if done by a hook
1064 if (Addon::isEnabled('qcomment')) {
1065 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1066 $qcomment = $words ? explode("\n", $words) : [];
1069 // Fetch the user id from the parent when the owner user is empty
1070 $uid = $conv->getProfileOwner();
1071 $parent_uid = $this->getDataValue('uid');
1073 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1075 $default_text = $this->getDefaultText();
1077 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
1081 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
1082 $comment_box = Renderer::replaceMacros($template, [
1083 '$return_path' => DI::args()->getQueryString(),
1084 '$threaded' => $this->isThreaded(),
1086 '$wall' => ($conv->getMode() === 'profile'),
1087 '$id' => $this->getId(),
1088 '$parent' => $this->getId(),
1089 '$qcomment' => $qcomment,
1090 '$default' => $default_text,
1091 '$profile_uid' => $uid,
1092 '$mylink' => DI::baseUrl()->remove($owner['url'] ?? ''),
1093 '$mytitle' => DI::l10n()->t('This is you'),
1094 '$myphoto' => DI::baseUrl()->remove($owner['thumb'] ?? ''),
1095 '$comment' => DI::l10n()->t('Comment'),
1096 '$submit' => DI::l10n()->t('Submit'),
1097 '$loading' => DI::l10n()->t('Loading...'),
1098 '$edbold' => DI::l10n()->t('Bold'),
1099 '$editalic' => DI::l10n()->t('Italic'),
1100 '$eduline' => DI::l10n()->t('Underline'),
1101 '$contentwarn' => DI::l10n()->t('Content Warning'),
1102 '$edquote' => DI::l10n()->t('Quote'),
1103 '$edemojis' => DI::l10n()->t('Add emojis'),
1104 '$edcode' => DI::l10n()->t('Code'),
1105 '$edimg' => DI::l10n()->t('Image'),
1106 '$edurl' => DI::l10n()->t('Link'),
1107 '$edattach' => DI::l10n()->t('Link or Media'),
1108 '$prompttext' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1109 '$preview' => DI::l10n()->t('Preview'),
1110 '$indent' => $indent,
1111 '$rand_num' => Crypto::randomDigits(12)
1115 return $comment_box;
1121 private function getRedirectUrl(): string
1123 return $this->redirect_url;
1127 * Check if we are a wall to wall item and set the relevant properties
1130 * @throws \Exception
1132 protected function checkWallToWall()
1135 $conv = $this->getThread();
1136 $this->wall_to_wall = false;
1138 if ($this->isToplevel()) {
1139 if ($conv->getMode() !== 'profile') {
1140 if ($this->getDataValue('owner-link')) {
1141 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1142 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1143 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1145 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1147 * The author url doesn't match the owner (typically the contact)
1148 * and also doesn't match the contact alias.
1149 * The name match is a hack to catch several weird cases where URLs are
1150 * all over the park. It can be tricked, but this prevents you from
1151 * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1152 * well that it's the same Bob Smith.
1153 * But it could be somebody else with the same name. It just isn't highly likely.
1155 $this->owner_name = $this->getDataValue('owner-name');
1156 $this->wall_to_wall = true;
1160 'id' => $this->getDataValue('owner-id'),
1161 'network' => $this->getDataValue('owner-network'),
1162 'url' => $this->getDataValue('owner-link'),
1163 'alias' => $this->getDataValue('owner-alias'),
1165 $this->owner_url = Contact::magicLinkByContact($owner);
1171 if (!$this->wall_to_wall) {
1172 $this->setTemplate('wall');
1173 $this->owner_url = '';
1174 $this->owner_name = '';
1181 private function isWallToWall(): bool
1183 return $this->wall_to_wall;
1189 private function getOwnerUrl(): string
1191 return $this->owner_url;
1197 private function getOwnerName(): string
1199 return $this->owner_name;
1205 private function isVisiting(): bool
1207 return $this->visiting;