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\Proxy;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44 use InvalidArgumentException;
52 private $template = null;
53 private $available_templates = [
54 'wall' => 'wall_thread.tpl',
55 'wall2wall' => 'wallwall_thread.tpl'
57 private $comment_box_template = 'comment_item.tpl';
58 private $toplevel = false;
59 private $writable = false;
63 private $children = [];
64 private $parent = null;
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;
80 * @param array $data data array
83 public function __construct(array $data)
86 $this->setTemplate('wall');
87 $this->toplevel = $this->getId() == $this->getDataValue('parent');
89 if (!empty(DI::userSession()->getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
90 $this->visiting = true;
93 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
96 'id' => $this->getDataValue('author-id'),
97 'network' => $this->getDataValue('author-network'),
98 'url' => $this->getDataValue('author-link'),
99 'alias' => $this->getDataValue('author-alias')
101 $this->redirect_url = Contact::magicLinkByContact($author);
102 if (!$this->isToplevel()) {
103 $this->threaded = true;
106 // Prepare the children
107 if (!empty($data['children'])) {
108 foreach ($data['children'] as $item) {
109 // Only add will be displayed
110 if ($item['network'] === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item['uid']) {
112 } elseif (!DI::contentItem()->isVisibleActivity($item)) {
116 // You can always comment on Diaspora and OStatus items
117 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (DI::userSession()->getLocalUserId() == $item['uid'])) {
118 $item['writable'] = true;
121 $item['pagedrop'] = $data['pagedrop'];
122 $child = new Post($item);
123 $this->addChild($child);
129 * Fetch the privacy of the post
131 * @param array $item Item record
132 * @return string Item privacy message
133 * @throws InvalidArgumentException If $item['private'] is unknown
135 private function fetchPrivacy(array $item): string
137 switch ($item['private']) {
139 $output = DI::l10n()->t('Private Message');
143 $output = DI::l10n()->t('Public Message');
147 $output = DI::l10n()->t('Unlisted Message');
151 throw new InvalidArgumentException('Item privacy ' . $item['privacy'] . ' is unsupported');
158 * Get data in a form usable by a conversation template
160 * @param array $conv_responses conversation responses
161 * @param string $formSecurityToken A security Token to avoid CSF attacks
162 * @param integer $thread_level default = 1
164 * @return mixed The data requested on success, false on failure
165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
166 * @throws \ImagickException
168 public function getTemplateData(array $conv_responses, string $formSecurityToken, int $thread_level = 1)
170 $item = $this->getData();
174 * If the time between "created" and "edited" differs we add
175 * a notice that the post was edited.
176 * Note: In some networks reshared items seem to have (sometimes) a difference
177 * between creation time and edit time of a second. Thats why we add the notice
178 * only if the difference is more than 1 second.
180 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
182 'label' => DI::l10n()->t('This entry was edited'),
183 'date' => DateTimeFormat::local($item['edited'], 'r'),
184 'relative' => Temporal::getRelativeDate($item['edited']),
198 $ignore_thread = false;
199 $ispinned = 'unpinned';
200 $isstarred = 'unstarred';
204 $total_children = $this->countDescendants();
206 $conv = $this->getThread();
208 $privacy = $this->fetchPrivacy($item);
209 $lock = ($item['private'] == Item::PRIVATE) ? $privacy : false;
210 $connector = !in_array($item['network'], Protocol::NATIVE_SUPPORT) ? DI::l10n()->t('Connector Message') : false;
212 $shareable = in_array($conv->getProfileOwner(), [0, DI::userSession()->getLocalUserId()]) && $item['private'] != Item::PRIVATE;
213 $announceable = $shareable && in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::TWITTER, Protocol::TUMBLR, Protocol::BLUESKY]);
214 $commentable = ($item['network'] != Protocol::TUMBLR);
216 // On Diaspora only toplevel posts can be reshared
217 if ($announceable && ($item['network'] == Protocol::DIASPORA) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
218 $announceable = false;
223 if (DI::userSession()->getLocalUserId()) {
224 if (Strings::compareLink(DI::session()->get('my_url'), $item['author-link'])) {
225 if ($item['event-id'] != 0) {
226 $edpost = ['calendar/event/edit/' . $item['event-id'], DI::l10n()->t('Edit')];
228 $edpost = [sprintf('post/%s/edit', $item['id']), DI::l10n()->t('Edit')];
231 $dropping = in_array($item['uid'], [0, DI::userSession()->getLocalUserId()]);
234 // Editing on items of not subscribed users isn't currently possible
235 // There are some issues on editing that prevent this.
236 // But also it is an issue of the supported protocols that doesn't allow editing at all.
237 if ($item['uid'] == 0) {
241 if (($this->getDataValue('uid') == DI::userSession()->getLocalUserId()) || $this->isVisiting()) {
245 $origin = $item['origin'] || $item['parent-origin'];
247 if (!empty($item['featured'])) {
248 $pinned = DI::l10n()->t('Pinned item');
256 if (DI::userSession()->getLocalUserId()) {
258 'dropping' => $dropping,
259 'pagedrop' => $item['pagedrop'],
260 'select' => DI::l10n()->t('Select'),
261 'label' => $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally'),
265 if (!$item['self'] && DI::userSession()->getLocalUserId()) {
268 'label' => DI::l10n()->t('Block %s', $item['author-name']),
269 'author_id' => $item['author-id'],
273 'label' => DI::l10n()->t('Ignore %s', $item['author-name']),
274 'author_id' => $item['author-id'],
277 'collapsing' => true,
278 'label' => DI::l10n()->t('Collapse %s', $item['author-name']),
279 'author_id' => $item['author-id'],
282 'label' => DI::l10n()->t('Report post'),
283 'href' => 'moderation/report/create?' . http_build_query(['cid' => $item['author-id'], 'uri-ids' => [$item['uri-id']]]),
287 $filer = DI::userSession()->getLocalUserId() ? DI::l10n()->t('Save to folder') : false;
289 $profile_name = $item['author-name'];
290 if (!empty($item['author-link']) && empty($item['author-name'])) {
291 $profile_name = $item['author-link'];
294 if (DI::userSession()->isAuthenticated()) {
297 'id' => $item['author-id'],
298 'network' => $item['author-network'],
299 'url' => $item['author-link'],
300 'alias' => $item['author-alias'],
302 $profile_link = Contact::magicLinkByContact($author);
304 $profile_link = $item['author-link'];
307 if (strpos($profile_link, 'contact/redir/') === 0) {
308 $sparkle = ' sparkle';
311 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
312 Hook::callAll('render_location', $locate);
313 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
315 // process action responses - e.g. like/dislike/attend/agree/whatever
316 $response_verbs = ['like', 'dislike', 'announce'];
320 if ($item['object-type'] === Activity\ObjectType::EVENT) {
321 $response_verbs[] = 'attendyes';
322 $response_verbs[] = 'attendno';
323 $response_verbs[] = 'attendmaybe';
325 if ($conv->isWritable()) {
327 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
332 foreach ($response_verbs as $value => $verb) {
333 $responses[$verb] = [
334 'self' => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
335 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? DI::conversation()->formatActivity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
340 * We should avoid doing this all the time, but it depends on the conversation mode
341 * And the conv mode may change when we change the conv, or it changes its mode
342 * Maybe we should establish a way to be notified about conversation changes
344 $this->checkWallToWall();
346 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
347 $osparkle = ' sparkle';
352 if ($this->isToplevel()) {
353 if (DI::userSession()->getLocalUserId()) {
354 $ignored_thread = PostModel\ThreadUser::getIgnored($item['uri-id'], DI::userSession()->getLocalUserId());
355 if ($item['mention'] || $ignored_thread) {
357 'do' => DI::l10n()->t('Ignore thread'),
358 'undo' => DI::l10n()->t('Unignore thread'),
359 'toggle' => DI::l10n()->t('Toggle ignore status'),
360 'classdo' => $ignored_thread ? 'hidden' : '',
361 'classundo' => $ignored_thread ? '' : 'hidden',
362 'ignored' => DI::l10n()->t('Ignored'),
366 $isstarred = (($item['starred']) ? 'starred' : 'unstarred');
369 'do' => DI::l10n()->t('Add star'),
370 'undo' => DI::l10n()->t('Remove star'),
371 'toggle' => DI::l10n()->t('Toggle star status'),
372 'classdo' => $item['starred'] ? 'hidden' : '',
373 'classundo' => $item['starred'] ? '' : 'hidden',
374 'starred' => DI::l10n()->t('Starred'),
377 if ($conv->getProfileOwner() == DI::userSession()->getLocalUserId() && ($item['uid'] != 0)) {
378 if ($origin && in_array($item['private'], [Item::PUBLIC, Item::UNLISTED])) {
379 $ispinned = ($item['featured'] ? 'pinned' : 'unpinned');
382 'do' => DI::l10n()->t('Pin'),
383 'undo' => DI::l10n()->t('Unpin'),
384 'toggle' => DI::l10n()->t('Toggle pin status'),
385 'classdo' => $item['featured'] ? 'hidden' : '',
386 'classundo' => $item['featured'] ? '' : 'hidden',
387 'pinned' => DI::l10n()->t('Pinned'),
392 'add' => DI::l10n()->t('Add tag'),
401 if ($conv->isWritable()) {
402 $buttons['like'] = [DI::l10n()->t("I like this \x28toggle\x29"), DI::l10n()->t('Like')];
403 $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t('Dislike')];
405 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
408 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
409 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
414 $comment_html = $this->getCommentBox($indent);
419 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
423 DI::contentItem()->localize($item);
425 $body_html = Item::prepareBody($item, true);
427 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, DI::userSession()->getLocalUserId());
429 if (!empty($item['title'])) {
430 $title = $item['title'];
431 } elseif (!empty($item['content-warning']) && DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false)) {
432 $title = ucfirst($item['content-warning']);
437 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike')) {
438 $buttons['dislike'] = false;
441 // Disable features that aren't available in several networks
442 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
443 if ($buttons['dislike']) {
444 $buttons['dislike'] = false;
451 if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
452 $buttons['like'] = false;
455 $tags = Tag::populateFromItem($item);
457 $ago = Temporal::getRelativeDate($item['created']);
458 $ago_received = Temporal::getRelativeDate($item['received']);
459 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
460 $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
463 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
464 if (!DI::userSession()->getLocalUserId() && ($item['network'] != Protocol::DIASPORA) && !empty(DI::session()->get('remote_comment'))) {
466 DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('Remote comment'),
467 str_replace('{uri}', urlencode($item['uri']), DI::session()->get('remote_comment'))
470 // Ensure to either display the remote comment or the local activities
474 $remote_comment = '';
478 if (!empty($item['direction'])) {
479 $direction = $item['direction'];
483 if (!empty($item['language'])) {
484 $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
487 if (in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($item['network'], Protocol::FEDERATED)) {
488 $browsershare = [DI::l10n()->t('Share via ...'), DI::l10n()->t('Share via external services')];
490 $browsershare = null;
494 'template' => $this->getTemplate(),
495 'type' => implode('', array_slice(explode('/', $item['verb']), -1)),
496 'comment_firstcollapsed' => false,
497 'comment_lastcollapsed' => false,
498 'suppress_tags' => DI::config()->get('system', 'suppress_tags'),
499 'tags' => $tags['tags'],
500 'hashtags' => $tags['hashtags'],
501 'mentions' => $tags['mentions'],
502 'implicit_mentions' => $tags['implicit_mentions'],
503 'txt_cats' => DI::l10n()->t('Categories:'),
504 'txt_folders' => DI::l10n()->t('Filed under:'),
505 'has_cats' => ((count($categories)) ? 'true' : ''),
506 'has_folders' => ((count($folders)) ? 'true' : ''),
507 'categories' => $categories,
508 'folders' => $folders,
509 'body_html' => $body_html,
510 'text' => strip_tags($body_html),
511 'id' => $this->getId(),
512 'guid' => urlencode($item['guid']),
513 'isevent' => $isevent,
515 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
516 'olinktitle' => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
517 'to' => DI::l10n()->t('to'),
518 'via' => DI::l10n()->t('via'),
519 'wall' => DI::l10n()->t('Wall-to-Wall'),
520 'vwall' => DI::l10n()->t('via Wall-To-Wall:'),
521 'profile_url' => $profile_link,
522 'name' => $profile_name,
523 'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
524 'thumb' => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)),
525 'osparkle' => $osparkle,
526 'sparkle' => $sparkle,
528 'localtime' => DateTimeFormat::local($item['created'], 'r'),
529 'ago' => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
530 'app' => $item['app'],
533 'private' => $item['private'],
534 'privacy' => $privacy,
535 'connector' => $connector,
536 'location_html' => $location_html,
539 'owner_self' => $item['author-link'] == DI::session()->get('my_url'),
540 'owner_url' => $this->getOwnerUrl(),
541 'owner_photo' => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)),
542 'owner_name' => $this->getOwnerName(),
543 'plink' => Item::getPlink($item),
544 'browsershare' => $browsershare,
546 'ispinned' => $ispinned,
549 'isstarred' => $isstarred,
551 'ignore' => $ignore_thread,
554 'language' => $languages,
557 'ignore_author' => $ignore,
558 'collapse' => $collapse,
561 'like_html' => $responses['like']['output'],
562 'dislike_html' => $responses['dislike']['output'],
563 'emojis' => $this->getEmojis($item),
564 'responses' => $responses,
565 'switchcomment' => DI::l10n()->t('Comment'),
566 'reply_label' => DI::l10n()->t('Reply to %s', $profile_name),
567 'comment_html' => $comment_html,
568 'remote_comment' => $remote_comment,
569 'menu' => DI::l10n()->t('More'),
570 'previewing' => $conv->isPreview() ? ' preview ' : '',
571 'wait' => DI::l10n()->t('Please wait'),
572 'thread_level' => $thread_level,
574 'network' => $item['network'],
575 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
576 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
577 'received' => $item['received'],
578 'commented' => $item['commented'],
579 'created_date' => $item['created'],
580 'uriid' => $item['uri-id'],
581 'return' => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
582 'direction' => $direction,
583 'reshared' => $item['reshared'] ?? '',
585 'queue_count' => $item['delivery_queue_count'],
586 'queue_done' => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
587 'notifier_pending' => DI::l10n()->t('Notifier task is pending'),
588 'delivery_pending' => DI::l10n()->t('Delivery to remote servers is pending'),
589 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
590 'delivery_almost' => DI::l10n()->t('Delivery to remote servers is mostly done'),
591 'delivery_done' => DI::l10n()->t('Delivery to remote servers is done'),
595 $arr = ['item' => $item, 'output' => $tmp_item];
596 Hook::callAll('display_item', $arr);
598 $result = $arr['output'];
600 $result['children'] = [];
601 $children = $this->getChildren();
602 $nb_children = count($children);
603 if ($nb_children > 0) {
604 foreach ($children as $child) {
605 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1);
609 if (($nb_children > 2) || ($thread_level > 1)) {
610 $result['children'][0]['comment_firstcollapsed'] = true;
611 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
612 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
613 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
614 if ($thread_level > 1) {
615 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
617 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
622 // Copy values/set defaults
623 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
624 $result['private'] = $item['private'];
625 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
626 $result['flatten'] = !$this->isThreaded();
627 $result['threaded'] = $this->isThreaded();
638 private function getEmojis(array $item): array
640 if (empty($item['emojis'])) {
645 foreach ($item['emojis'] as $index => $element) {
646 $actors = implode(', ', $element['title']);
647 switch ($element['verb']) {
648 case Activity::ANNOUNCE:
649 $title = DI::l10n()->t('Reshared by: %s', $actors);
650 $icon = ['fa' => 'fa-retweet', 'icon' => 'icon-retweet'];
654 $title = DI::l10n()->t('Viewed by: %s', $actors);
655 $icon = ['fa' => 'fa-eye', 'icon' => 'icon-eye-open'];
659 $title = DI::l10n()->t('Liked by: %s', $actors);
660 $icon = ['fa' => 'fa-thumbs-up', 'icon' => 'icon-thumbs-up'];
663 case Activity::DISLIKE:
664 $title = DI::l10n()->t('Disliked by: %s', $actors);
665 $icon = ['fa' => 'fa-thumbs-down', 'icon' => 'icon-thumbs-down'];
668 case Activity::ATTEND:
669 $title = DI::l10n()->t('Attended by: %s', $actors);
670 $icon = ['fa' => 'fa-check', 'icon' => 'icon-ok'];
673 case Activity::ATTENDMAYBE:
674 $title = DI::l10n()->t('Maybe attended by: %s', $actors);
675 $icon = ['fa' => 'fa-question', 'icon' => 'icon-question'];
678 case Activity::ATTENDNO:
679 $title = DI::l10n()->t('Not attended by: %s', $actors);
680 $icon = ['fa' => 'fa-times', 'icon' => 'icon-remove'];
684 $title = DI::l10n()->t('Reacted with %s by: %s', $element['emoji'], $actors);
688 $emojis[$index] = ['emoji' => $element['emoji'], 'total' => $element['total'], 'title' => $title, 'icon' => $icon];
698 public function getId(): int
700 return $this->getDataValue('id');
706 public function isThreaded(): bool
708 return $this->threaded;
714 * @param Post $item The child post to add
716 * @return Post|bool Last Post object or bool on any error
719 public function addChild(Post $item)
721 if (!$item->getId()) {
722 Logger::error('Post object has no id', ['post' => $item]);
724 } elseif ($this->getChild($item->getId())) {
725 Logger::warning('Post object already exists', ['post' => $item]);
730 * Only add what will be displayed
732 if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) {
733 Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]);
736 DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) ||
737 DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE)
739 Logger::warning('Post objects is a like/dislike', ['post' => $item]);
743 $item->setParent($this);
744 $this->children[] = $item;
746 return end($this->children);
750 * Get a child by its ID
752 * @param integer $id The child id
753 * @return Thread|null Thread or NULL if not found
755 public function getChild(int $id)
757 foreach ($this->getChildren() as $child) {
758 if ($child->getId() == $id) {
767 * Get all our children
771 public function getChildren(): array
773 return $this->children;
779 * @param Post $item The item to set as parent
782 protected function setParent(Post $item)
784 $parent = $this->getParent();
786 $parent->removeChild($this);
789 $this->parent = $item;
790 $this->setThread($item->getThread());
798 protected function removeParent()
800 $this->parent = null;
801 $this->thread = null;
807 * @param Post $item The child to be removed
808 * @return boolean Success or failure
811 public function removeChild(Post $item): bool
813 $id = $item->getId();
814 foreach ($this->getChildren() as $key => $child) {
815 if ($child->getId() == $id) {
816 $child->removeParent();
817 unset($this->children[$key]);
818 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
819 $this->children = array_values($this->children);
824 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
833 protected function getParent()
835 return $this->parent;
839 * Set conversation thread
841 * @param Thread|null $thread
845 public function setThread(Thread $thread = null)
847 $this->thread = $thread;
849 // Set it on our children too
850 foreach ($this->getChildren() as $child) {
851 $child->setThread($thread);
858 * @return Thread|null
860 public function getThread()
862 return $this->thread;
868 * We shouldn't need this
872 public function getData(): array
880 * @param string $name key
882 * @return mixed value on success, false on failure
884 public function getDataValue(string $name)
886 if (!isset($this->data[$name])) {
887 // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
891 return $this->data[$name];
895 * Set template by name
897 * @param string $name Template name
900 * @throws InvalidArgumentException
902 private function setTemplate(string $name)
904 if (empty($this->available_templates[$name])) {
906 throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
909 $this->template = $this->available_templates[$name];
917 private function getTemplate()
919 return $this->template;
923 * Check if this is a toplevel post
927 private function isToplevel(): bool
929 return $this->toplevel;
933 * Check if this is writable
937 private function isWritable(): bool
939 $conv = $this->getThread();
942 // This will allow us to comment on wall-to-wall items owned by our friends
943 // and community groups even if somebody else wrote the post.
944 // bug #517 - this fixes for conversation owner
945 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == DI::userSession()->getLocalUserId()) {
949 // this fixes for visitors
950 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
952 return $this->writable;
956 * Count the total of our descendants
960 private function countDescendants(): int
962 $children = $this->getChildren();
963 $total = count($children);
965 foreach ($children as $child) {
966 $total += $child->countDescendants();
974 * Get the template for the comment box
978 private function getCommentBoxTemplate(): string
980 return $this->comment_box_template;
984 * Get default text for the comment box
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989 private function getDefaultText(): string
993 if (!DI::userSession()->getLocalUserId()) {
997 $owner = User::getOwnerDataById($a->getLoggedInUserId());
998 $item = $this->getData();
1000 if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), 'add_abstract')) {
1001 $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
1006 if (!Feature::isEnabled(DI::userSession()->getLocalUserId(), 'explicit_mentions')) {
1010 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != Item::GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
1011 $text .= '@' . $item['author-addr'] . ' ';
1014 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1015 foreach ($terms as $term) {
1016 if (!$term['url']) {
1017 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
1021 $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
1023 !empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
1024 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])
1026 $text .= '@' . $profile['addr'] . ' ';
1034 * Get the comment box
1036 * @param string $indent Indent value
1038 * @return mixed The comment box string (empty if no comment box), false on failure
1039 * @throws \Exception
1040 * @todo return false is nowhere in this method?
1042 private function getCommentBox(string $indent)
1047 $conv = $this->getThread();
1049 if ($conv->isWritable() && $this->isWritable()) {
1051 * Hmmm, code depending on the presence of a particular addon?
1052 * This should be better if done by a hook
1055 if (Addon::isEnabled('qcomment')) {
1056 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1057 $qcomment = $words ? explode("\n", $words) : [];
1060 // Fetch the user id from the parent when the owner user is empty
1061 $uid = $conv->getProfileOwner();
1062 $parent_uid = $this->getDataValue('uid');
1064 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1066 $default_text = $this->getDefaultText();
1068 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
1072 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
1073 $comment_box = Renderer::replaceMacros($template, [
1074 '$return_path' => DI::args()->getQueryString(),
1075 '$threaded' => $this->isThreaded(),
1077 '$wall' => ($conv->getMode() === 'profile'),
1078 '$id' => $this->getId(),
1079 '$parent' => $this->getId(),
1080 '$qcomment' => $qcomment,
1081 '$default' => $default_text,
1082 '$profile_uid' => $uid,
1083 '$mylink' => DI::baseUrl()->remove($owner['url'] ?? ''),
1084 '$mytitle' => DI::l10n()->t('This is you'),
1085 '$myphoto' => DI::baseUrl()->remove($owner['thumb'] ?? ''),
1086 '$comment' => DI::l10n()->t('Comment'),
1087 '$submit' => DI::l10n()->t('Submit'),
1088 '$loading' => DI::l10n()->t('Loading...'),
1089 '$edbold' => DI::l10n()->t('Bold'),
1090 '$editalic' => DI::l10n()->t('Italic'),
1091 '$eduline' => DI::l10n()->t('Underline'),
1092 '$contentwarn' => DI::l10n()->t('Content Warning'),
1093 '$edquote' => DI::l10n()->t('Quote'),
1094 '$edemojis' => DI::l10n()->t('Add emojis'),
1095 '$edcode' => DI::l10n()->t('Code'),
1096 '$edimg' => DI::l10n()->t('Image'),
1097 '$edurl' => DI::l10n()->t('Link'),
1098 '$edattach' => DI::l10n()->t('Link or Media'),
1099 '$prompttext' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1100 '$preview' => DI::l10n()->t('Preview'),
1101 '$indent' => $indent,
1102 '$rand_num' => Crypto::randomDigits(12)
1106 return $comment_box;
1112 private function getRedirectUrl(): string
1114 return $this->redirect_url;
1118 * Check if we are a wall to wall item and set the relevant properties
1121 * @throws \Exception
1123 protected function checkWallToWall()
1126 $conv = $this->getThread();
1127 $this->wall_to_wall = false;
1129 if ($this->isToplevel()) {
1130 if ($conv->getMode() !== 'profile') {
1131 if ($this->getDataValue('owner-link')) {
1132 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1133 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1134 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1136 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1138 * The author url doesn't match the owner (typically the contact)
1139 * and also doesn't match the contact alias.
1140 * The name match is a hack to catch several weird cases where URLs are
1141 * all over the park. It can be tricked, but this prevents you from
1142 * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1143 * well that it's the same Bob Smith.
1144 * But it could be somebody else with the same name. It just isn't highly likely.
1146 $this->owner_name = $this->getDataValue('owner-name');
1147 $this->wall_to_wall = true;
1151 'id' => $this->getDataValue('owner-id'),
1152 'network' => $this->getDataValue('owner-network'),
1153 'url' => $this->getDataValue('owner-link'),
1154 'alias' => $this->getDataValue('owner-alias'),
1156 $this->owner_url = Contact::magicLinkByContact($owner);
1162 if (!$this->wall_to_wall) {
1163 $this->setTemplate('wall');
1164 $this->owner_url = '';
1165 $this->owner_name = '';
1172 private function isWallToWall(): bool
1174 return $this->wall_to_wall;
1180 private function getOwnerUrl(): string
1182 return $this->owner_url;
1188 private function getOwnerName(): string
1190 return $this->owner_name;
1196 private function isVisiting(): bool
1198 return $this->visiting;