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');
251 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
252 $delete = $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally');
258 if (DI::userSession()->getLocalUserId()) {
260 'dropping' => $dropping,
261 'pagedrop' => $item['pagedrop'],
262 'select' => DI::l10n()->t('Select'),
267 if (!$item['self'] && DI::userSession()->getLocalUserId()) {
270 'block' => DI::l10n()->t('Block %s', $item['author-name']),
271 'author_id' => $item['author-id'],
275 'ignore' => DI::l10n()->t('Ignore %s', $item['author-name']),
276 'author_id' => $item['author-id'],
279 'collapsing' => true,
280 'collapse' => DI::l10n()->t('Collapse %s', $item['author-name']),
281 'author_id' => $item['author-id'],
285 $filer = DI::userSession()->getLocalUserId() ? DI::l10n()->t('Save to folder') : false;
287 $profile_name = $item['author-name'];
288 if (!empty($item['author-link']) && empty($item['author-name'])) {
289 $profile_name = $item['author-link'];
292 if (DI::userSession()->isAuthenticated()) {
295 'id' => $item['author-id'],
296 'network' => $item['author-network'],
297 'url' => $item['author-link'],
298 'alias' => $item['author-alias'],
300 $profile_link = Contact::magicLinkByContact($author);
302 $profile_link = $item['author-link'];
305 if (strpos($profile_link, 'contact/redir/') === 0) {
306 $sparkle = ' sparkle';
309 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
310 Hook::callAll('render_location', $locate);
311 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
313 // process action responses - e.g. like/dislike/attend/agree/whatever
314 $response_verbs = ['like', 'dislike', 'announce'];
318 if ($item['object-type'] === Activity\ObjectType::EVENT) {
319 $response_verbs[] = 'attendyes';
320 $response_verbs[] = 'attendno';
321 $response_verbs[] = 'attendmaybe';
323 if ($conv->isWritable()) {
325 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
330 foreach ($response_verbs as $value => $verb) {
331 $responses[$verb] = [
332 'self' => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
333 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? DI::conversation()->formatActivity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
338 * We should avoid doing this all the time, but it depends on the conversation mode
339 * And the conv mode may change when we change the conv, or it changes its mode
340 * Maybe we should establish a way to be notified about conversation changes
342 $this->checkWallToWall();
344 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
345 $osparkle = ' sparkle';
350 if ($this->isToplevel()) {
351 if (DI::userSession()->getLocalUserId()) {
352 $ignored_thread = PostModel\ThreadUser::getIgnored($item['uri-id'], DI::userSession()->getLocalUserId());
353 if ($item['mention'] || $ignored_thread) {
355 'do' => DI::l10n()->t('Ignore thread'),
356 'undo' => DI::l10n()->t('Unignore thread'),
357 'toggle' => DI::l10n()->t('Toggle ignore status'),
358 'classdo' => $ignored_thread ? 'hidden' : '',
359 'classundo' => $ignored_thread ? '' : 'hidden',
360 'ignored' => DI::l10n()->t('Ignored'),
364 $isstarred = (($item['starred']) ? 'starred' : 'unstarred');
367 'do' => DI::l10n()->t('Add star'),
368 'undo' => DI::l10n()->t('Remove star'),
369 'toggle' => DI::l10n()->t('Toggle star status'),
370 'classdo' => $item['starred'] ? 'hidden' : '',
371 'classundo' => $item['starred'] ? '' : 'hidden',
372 'starred' => DI::l10n()->t('Starred'),
375 if ($conv->getProfileOwner() == DI::userSession()->getLocalUserId() && ($item['uid'] != 0)) {
376 if ($origin && in_array($item['private'], [Item::PUBLIC, Item::UNLISTED])) {
377 $ispinned = ($item['featured'] ? 'pinned' : 'unpinned');
380 'do' => DI::l10n()->t('Pin'),
381 'undo' => DI::l10n()->t('Unpin'),
382 'toggle' => DI::l10n()->t('Toggle pin status'),
383 'classdo' => $item['featured'] ? 'hidden' : '',
384 'classundo' => $item['featured'] ? '' : 'hidden',
385 'pinned' => DI::l10n()->t('Pinned'),
390 'add' => DI::l10n()->t('Add tag'),
399 if ($conv->isWritable()) {
400 $buttons['like'] = [DI::l10n()->t("I like this \x28toggle\x29"), DI::l10n()->t('Like')];
401 $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t('Dislike')];
403 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
406 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
407 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
412 $comment_html = $this->getCommentBox($indent);
417 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
421 DI::contentItem()->localize($item);
423 $body_html = Item::prepareBody($item, true);
425 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, DI::userSession()->getLocalUserId());
427 if (!empty($item['title'])) {
428 $title = $item['title'];
429 } elseif (!empty($item['content-warning']) && DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false)) {
430 $title = ucfirst($item['content-warning']);
435 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike')) {
436 $buttons['dislike'] = false;
439 // Disable features that aren't available in several networks
440 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
441 if ($buttons['dislike']) {
442 $buttons['dislike'] = false;
449 if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
450 $buttons['like'] = false;
453 $tags = Tag::populateFromItem($item);
455 $ago = Temporal::getRelativeDate($item['created']);
456 $ago_received = Temporal::getRelativeDate($item['received']);
457 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
458 $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
461 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
462 if (!DI::userSession()->getLocalUserId() && ($item['network'] != Protocol::DIASPORA) && !empty(DI::session()->get('remote_comment'))) {
464 DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('Remote comment'),
465 str_replace('{uri}', urlencode($item['uri']), DI::session()->get('remote_comment'))
468 // Ensure to either display the remote comment or the local activities
472 $remote_comment = '';
476 if (!empty($item['direction'])) {
477 $direction = $item['direction'];
481 if (!empty($item['language'])) {
482 $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
485 if (in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($item['network'], Protocol::FEDERATED)) {
486 $browsershare = [DI::l10n()->t('Share via ...'), DI::l10n()->t('Share via external services')];
488 $browsershare = null;
492 'template' => $this->getTemplate(),
493 'type' => implode('', array_slice(explode('/', $item['verb']), -1)),
494 'comment_firstcollapsed' => false,
495 'comment_lastcollapsed' => false,
496 'suppress_tags' => DI::config()->get('system', 'suppress_tags'),
497 'tags' => $tags['tags'],
498 'hashtags' => $tags['hashtags'],
499 'mentions' => $tags['mentions'],
500 'implicit_mentions' => $tags['implicit_mentions'],
501 'txt_cats' => DI::l10n()->t('Categories:'),
502 'txt_folders' => DI::l10n()->t('Filed under:'),
503 'has_cats' => ((count($categories)) ? 'true' : ''),
504 'has_folders' => ((count($folders)) ? 'true' : ''),
505 'categories' => $categories,
506 'folders' => $folders,
507 'body_html' => $body_html,
508 'text' => strip_tags($body_html),
509 'id' => $this->getId(),
510 'guid' => urlencode($item['guid']),
511 'isevent' => $isevent,
513 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
514 'olinktitle' => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
515 'to' => DI::l10n()->t('to'),
516 'via' => DI::l10n()->t('via'),
517 'wall' => DI::l10n()->t('Wall-to-Wall'),
518 'vwall' => DI::l10n()->t('via Wall-To-Wall:'),
519 'profile_url' => $profile_link,
520 'name' => $profile_name,
521 'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
522 'thumb' => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)),
523 'osparkle' => $osparkle,
524 'sparkle' => $sparkle,
526 'localtime' => DateTimeFormat::local($item['created'], 'r'),
527 'ago' => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
528 'app' => $item['app'],
531 'private' => $item['private'],
532 'privacy' => $privacy,
533 'connector' => $connector,
534 'location_html' => $location_html,
537 'owner_self' => $item['author-link'] == DI::session()->get('my_url'),
538 'owner_url' => $this->getOwnerUrl(),
539 'owner_photo' => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)),
540 'owner_name' => $this->getOwnerName(),
541 'plink' => Item::getPlink($item),
542 'browsershare' => $browsershare,
544 'ispinned' => $ispinned,
547 'isstarred' => $isstarred,
549 'ignore' => $ignore_thread,
552 'language' => $languages,
555 'ignore_author' => $ignore,
556 'collapse' => $collapse,
558 'like_html' => $responses['like']['output'],
559 'dislike_html' => $responses['dislike']['output'],
560 'emojis' => $this->getEmojis($item),
561 'responses' => $responses,
562 'switchcomment' => DI::l10n()->t('Comment'),
563 'reply_label' => DI::l10n()->t('Reply to %s', $profile_name),
564 'comment_html' => $comment_html,
565 'remote_comment' => $remote_comment,
566 'menu' => DI::l10n()->t('More'),
567 'previewing' => $conv->isPreview() ? ' preview ' : '',
568 'wait' => DI::l10n()->t('Please wait'),
569 'thread_level' => $thread_level,
571 'network' => $item['network'],
572 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
573 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
574 'received' => $item['received'],
575 'commented' => $item['commented'],
576 'created_date' => $item['created'],
577 'uriid' => $item['uri-id'],
578 'return' => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
579 'direction' => $direction,
580 'reshared' => $item['reshared'] ?? '',
582 'queue_count' => $item['delivery_queue_count'],
583 'queue_done' => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
584 'notifier_pending' => DI::l10n()->t('Notifier task is pending'),
585 'delivery_pending' => DI::l10n()->t('Delivery to remote servers is pending'),
586 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
587 'delivery_almost' => DI::l10n()->t('Delivery to remote servers is mostly done'),
588 'delivery_done' => DI::l10n()->t('Delivery to remote servers is done'),
592 $arr = ['item' => $item, 'output' => $tmp_item];
593 Hook::callAll('display_item', $arr);
595 $result = $arr['output'];
597 $result['children'] = [];
598 $children = $this->getChildren();
599 $nb_children = count($children);
600 if ($nb_children > 0) {
601 foreach ($children as $child) {
602 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1);
606 if (($nb_children > 2) || ($thread_level > 1)) {
607 $result['children'][0]['comment_firstcollapsed'] = true;
608 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
609 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
610 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
611 if ($thread_level > 1) {
612 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
614 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
619 // Copy values/set defaults
620 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
621 $result['private'] = $item['private'];
622 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
623 $result['flatten'] = !$this->isThreaded();
624 $result['threaded'] = $this->isThreaded();
635 private function getEmojis(array $item): array
637 if (empty($item['emojis'])) {
642 foreach ($item['emojis'] as $index => $element) {
643 $actors = implode(', ', $element['title']);
644 switch ($element['verb']) {
645 case Activity::ANNOUNCE:
646 $title = DI::l10n()->t('Reshared by: %s', $actors);
647 $icon = ['fa' => 'fa-retweet', 'icon' => 'icon-retweet'];
651 $title = DI::l10n()->t('Viewed by: %s', $actors);
652 $icon = ['fa' => 'fa-eye', 'icon' => 'icon-eye-open'];
656 $title = DI::l10n()->t('Liked by: %s', $actors);
657 $icon = ['fa' => 'fa-thumbs-up', 'icon' => 'icon-thumbs-up'];
660 case Activity::DISLIKE:
661 $title = DI::l10n()->t('Disliked by: %s', $actors);
662 $icon = ['fa' => 'fa-thumbs-down', 'icon' => 'icon-thumbs-down'];
665 case Activity::ATTEND:
666 $title = DI::l10n()->t('Attended by: %s', $actors);
667 $icon = ['fa' => 'fa-check', 'icon' => 'icon-ok'];
670 case Activity::ATTENDMAYBE:
671 $title = DI::l10n()->t('Maybe attended by: %s', $actors);
672 $icon = ['fa' => 'fa-question', 'icon' => 'icon-question'];
675 case Activity::ATTENDNO:
676 $title = DI::l10n()->t('Not attended by: %s', $actors);
677 $icon = ['fa' => 'fa-times', 'icon' => 'icon-remove'];
681 $title = DI::l10n()->t('Reacted with %s by: %s', $element['emoji'], $actors);
685 $emojis[$index] = ['emoji' => $element['emoji'], 'total' => $element['total'], 'title' => $title, 'icon' => $icon];
695 public function getId(): int
697 return $this->getDataValue('id');
703 public function isThreaded(): bool
705 return $this->threaded;
711 * @param Post $item The child post to add
713 * @return Post|bool Last Post object or bool on any error
716 public function addChild(Post $item)
718 if (!$item->getId()) {
719 Logger::error('Post object has no id', ['post' => $item]);
721 } elseif ($this->getChild($item->getId())) {
722 Logger::warning('Post object already exists', ['post' => $item]);
727 * Only add what will be displayed
729 if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) {
730 Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]);
733 DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) ||
734 DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE)
736 Logger::warning('Post objects is a like/dislike', ['post' => $item]);
740 $item->setParent($this);
741 $this->children[] = $item;
743 return end($this->children);
747 * Get a child by its ID
749 * @param integer $id The child id
750 * @return Thread|null Thread or NULL if not found
752 public function getChild(int $id)
754 foreach ($this->getChildren() as $child) {
755 if ($child->getId() == $id) {
764 * Get all our children
768 public function getChildren(): array
770 return $this->children;
776 * @param Post $item The item to set as parent
779 protected function setParent(Post $item)
781 $parent = $this->getParent();
783 $parent->removeChild($this);
786 $this->parent = $item;
787 $this->setThread($item->getThread());
795 protected function removeParent()
797 $this->parent = null;
798 $this->thread = null;
804 * @param Post $item The child to be removed
805 * @return boolean Success or failure
808 public function removeChild(Post $item): bool
810 $id = $item->getId();
811 foreach ($this->getChildren() as $key => $child) {
812 if ($child->getId() == $id) {
813 $child->removeParent();
814 unset($this->children[$key]);
815 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
816 $this->children = array_values($this->children);
821 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
830 protected function getParent()
832 return $this->parent;
836 * Set conversation thread
838 * @param Thread|null $thread
842 public function setThread(Thread $thread = null)
844 $this->thread = $thread;
846 // Set it on our children too
847 foreach ($this->getChildren() as $child) {
848 $child->setThread($thread);
855 * @return Thread|null
857 public function getThread()
859 return $this->thread;
865 * We shouldn't need this
869 public function getData(): array
877 * @param string $name key
879 * @return mixed value on success, false on failure
881 public function getDataValue(string $name)
883 if (!isset($this->data[$name])) {
884 // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
888 return $this->data[$name];
892 * Set template by name
894 * @param string $name Template name
897 * @throws InvalidArgumentException
899 private function setTemplate(string $name)
901 if (empty($this->available_templates[$name])) {
903 throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
906 $this->template = $this->available_templates[$name];
914 private function getTemplate()
916 return $this->template;
920 * Check if this is a toplevel post
924 private function isToplevel(): bool
926 return $this->toplevel;
930 * Check if this is writable
934 private function isWritable(): bool
936 $conv = $this->getThread();
939 // This will allow us to comment on wall-to-wall items owned by our friends
940 // and community groups even if somebody else wrote the post.
941 // bug #517 - this fixes for conversation owner
942 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == DI::userSession()->getLocalUserId()) {
946 // this fixes for visitors
947 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
949 return $this->writable;
953 * Count the total of our descendants
957 private function countDescendants(): int
959 $children = $this->getChildren();
960 $total = count($children);
962 foreach ($children as $child) {
963 $total += $child->countDescendants();
971 * Get the template for the comment box
975 private function getCommentBoxTemplate(): string
977 return $this->comment_box_template;
981 * Get default text for the comment box
984 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
986 private function getDefaultText(): string
990 if (!DI::userSession()->getLocalUserId()) {
994 $owner = User::getOwnerDataById($a->getLoggedInUserId());
995 $item = $this->getData();
997 if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), 'add_abstract')) {
998 $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
1003 if (!Feature::isEnabled(DI::userSession()->getLocalUserId(), 'explicit_mentions')) {
1007 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != Item::GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
1008 $text .= '@' . $item['author-addr'] . ' ';
1011 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1012 foreach ($terms as $term) {
1013 if (!$term['url']) {
1014 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
1018 $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
1020 !empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
1021 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])
1023 $text .= '@' . $profile['addr'] . ' ';
1031 * Get the comment box
1033 * @param string $indent Indent value
1035 * @return mixed The comment box string (empty if no comment box), false on failure
1036 * @throws \Exception
1037 * @todo return false is nowhere in this method?
1039 private function getCommentBox(string $indent)
1044 $conv = $this->getThread();
1046 if ($conv->isWritable() && $this->isWritable()) {
1048 * Hmmm, code depending on the presence of a particular addon?
1049 * This should be better if done by a hook
1052 if (Addon::isEnabled('qcomment')) {
1053 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1054 $qcomment = $words ? explode("\n", $words) : [];
1057 // Fetch the user id from the parent when the owner user is empty
1058 $uid = $conv->getProfileOwner();
1059 $parent_uid = $this->getDataValue('uid');
1061 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1063 $default_text = $this->getDefaultText();
1065 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
1069 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
1070 $comment_box = Renderer::replaceMacros($template, [
1071 '$return_path' => DI::args()->getQueryString(),
1072 '$threaded' => $this->isThreaded(),
1074 '$wall' => ($conv->getMode() === 'profile'),
1075 '$id' => $this->getId(),
1076 '$parent' => $this->getId(),
1077 '$qcomment' => $qcomment,
1078 '$default' => $default_text,
1079 '$profile_uid' => $uid,
1080 '$mylink' => DI::baseUrl()->remove($owner['url'] ?? ''),
1081 '$mytitle' => DI::l10n()->t('This is you'),
1082 '$myphoto' => DI::baseUrl()->remove($owner['thumb'] ?? ''),
1083 '$comment' => DI::l10n()->t('Comment'),
1084 '$submit' => DI::l10n()->t('Submit'),
1085 '$loading' => DI::l10n()->t('Loading...'),
1086 '$edbold' => DI::l10n()->t('Bold'),
1087 '$editalic' => DI::l10n()->t('Italic'),
1088 '$eduline' => DI::l10n()->t('Underline'),
1089 '$edquote' => DI::l10n()->t('Quote'),
1090 '$edemojis' => DI::l10n()->t('Add emojis'),
1091 '$edcode' => DI::l10n()->t('Code'),
1092 '$edimg' => DI::l10n()->t('Image'),
1093 '$edurl' => DI::l10n()->t('Link'),
1094 '$edattach' => DI::l10n()->t('Link or Media'),
1095 '$prompttext' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1096 '$preview' => DI::l10n()->t('Preview'),
1097 '$indent' => $indent,
1098 '$rand_num' => Crypto::randomDigits(12)
1102 return $comment_box;
1108 private function getRedirectUrl(): string
1110 return $this->redirect_url;
1114 * Check if we are a wall to wall item and set the relevant properties
1117 * @throws \Exception
1119 protected function checkWallToWall()
1122 $conv = $this->getThread();
1123 $this->wall_to_wall = false;
1125 if ($this->isToplevel()) {
1126 if ($conv->getMode() !== 'profile') {
1127 if ($this->getDataValue('owner-link')) {
1128 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1129 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1130 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1132 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1134 * The author url doesn't match the owner (typically the contact)
1135 * and also doesn't match the contact alias.
1136 * The name match is a hack to catch several weird cases where URLs are
1137 * all over the park. It can be tricked, but this prevents you from
1138 * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1139 * well that it's the same Bob Smith.
1140 * But it could be somebody else with the same name. It just isn't highly likely.
1142 $this->owner_name = $this->getDataValue('owner-name');
1143 $this->wall_to_wall = true;
1147 'id' => $this->getDataValue('owner-id'),
1148 'network' => $this->getDataValue('owner-network'),
1149 'url' => $this->getDataValue('owner-link'),
1150 'alias' => $this->getDataValue('owner-alias'),
1152 $this->owner_url = Contact::magicLinkByContact($owner);
1158 if (!$this->wall_to_wall) {
1159 $this->setTemplate('wall');
1160 $this->owner_url = '';
1161 $this->owner_name = '';
1168 private function isWallToWall(): bool
1170 return $this->wall_to_wall;
1176 private function getOwnerUrl(): string
1178 return $this->owner_url;
1184 private function getOwnerName(): string
1186 return $this->owner_name;
1192 private function isVisiting(): bool
1194 return $this->visiting;