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\Post as PostModel;
35 use Friendica\Model\Tag;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Util\Crypto;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Strings;
41 use Friendica\Util\Temporal;
42 use GuzzleHttp\Psr7\Uri;
43 use InvalidArgumentException;
51 private $template = null;
52 private $available_templates = [
53 'wall' => 'wall_thread.tpl',
54 'wall2wall' => 'wallwall_thread.tpl'
56 private $comment_box_template = 'comment_item.tpl';
57 private $toplevel = false;
58 private $writable = false;
62 private $children = [];
63 private $parent = null;
68 private $thread = null;
69 private $redirect_url = null;
70 private $owner_url = '';
71 private $owner_name = '';
72 private $wall_to_wall = false;
73 private $threaded = false;
74 private $visiting = false;
79 * @param array $data data array
82 public function __construct(array $data)
85 $this->setTemplate('wall');
86 $this->toplevel = $this->getId() == $this->getDataValue('parent');
88 if (!empty(DI::userSession()->getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
89 $this->visiting = true;
92 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
95 'id' => $this->getDataValue('author-id'),
96 'network' => $this->getDataValue('author-network'),
97 'url' => $this->getDataValue('author-link'),
98 'alias' => $this->getDataValue('author-alias')
100 $this->redirect_url = Contact::magicLinkByContact($author);
101 if (!$this->isToplevel()) {
102 $this->threaded = true;
105 // Prepare the children
106 if (!empty($data['children'])) {
107 foreach ($data['children'] as $item) {
108 // Only add will be displayed
109 if ($item['network'] === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item['uid']) {
111 } elseif (!DI::contentItem()->isVisibleActivity($item)) {
115 // You can always comment on Diaspora and OStatus items
116 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (DI::userSession()->getLocalUserId() == $item['uid'])) {
117 $item['writable'] = true;
120 $item['pagedrop'] = $data['pagedrop'];
121 $child = new Post($item);
122 $this->addChild($child);
128 * Fetch the privacy of the post
130 * @param array $item Item record
131 * @return string Item privacy message
132 * @throws InvalidArgumentException If $item['private'] is unknown
134 private function fetchPrivacy(array $item): string
136 switch ($item['private']) {
138 $output = DI::l10n()->t('Private Message');
142 $output = DI::l10n()->t('Public Message');
146 $output = DI::l10n()->t('Unlisted Message');
150 throw new InvalidArgumentException('Item privacy ' . $item['privacy'] . ' is unsupported');
157 * Get data in a form usable by a conversation template
159 * @param array $conv_responses conversation responses
160 * @param string $formSecurityToken A security Token to avoid CSF attacks
161 * @param integer $thread_level default = 1
162 * @param array $thread_parent Array of parent guid and parent author names
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, array $thread_parent = [])
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 $ignoreServer = false;
257 if (DI::userSession()->getLocalUserId()) {
259 'dropping' => $dropping,
260 'pagedrop' => $item['pagedrop'],
261 'select' => DI::l10n()->t('Select'),
262 'label' => $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally'),
266 if (!$item['self'] && DI::userSession()->getLocalUserId()) {
269 'label' => DI::l10n()->t('Block %s', $item['author-name']),
270 'author_id' => $item['author-id'],
274 'label' => DI::l10n()->t('Ignore %s', $item['author-name']),
275 'author_id' => $item['author-id'],
278 'collapsing' => true,
279 'label' => DI::l10n()->t('Collapse %s', $item['author-name']),
280 'author_id' => $item['author-id'],
283 'label' => DI::l10n()->t('Report post'),
284 'href' => 'moderation/report/create?' . http_build_query(['cid' => $item['author-id'], 'uri-ids' => [$item['uri-id']]]),
286 $authorBaseUri = new Uri($item['author-baseurl'] ?? '');
287 if ($authorBaseUri->getHost() && !DI::baseUrl()->isLocalUrl($authorBaseUri)) {
289 'label' => DI::l10n()->t("Ignore %s server", $authorBaseUri->getHost()),
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', 'comment'];
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')];
338 $emojis = $this->getEmojis($item);
341 'like' => Activity::LIKE,
342 'dislike' => Activity::DISLIKE,
343 'announce' => Activity::ANNOUNCE,
344 'comment' => Activity::POST,
345 'attendyes' => Activity::ATTEND,
346 'attendno' => Activity::ATTENDNO,
347 'attendmaybe' => Activity::ATTENDMAYBE,
349 $reactions = $emojis;
351 foreach ($response_verbs as $value => $verb) {
352 $responses[$verb] = [
353 'self' => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
354 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? DI::conversation()->formatActivity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
355 'total' => $emojis[$verbs[$verb]]['total'] ?? '',
356 'title' => $emojis[$verbs[$verb]]['title'] ?? '',
358 unset($reactions[$verbs[$verb]]);
361 unset($emojis[Activity::POST]);
364 * We should avoid doing this all the time, but it depends on the conversation mode
365 * And the conv mode may change when we change the conv, or it changes its mode
366 * Maybe we should establish a way to be notified about conversation changes
368 $this->checkWallToWall();
370 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
371 $osparkle = ' sparkle';
376 if ($this->isToplevel()) {
377 if (DI::userSession()->getLocalUserId()) {
378 $ignored_thread = PostModel\ThreadUser::getIgnored($item['uri-id'], DI::userSession()->getLocalUserId());
379 if ($item['mention'] || $ignored_thread) {
381 'do' => DI::l10n()->t('Ignore thread'),
382 'undo' => DI::l10n()->t('Unignore thread'),
383 'toggle' => DI::l10n()->t('Toggle ignore status'),
384 'classdo' => $ignored_thread ? 'hidden' : '',
385 'classundo' => $ignored_thread ? '' : 'hidden',
386 'ignored' => DI::l10n()->t('Ignored'),
390 $isstarred = (($item['starred']) ? 'starred' : 'unstarred');
393 'do' => DI::l10n()->t('Add star'),
394 'undo' => DI::l10n()->t('Remove star'),
395 'toggle' => DI::l10n()->t('Toggle star status'),
396 'classdo' => $item['starred'] ? 'hidden' : '',
397 'classundo' => $item['starred'] ? '' : 'hidden',
398 'starred' => DI::l10n()->t('Starred'),
401 if ($conv->getProfileOwner() == DI::userSession()->getLocalUserId() && ($item['uid'] != 0)) {
402 if ($origin && in_array($item['private'], [Item::PUBLIC, Item::UNLISTED])) {
403 $ispinned = ($item['featured'] ? 'pinned' : 'unpinned');
406 'do' => DI::l10n()->t('Pin'),
407 'undo' => DI::l10n()->t('Unpin'),
408 'toggle' => DI::l10n()->t('Toggle pin status'),
409 'classdo' => $item['featured'] ? 'hidden' : '',
410 'classundo' => $item['featured'] ? '' : 'hidden',
411 'pinned' => DI::l10n()->t('Pinned'),
416 'add' => DI::l10n()->t('Add tag'),
425 if ($conv->isWritable()) {
426 $buttons['like'] = [DI::l10n()->t("I like this \x28toggle\x29"), DI::l10n()->t('Like')];
427 $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t('Dislike')];
429 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
432 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
433 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
438 $comment_html = $this->getCommentBox($indent);
443 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
447 DI::contentItem()->localize($item);
449 $body_html = Item::prepareBody($item, true);
451 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, DI::userSession()->getLocalUserId());
453 if (!empty($item['title'])) {
454 $title = $item['title'];
455 } elseif (!empty($item['content-warning']) && DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false)) {
456 $title = ucfirst($item['content-warning']);
461 $hide_dislike = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike');
463 $buttons['dislike'] = false;
466 // Disable features that aren't available in several networks
467 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
468 if ($buttons['dislike']) {
469 $buttons['dislike'] = false;
476 if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
477 $buttons['like'] = false;
480 $tags = Tag::populateFromItem($item);
482 $ago = Temporal::getRelativeDate($item['created']);
483 $ago_received = Temporal::getRelativeDate($item['received']);
484 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
485 $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
488 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
489 if (!DI::userSession()->getLocalUserId() && ($item['network'] != Protocol::DIASPORA) && !empty(DI::session()->get('remote_comment'))) {
491 DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('Remote comment'),
492 str_replace('{uri}', urlencode($item['uri']), DI::session()->get('remote_comment'))
495 // Ensure to either display the remote comment or the local activities
499 $remote_comment = '';
503 if (!empty($item['direction'])) {
504 $direction = $item['direction'];
508 if (!empty($item['language'])) {
509 $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
512 if (in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($item['network'], Protocol::FEDERATED)) {
513 $browsershare = [DI::l10n()->t('Share via ...'), DI::l10n()->t('Share via external services')];
515 $browsershare = null;
518 $parent_guid = $thread_parent[$item['thr-parent-id']]['guid'] ?? '';
519 $parent_username = $thread_parent[$item['thr-parent-id']]['name'] ?? '';
520 $parent_unknown = $parent_username ? '' : DI::l10n()->t('Unknown parent');
523 'parentguid' => $parent_guid,
524 'inreplyto' => DI::l10n()->t('in reply to %s', $parent_username),
525 'isunknown' => $parent_unknown,
526 'isunknown_label' => DI::l10n()->t('Parent is probably private or not federated.'),
527 'template' => $this->getTemplate(),
528 'type' => implode('', array_slice(explode('/', $item['verb']), -1)),
529 'comment_firstcollapsed' => false,
530 'comment_lastcollapsed' => false,
531 'suppress_tags' => DI::config()->get('system', 'suppress_tags'),
532 'tags' => $tags['tags'],
533 'hashtags' => $tags['hashtags'],
534 'mentions' => $tags['mentions'],
535 'implicit_mentions' => $tags['implicit_mentions'],
536 'txt_cats' => DI::l10n()->t('Categories:'),
537 'txt_folders' => DI::l10n()->t('Filed under:'),
538 'has_cats' => ((count($categories)) ? 'true' : ''),
539 'has_folders' => ((count($folders)) ? 'true' : ''),
540 'categories' => $categories,
541 'folders' => $folders,
542 'body_html' => $body_html,
543 'text' => strip_tags($body_html),
544 'id' => $this->getId(),
545 'guid' => urlencode($item['guid']),
546 'isevent' => $isevent,
548 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
549 'olinktitle' => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
550 'to' => DI::l10n()->t('to'),
551 'via' => DI::l10n()->t('via'),
552 'wall' => DI::l10n()->t('Wall-to-Wall'),
553 'vwall' => DI::l10n()->t('via Wall-To-Wall:'),
554 'profile_url' => $profile_link,
555 'name' => $profile_name,
556 'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
557 'thumb' => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)),
558 'osparkle' => $osparkle,
559 'sparkle' => $sparkle,
561 'localtime' => DateTimeFormat::local($item['created'], 'r'),
562 'ago' => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
563 'app' => $item['app'],
566 'private' => $item['private'],
567 'privacy' => $privacy,
568 'connector' => $connector,
569 'location_html' => $location_html,
572 'owner_self' => $item['author-link'] == DI::session()->get('my_url'),
573 'owner_url' => $this->getOwnerUrl(),
574 'owner_photo' => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)),
575 'owner_name' => $this->getOwnerName(),
576 'plink' => Item::getPlink($item),
577 'browsershare' => $browsershare,
579 'ispinned' => $ispinned,
582 'isstarred' => $isstarred,
584 'ignore' => $ignore_thread,
587 'language' => $languages,
590 'ignore_author' => $ignore,
591 'collapse' => $collapse,
593 'ignore_server' => $ignoreServer,
595 'like_html' => $responses['like']['output'],
596 'dislike_html' => $responses['dislike']['output'],
597 'hide_dislike' => $hide_dislike,
599 'quoteshares' => $this->getQuoteShares($item['quoteshares']),
600 'reactions' => $reactions,
601 'responses' => $responses,
602 'legacy_activities' => DI::config()->get('system', 'legacy_activities'),
603 'switchcomment' => DI::l10n()->t('Comment'),
604 'reply_label' => DI::l10n()->t('Reply to %s', $profile_name),
605 'comment_html' => $comment_html,
606 'remote_comment' => $remote_comment,
607 'menu' => DI::l10n()->t('More'),
608 'previewing' => $conv->isPreview() ? ' preview ' : '',
609 'wait' => DI::l10n()->t('Please wait'),
610 'thread_level' => $thread_level,
612 'author_gsid' => $item['author-gsid'],
613 'network' => $item['network'],
614 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
615 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
616 'received' => $item['received'],
617 'commented' => $item['commented'],
618 'created_date' => $item['created'],
619 'uriid' => $item['uri-id'],
620 'return' => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
621 'direction' => $direction,
622 'reshared' => $item['reshared'] ?? '',
624 'queue_count' => $item['delivery_queue_count'],
625 'queue_done' => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
626 'notifier_pending' => DI::l10n()->t('Notifier task is pending'),
627 'delivery_pending' => DI::l10n()->t('Delivery to remote servers is pending'),
628 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
629 'delivery_almost' => DI::l10n()->t('Delivery to remote servers is mostly done'),
630 'delivery_done' => DI::l10n()->t('Delivery to remote servers is done'),
634 $arr = ['item' => $item, 'output' => $tmp_item];
635 Hook::callAll('display_item', $arr);
637 $result = $arr['output'];
639 $result['children'] = [];
640 $children = $this->getChildren();
641 $nb_children = count($children);
642 if ($nb_children > 0) {
643 $thread_parent[$item['uri-id']] = ['guid' => $item['guid'], 'name' => $item['author-name']];
644 foreach ($children as $child) {
645 $thread_parent[$child->getDataValue('uri-id')] = ['guid' => $child->getDataValue('guid'), 'name' => $child->getDataValue('author-name')];
646 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1, $thread_parent);
650 if (($nb_children > 2) || ($thread_level > 1)) {
651 $result['children'][0]['comment_firstcollapsed'] = true;
652 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
653 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
654 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
655 if ($thread_level > 1) {
656 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
658 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
663 // Copy values/set defaults
664 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
665 $result['private'] = $item['private'];
666 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
667 $result['flatten'] = !$this->isThreaded();
668 $result['threaded'] = $this->isThreaded();
679 private function getEmojis(array $item): array
681 if (empty($item['emojis'])) {
686 foreach ($item['emojis'] as $index => $element) {
687 $key = $element['verb'];
688 $actors = implode(', ', $element['title']);
689 switch ($element['verb']) {
690 case Activity::ANNOUNCE:
691 $title = DI::l10n()->t('Reshared by: %s', $actors);
692 $icon = ['fa' => 'fa-retweet', 'icon' => 'icon-retweet'];
696 $title = DI::l10n()->t('Viewed by: %s', $actors);
697 $icon = ['fa' => 'fa-eye', 'icon' => 'icon-eye-open'];
701 $title = DI::l10n()->t('Liked by: %s', $actors);
702 $icon = ['fa' => 'fa-thumbs-up', 'icon' => 'icon-thumbs-up'];
705 case Activity::DISLIKE:
706 $title = DI::l10n()->t('Disliked by: %s', $actors);
707 $icon = ['fa' => 'fa-thumbs-down', 'icon' => 'icon-thumbs-down'];
710 case Activity::ATTEND:
711 $title = DI::l10n()->t('Attended by: %s', $actors);
712 $icon = ['fa' => 'fa-check', 'icon' => 'icon-ok'];
715 case Activity::ATTENDMAYBE:
716 $title = DI::l10n()->t('Maybe attended by: %s', $actors);
717 $icon = ['fa' => 'fa-question', 'icon' => 'icon-question'];
720 case Activity::ATTENDNO:
721 $title = DI::l10n()->t('Not attended by: %s', $actors);
722 $icon = ['fa' => 'fa-times', 'icon' => 'icon-remove'];
726 $title = DI::l10n()->t('Commented by: %s', $actors);
727 $icon = ['fa' => 'fa-commenting', 'icon' => 'icon-commenting'];
731 $title = DI::l10n()->t('Reacted with %s by: %s', $element['emoji'], $actors);
733 $key = $element['emoji'];
736 $emojis[$key] = ['emoji' => $element['emoji'], 'total' => $element['total'], 'title' => $title, 'icon' => $icon];
745 * @param array $quoteshares
748 private function getQuoteShares($quoteshares)
750 if (empty($quoteshares)) {
754 return ['total' => $quoteshares['total'], 'title' => DI::l10n()->t('Quote shared by: %s', implode(', ', $quoteshares['title']))];
760 public function getId(): int
762 return $this->getDataValue('id');
768 public function isThreaded(): bool
770 return $this->threaded;
776 * @param Post $item The child post to add
778 * @return Post|bool Last Post object or bool on any error
781 public function addChild(Post $item)
783 if (!$item->getId()) {
784 Logger::error('Post object has no id', ['post' => $item]);
786 } elseif ($this->getChild($item->getId())) {
787 Logger::warning('Post object already exists', ['post' => $item]);
792 * Only add what will be displayed
794 if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) {
795 Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]);
798 DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) ||
799 DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE)
801 Logger::warning('Post objects is a like/dislike', ['post' => $item]);
805 $item->setParent($this);
806 $this->children[] = $item;
808 return end($this->children);
812 * Get a child by its ID
814 * @param integer $id The child id
815 * @return Thread|null Thread or NULL if not found
817 public function getChild(int $id)
819 foreach ($this->getChildren() as $child) {
820 if ($child->getId() == $id) {
829 * Get all our children
833 public function getChildren(): array
835 return $this->children;
841 * @param Post $item The item to set as parent
844 protected function setParent(Post $item)
846 $parent = $this->getParent();
848 $parent->removeChild($this);
851 $this->parent = $item;
852 $this->setThread($item->getThread());
860 protected function removeParent()
862 $this->parent = null;
863 $this->thread = null;
869 * @param Post $item The child to be removed
870 * @return boolean Success or failure
873 public function removeChild(Post $item): bool
875 $id = $item->getId();
876 foreach ($this->getChildren() as $key => $child) {
877 if ($child->getId() == $id) {
878 $child->removeParent();
879 unset($this->children[$key]);
880 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
881 $this->children = array_values($this->children);
886 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
895 protected function getParent()
897 return $this->parent;
901 * Set conversation thread
903 * @param Thread|null $thread
907 public function setThread(Thread $thread = null)
909 $this->thread = $thread;
911 // Set it on our children too
912 foreach ($this->getChildren() as $child) {
913 $child->setThread($thread);
920 * @return Thread|null
922 public function getThread()
924 return $this->thread;
930 * We shouldn't need this
934 public function getData(): array
942 * @param string $name key
944 * @return mixed value on success, false on failure
946 public function getDataValue(string $name)
948 if (!isset($this->data[$name])) {
949 // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
953 return $this->data[$name];
957 * Set template by name
959 * @param string $name Template name
962 * @throws InvalidArgumentException
964 private function setTemplate(string $name)
966 if (empty($this->available_templates[$name])) {
968 throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
971 $this->template = $this->available_templates[$name];
979 private function getTemplate()
981 return $this->template;
985 * Check if this is a toplevel post
989 private function isToplevel(): bool
991 return $this->toplevel;
995 * Check if this is writable
999 private function isWritable(): bool
1001 $conv = $this->getThread();
1004 // This will allow us to comment on wall-to-wall items owned by our friends
1005 // and community groups even if somebody else wrote the post.
1006 // bug #517 - this fixes for conversation owner
1007 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == DI::userSession()->getLocalUserId()) {
1011 // this fixes for visitors
1012 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
1014 return $this->writable;
1018 * Count the total of our descendants
1022 private function countDescendants(): int
1024 $children = $this->getChildren();
1025 $total = count($children);
1027 foreach ($children as $child) {
1028 $total += $child->countDescendants();
1036 * Get the template for the comment box
1040 private function getCommentBoxTemplate(): string
1042 return $this->comment_box_template;
1046 * Get default text for the comment box
1049 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1051 private function getDefaultText(): string
1055 if (!DI::userSession()->getLocalUserId()) {
1059 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1060 $item = $this->getData();
1062 if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), 'add_abstract')) {
1063 $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
1068 if (!Feature::isEnabled(DI::userSession()->getLocalUserId(), 'explicit_mentions')) {
1072 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != Item::GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
1073 $text .= '@' . $item['author-addr'] . ' ';
1076 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1077 foreach ($terms as $term) {
1078 if (!$term['url']) {
1079 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
1083 $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
1085 !empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
1086 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])
1088 $text .= '@' . $profile['addr'] . ' ';
1096 * Get the comment box
1098 * @param string $indent Indent value
1100 * @return mixed The comment box string (empty if no comment box), false on failure
1101 * @throws \Exception
1102 * @todo return false is nowhere in this method?
1104 private function getCommentBox(string $indent)
1109 $conv = $this->getThread();
1111 if ($conv->isWritable() && $this->isWritable()) {
1113 * Hmmm, code depending on the presence of a particular addon?
1114 * This should be better if done by a hook
1117 if (Addon::isEnabled('qcomment')) {
1118 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1119 $qcomment = $words ? explode("\n", $words) : [];
1122 // Fetch the user id from the parent when the owner user is empty
1123 $uid = $conv->getProfileOwner();
1124 $parent_uid = $this->getDataValue('uid');
1126 $owner = User::getOwnerDataById($a->getLoggedInUserId());
1128 $default_text = $this->getDefaultText();
1130 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
1134 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
1135 $comment_box = Renderer::replaceMacros($template, [
1136 '$return_path' => DI::args()->getQueryString(),
1137 '$threaded' => $this->isThreaded(),
1139 '$wall' => ($conv->getMode() === 'profile'),
1140 '$id' => $this->getId(),
1141 '$parent' => $this->getId(),
1142 '$qcomment' => $qcomment,
1143 '$default' => $default_text,
1144 '$profile_uid' => $uid,
1145 '$mylink' => DI::baseUrl()->remove($owner['url'] ?? ''),
1146 '$mytitle' => DI::l10n()->t('This is you'),
1147 '$myphoto' => DI::baseUrl()->remove($owner['thumb'] ?? ''),
1148 '$comment' => DI::l10n()->t('Comment'),
1149 '$submit' => DI::l10n()->t('Submit'),
1150 '$loading' => DI::l10n()->t('Loading...'),
1151 '$edbold' => DI::l10n()->t('Bold'),
1152 '$editalic' => DI::l10n()->t('Italic'),
1153 '$eduline' => DI::l10n()->t('Underline'),
1154 '$contentwarn' => DI::l10n()->t('Content Warning'),
1155 '$edquote' => DI::l10n()->t('Quote'),
1156 '$edemojis' => DI::l10n()->t('Add emojis'),
1157 '$edcode' => DI::l10n()->t('Code'),
1158 '$edimg' => DI::l10n()->t('Image'),
1159 '$edurl' => DI::l10n()->t('Link'),
1160 '$edattach' => DI::l10n()->t('Link or Media'),
1161 '$prompttext' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1162 '$preview' => DI::l10n()->t('Preview'),
1163 '$indent' => $indent,
1164 '$rand_num' => Crypto::randomDigits(12)
1168 return $comment_box;
1174 private function getRedirectUrl(): string
1176 return $this->redirect_url;
1180 * Check if we are a wall to wall item and set the relevant properties
1183 * @throws \Exception
1185 protected function checkWallToWall()
1188 $conv = $this->getThread();
1189 $this->wall_to_wall = false;
1191 if ($this->isToplevel()) {
1192 if ($conv->getMode() !== 'profile') {
1193 if ($this->getDataValue('owner-link')) {
1194 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1195 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1196 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1198 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1200 * The author url doesn't match the owner (typically the contact)
1201 * and also doesn't match the contact alias.
1202 * The name match is a hack to catch several weird cases where URLs are
1203 * all over the park. It can be tricked, but this prevents you from
1204 * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1205 * well that it's the same Bob Smith.
1206 * But it could be somebody else with the same name. It just isn't highly likely.
1208 $this->owner_name = $this->getDataValue('owner-name');
1209 $this->wall_to_wall = true;
1213 'id' => $this->getDataValue('owner-id'),
1214 'network' => $this->getDataValue('owner-network'),
1215 'url' => $this->getDataValue('owner-link'),
1216 'alias' => $this->getDataValue('owner-alias'),
1218 $this->owner_url = Contact::magicLinkByContact($owner);
1224 if (!$this->wall_to_wall) {
1225 $this->setTemplate('wall');
1226 $this->owner_url = '';
1227 $this->owner_name = '';
1234 private function isWallToWall(): bool
1236 return $this->wall_to_wall;
1242 private function getOwnerUrl(): string
1244 return $this->owner_url;
1250 private function getOwnerName(): string
1252 return $this->owner_name;
1258 private function isVisiting(): bool
1260 return $this->visiting;