3 * @copyright Copyright (C) 2010-2022, 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\Content;
25 use Friendica\App\Arguments;
26 use Friendica\App\BaseURL;
27 use Friendica\BaseModule;
28 use Friendica\Core\ACL;
29 use Friendica\Core\Config\Capability\IManageConfigValues;
30 use Friendica\Core\Hook;
31 use Friendica\Core\L10n;
32 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\Session\Capability\IHandleSessions;
36 use Friendica\Core\Session\Capability\IHandleUserSessions;
37 use Friendica\Core\Theme;
38 use Friendica\Database\DBA;
39 use Friendica\Model\Contact;
40 use Friendica\Model\Item as ItemModel;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Object\Post as PostObject;
46 use Friendica\Object\Thread;
47 use Friendica\Protocol\Activity;
48 use Friendica\Util\Crypto;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\Profiler;
51 use Friendica\Util\Strings;
52 use Friendica\Util\Temporal;
53 use Psr\Log\LoggerInterface;
63 /** @var LoggerInterface */
67 /** @var App\Arguments */
69 /** @var IManagePersonalConfigValues */
73 /** @var IManageConfigValues */
81 /** @var IHandleSessions */
83 /** @var IHandleUserSessions */
86 public function __construct(LoggerInterface $logger, Profiler $profiler, Activity $activity, L10n $l10n, Item $item, Arguments $args, BaseURL $baseURL, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, App\Page $page, App\Mode $mode, App $app, IHandleSessions $session, IHandleUserSessions $userSession)
88 $this->activity = $activity;
90 $this->config = $config;
92 $this->baseURL = $baseURL;
93 $this->profiler = $profiler;
94 $this->logger = $logger;
97 $this->pConfig = $pConfig;
100 $this->session = $session;
101 $this->userSession = $userSession;
105 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
107 * Increments the count of each matching activity and adds a link to the author as needed.
109 * @param array $activity
110 * @param array &$conv_responses (already created with builtin activity structure)
112 * @throws ImagickException
113 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
115 public function builtinActivityPuller(array $activity, array &$conv_responses)
117 $thread_parent = $activity['thr-parent-row'] ?? [];
119 foreach ($conv_responses as $mode => $v) {
124 $verb = Activity::LIKE;
127 $verb = Activity::DISLIKE;
130 $verb = Activity::ATTEND;
133 $verb = Activity::ATTENDNO;
136 $verb = Activity::ATTENDMAYBE;
139 $verb = Activity::ANNOUNCE;
145 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
148 'id' => $activity['author-id'],
149 'network' => $activity['author-network'],
150 'url' => $activity['author-link']
152 $url = Contact::magicLinkByContact($author);
153 if (strpos($url, 'redir/') === 0) {
154 $sparkle = ' class="sparkle" ';
157 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
159 if (empty($activity['thr-parent-id'])) {
160 $activity['thr-parent-id'] = $activity['parent-uri-id'];
163 // Skip when the causer of the parent is the same as the author of the announce
164 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
168 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
169 $conv_responses[$mode][$activity['thr-parent-id']] = [
173 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
174 // only list each unique author once
178 if ($this->userSession->getPublicContactId() == $activity['author-id']) {
179 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
182 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
184 // there can only be one activity verb per item so if we found anything, we can stop looking
191 * Format the activity text for an item/photo/video
193 * @param array $links = array of pre-linked names of actors
194 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
195 * @param int $id = item id
196 * @return string formatted text
197 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
199 public function formatActivity(array $links, string $verb, int $id): string
201 $this->profiler->startRecording('rendering');
206 $total = count($links);
210 // Phrase if there is only one liker. In other cases it will be uses for the expanded
211 // list which show all likers
214 $phrase = $this->l10n->t('%s likes this.', $likers);
217 $phrase = $this->l10n->t('%s doesn\'t like this.', $likers);
220 $phrase = $this->l10n->t('%s attends.', $likers);
223 $phrase = $this->l10n->t('%s doesn\'t attend.', $likers);
226 $phrase = $this->l10n->t('%s attends maybe.', $likers);
229 $phrase = $this->l10n->t('%s reshared this.', $likers);
232 } elseif ($total > 1) {
233 if ($total < $this->config->get('system', 'max_likers')) {
234 $likers = implode(', ', array_slice($links, 0, -1));
235 $likers .= ' ' . $this->l10n->t('and') . ' ' . $links[count($links) - 1];
237 $likers = implode(', ', array_slice($links, 0, $this->config->get('system', 'max_likers') - 1));
238 $likers .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
241 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
246 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
247 $explikers = $this->l10n->t('%s like this.', $likers);
250 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
251 $explikers = $this->l10n->t('%s don\'t like this.', $likers);
254 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
255 $explikers = $this->l10n->t('%s attend.', $likers);
258 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
259 $explikers = $this->l10n->t('%s don\'t attend.', $likers);
262 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
263 $explikers = $this->l10n->t('%s attend maybe.', $likers);
266 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
267 $explikers = $this->l10n->t('%s reshared this.', $likers);
271 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
274 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
275 '$phrase' => $phrase,
281 $this->profiler->stopRecording();
285 public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
287 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
288 if (empty($user['uid'])) {
292 $this->profiler->startRecording('rendering');
295 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
296 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
297 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
298 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
299 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
300 $x['bang'] = $x['bang'] ?? '';
301 $x['visitor'] = $x['visitor'] ?? 'block';
302 $x['is_owner'] = $x['is_owner'] ?? true;
303 $x['profile_uid'] = $x['profile_uid'] ?? $this->userSession->getLocalUserId();
306 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
308 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
309 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
310 '$newpost' => 'true',
311 '$baseurl' => $this->baseURL->get(true),
312 '$geotag' => $geotag,
313 '$nickname' => $x['nickname'],
314 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
315 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
316 '$term' => $this->l10n->t('Tag term:'),
317 '$fileas' => $this->l10n->t('Save to Folder:'),
318 '$whereareu' => $this->l10n->t('Where are you right now?'),
319 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
320 '$is_mobile' => $this->mode->isMobile(),
324 Hook::callAll('jot_tool', $jotplugins);
326 if ($this->config->get('system', 'set_creation_date')) {
327 $created_at = Temporal::getDateTimeField(
328 new \DateTime(DBA::NULL_DATETIME),
329 new \DateTime('now'),
331 $this->l10n->t('Created at'),
338 $tpl = Renderer::getMarkupTemplate('jot.tpl');
340 $o .= Renderer::replaceMacros($tpl, [
341 '$new_post' => $this->l10n->t('New Post'),
342 '$return_path' => $this->args->getQueryString(),
344 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
345 '$loading' => $this->l10n->t('Loading...'),
346 '$upload' => $this->l10n->t('Upload photo'),
347 '$shortupload' => $this->l10n->t('upload photo'),
348 '$attach' => $this->l10n->t('Attach file'),
349 '$shortattach' => $this->l10n->t('attach file'),
350 '$edbold' => $this->l10n->t('Bold'),
351 '$editalic' => $this->l10n->t('Italic'),
352 '$eduline' => $this->l10n->t('Underline'),
353 '$edquote' => $this->l10n->t('Quote'),
354 '$edcode' => $this->l10n->t('Code'),
355 '$edimg' => $this->l10n->t('Image'),
356 '$edurl' => $this->l10n->t('Link'),
357 '$edattach' => $this->l10n->t('Link or Media'),
358 '$edvideo' => $this->l10n->t('Video'),
359 '$setloc' => $this->l10n->t('Set your location'),
360 '$shortsetloc' => $this->l10n->t('set location'),
361 '$noloc' => $this->l10n->t('Clear browser location'),
362 '$shortnoloc' => $this->l10n->t('clear location'),
363 '$title' => $x['title'] ?? '',
364 '$placeholdertitle' => $this->l10n->t('Set title'),
365 '$category' => $x['category'] ?? '',
366 '$placeholdercategory' => Feature::isEnabled($this->userSession->getLocalUserId(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
367 '$scheduled_at' => Temporal::getDateTimeField(
369 new \DateTime('now + 6 months'),
371 $this->l10n->t('Scheduled at'),
374 '$created_at' => $created_at,
375 '$wait' => $this->l10n->t('Please wait'),
376 '$permset' => $this->l10n->t('Permission settings'),
377 '$shortpermset' => $this->l10n->t('Permissions'),
378 '$wall' => $notes_cid ? 0 : 1,
379 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
380 '$content' => $x['content'] ?? '',
381 '$post_id' => $x['post_id'] ?? '',
382 '$baseurl' => $this->baseURL->get(true),
383 '$defloc' => $x['default_location'],
384 '$visitor' => $x['visitor'],
385 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
386 '$public' => $this->l10n->t('Public post'),
387 '$lockstate' => $x['lockstate'],
388 '$bang' => $x['bang'],
389 '$profile_uid' => $x['profile_uid'],
390 '$preview' => $this->l10n->t('Preview'),
391 '$jotplugins' => $jotplugins,
392 '$notes_cid' => $notes_cid,
393 '$cancel' => $this->l10n->t('Cancel'),
394 '$rand_num' => Crypto::randomDigits(12),
396 // ACL permissions box
399 //jot nav tab (used in some themes)
400 '$message' => $this->l10n->t('Message'),
401 '$browser' => $this->l10n->t('Browser'),
403 '$compose_link_title' => $this->l10n->t('Open Compose page'),
404 '$always_open_compose' => $this->pConfig->get($this->userSession->getLocalUserId(), 'frio', 'always_open_compose', false),
408 if ($popup == true) {
409 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
412 $this->profiler->stopRecording();
417 * "Render" a conversation or list of items for HTML display.
418 * There are two major forms of display:
419 * - Sequential or unthreaded ("New Item View" or search results)
420 * - conversation view
421 * The $mode parameter decides between the various renderings and also
422 * figures out how to determine page owner and other contextual items
423 * that are based on unique features of the calling module.
424 * @param array $items
425 * @param string $mode
426 * @param $update @TODO Which type?
427 * @param bool $preview
428 * @param string $order
431 * @throws ImagickException
432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 public function create(array $items, string $mode, $update, bool $preview = false, string $order = 'commented', int $uid = 0): string
436 $this->profiler->startRecording('rendering');
438 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
439 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
440 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
441 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
443 $ssl_state = (bool)$this->userSession->getLocalUserId();
445 $live_update_div = '';
447 $blocklist = $this->getBlocklist();
449 $previewing = (($preview) ? ' preview ' : '');
451 if ($mode === 'network') {
452 $items = $this->addChildren($items, false, $order, $uid, $mode);
455 * The special div is needed for liveUpdate to kick in for this page.
456 * We only launch liveUpdate if you aren't filtering in some incompatible
457 * way and also you aren't writing a comment (discovered in javascript).
459 $live_update_div = '<div id="live-network"></div>' . "\r\n"
460 . "<script> var profile_uid = " . $_SESSION['uid']
461 . "; var netargs = '" . substr($this->args->getCommand(), 8)
463 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
464 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
465 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
466 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
467 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
468 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
469 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
470 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
471 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
472 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
473 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
475 . "'; </script>\r\n";
477 } elseif ($mode === 'profile') {
478 $items = $this->addChildren($items, false, $order, $uid, $mode);
481 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
483 if ($tab === 'posts') {
485 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
486 * because browser prefetching might change it on us. We have to deliver it with the page.
489 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
490 . "<script> var profile_uid = " . $uid
491 . "; var netargs = '?f='; </script>\r\n";
494 } elseif ($mode === 'notes') {
495 $items = $this->addChildren($items, false, $order, $this->userSession->getLocalUserId(), $mode);
498 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
499 . "<script> var profile_uid = " . $this->userSession->getLocalUserId()
500 . "; var netargs = '/?f='; </script>\r\n";
502 } elseif ($mode === 'display') {
503 $items = $this->addChildren($items, false, $order, $uid, $mode);
506 $live_update_div = '<div id="live-display"></div>' . "\r\n"
507 . "<script> var profile_uid = " . $this->session->get('uid', 0) . ";"
510 } elseif ($mode === 'community') {
511 $items = $this->addChildren($items, true, $order, $uid, $mode);
514 $live_update_div = '<div id="live-community"></div>' . "\r\n"
515 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
517 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
518 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
519 . "'; </script>\r\n";
521 } elseif ($mode === 'contacts') {
522 $items = $this->addChildren($items, false, $order, $uid, $mode);
525 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
526 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
527 ."/?f='; </script>\r\n";
529 } elseif ($mode === 'search') {
530 $live_update_div = '<div id="live-search"></div>' . "\r\n";
533 $page_dropping = $this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $uid;
536 $_SESSION['return_path'] = $this->args->getQueryString();
539 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
540 Hook::callAll('conversation_start', $cb);
542 $items = $cb['items'];
553 if ($this->pConfig->get($this->userSession->getLocalUserId(), 'system', 'hide_dislike')) {
554 unset($conv_responses['dislike']);
557 // array with html for each thread (parent+comments)
561 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
562 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
564 if (!empty($items)) {
565 if (in_array($mode, ['community', 'contacts', 'profile'])) {
568 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
571 if (!$this->userSession->getLocalUserId()) {
575 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
578 * "New Item View" on network page or search page results
579 * - just loop through the items and format them minimally for display
582 $tpl = 'search_item.tpl';
586 foreach ($items as $item) {
587 if (in_array($item['uri-id'], $uriids)) {
591 $uriids[] = $item['uri-id'];
593 if (!$this->item->isVisibleActivity($item)) {
597 if (in_array($item['author-id'], $blocklist)) {
603 // prevent private email from leaking.
604 if ($item['network'] === Protocol::MAIL && $this->userSession->getLocalUserId() != $item['uid']) {
608 $profile_name = $item['author-name'];
609 if (!empty($item['author-link']) && empty($item['author-name'])) {
610 $profile_name = $item['author-link'];
613 $tags = Tag::populateFromItem($item);
615 $author = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
616 $profile_link = Contact::magicLinkByContact($author);
619 if (strpos($profile_link, 'redir/') === 0) {
620 $sparkle = ' sparkle';
623 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
624 Hook::callAll('render_location', $locate);
625 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
627 $this->item->localize($item);
628 if ($mode === 'filed') {
635 'dropping' => $dropping,
636 'pagedrop' => $page_dropping,
637 'select' => $this->l10n->t('Select'),
638 'delete' => $this->l10n->t('Delete'),
648 if ($this->pConfig->get($this->userSession->getLocalUserId(), 'system', 'hide_dislike')) {
649 unset($likebuttons['dislike']);
652 $body_html = ItemModel::prepareBody($item, true, $preview);
654 [$categories, $folders] = $this->item->determineCategoriesTerms($item, $this->userSession->getLocalUserId());
656 if (!empty($item['title'])) {
657 $title = $item['title'];
658 } elseif (!empty($item['content-warning']) && $this->pConfig->get($this->userSession->getLocalUserId(), 'system', 'disable_cw', false)) {
659 $title = ucfirst($item['content-warning']);
664 if (!empty($item['featured'])) {
665 $pinned = $this->l10n->t('Pinned item');
672 'id' => ($preview ? 'P0' : $item['id']),
673 'guid' => ($preview ? 'Q0' : $item['guid']),
674 'commented' => $item['commented'],
675 'received' => $item['received'],
676 'created_date' => $item['created'],
677 'uriid' => $item['uri-id'],
678 'network' => $item['network'],
679 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
680 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
681 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
682 'profile_url' => $profile_link,
683 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
684 'name' => $profile_name,
685 'sparkle' => $sparkle,
687 'thumb' => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
689 'body_html' => $body_html,
690 'tags' => $tags['tags'],
691 'hashtags' => $tags['hashtags'],
692 'mentions' => $tags['mentions'],
693 'implicit_mentions' => $tags['implicit_mentions'],
694 'txt_cats' => $this->l10n->t('Categories:'),
695 'txt_folders' => $this->l10n->t('Filed under:'),
696 'has_cats' => ((count($categories)) ? 'true' : ''),
697 'has_folders' => ((count($folders)) ? 'true' : ''),
698 'categories' => $categories,
699 'folders' => $folders,
700 'text' => strip_tags($body_html),
701 'localtime' => DateTimeFormat::local($item['created'], 'r'),
702 'utc' => DateTimeFormat::utc($item['created'], 'c'),
703 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
704 'location_html' => $location_html,
708 'owner_photo' => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
709 'plink' => ItemModel::getPlink($item),
712 'isstarred' => 'unstarred',
715 'vote' => $likebuttons,
717 'dislike_html ' => '',
718 'comment_html' => '',
719 'conv' => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
720 'previewing' => $previewing,
721 'wait' => $this->l10n->t('Please wait'),
725 $arr = ['item' => $item, 'output' => $tmp_item];
726 Hook::callAll('display_item', $arr);
728 $threads[$threadsid]['id'] = $item['id'];
729 $threads[$threadsid]['network'] = $item['network'];
730 $threads[$threadsid]['items'] = [$arr['output']];
734 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
736 $conv = new Thread($mode, $preview, $writable);
739 * get all the topmost parents
740 * this shouldn't be needed, as we should have only them in our array
741 * But for now, this array respects the old style, just in case
743 foreach ($items as $item) {
744 if (in_array($item['author-id'], $blocklist)) {
748 // Can we put this after the visibility check?
749 $this->builtinActivityPuller($item, $conv_responses);
751 // Only add what is visible
752 if ($item['network'] === Protocol::MAIL && $this->userSession->getLocalUserId() != $item['uid']) {
756 if (!$this->item->isVisibleActivity($item)) {
760 /// @todo Check if this call is needed or not
761 $arr = ['item' => $item];
762 Hook::callAll('display_item', $arr);
764 $item['pagedrop'] = $page_dropping;
766 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
767 $item_object = new PostObject($item);
768 $conv->addParent($item_object);
772 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
774 $this->logger->info('[ERROR] conversation : Failed to get template data.');
780 $o = Renderer::replaceMacros($page_template, [
781 '$baseurl' => $this->baseURL->get($ssl_state),
782 '$return_path' => $this->args->getQueryString(),
783 '$live_update' => $live_update_div,
784 '$remove' => $this->l10n->t('remove'),
786 '$update' => $update,
787 '$threads' => $threads,
788 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
791 $this->profiler->stopRecording();
795 private function getBlocklist(): array
797 if (!$this->userSession->getLocalUserId()) {
801 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get($this->userSession->getLocalUserId(), 'system', 'blocked'));
802 if (empty($str_blocked)) {
808 foreach (explode(',', $str_blocked) as $entry) {
809 $cid = Contact::getIdForURL(trim($entry), 0, false);
819 * Adds some information (Causer, post reason, direction) to the fetched post row.
821 * @param array $row Post row
822 * @param array $activity Contact data of the resharer
823 * @param array $thr_parent Thread parent row
825 * @return array items with parents and comments
827 private function addRowInformation(array $row, array $activity, array $thr_parent): array
829 $this->profiler->startRecording('rendering');
831 if (!$row['writable']) {
832 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
835 if (!empty($activity)) {
836 if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
837 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
839 $row = array_merge($row, $activity);
840 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
842 $row['causer-link'] = $contact['url'];
843 $row['causer-avatar'] = $contact['thumb'];
844 $row['causer-name'] = $contact['name'];
845 } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
846 ($row['author-id'] == $activity['causer-id'])) {
851 switch ($row['post-reason']) {
852 case ItemModel::PR_TO:
853 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
855 case ItemModel::PR_CC:
856 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
858 case ItemModel::PR_BTO:
859 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
861 case ItemModel::PR_BCC:
862 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
864 case ItemModel::PR_FOLLOWER:
865 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
867 case ItemModel::PR_TAG:
868 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
870 case ItemModel::PR_ANNOUNCEMENT:
871 if (!empty($row['causer-id']) && $this->pConfig->get($this->userSession->getLocalUserId(), 'system', 'display_resharer')) {
872 $row['owner-id'] = $row['causer-id'];
873 $row['owner-link'] = $row['causer-link'];
874 $row['owner-avatar'] = $row['causer-avatar'];
875 $row['owner-name'] = $row['causer-name'];
878 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
879 $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
881 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
883 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Reshared') : $this->l10n->t('Reshared by %s <%s>', $row['causer-name'], $row['causer-link']))];
885 case ItemModel::PR_COMMENT:
886 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
888 case ItemModel::PR_STORED:
889 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
891 case ItemModel::PR_GLOBAL:
892 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
894 case ItemModel::PR_RELAY:
895 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Sent via an relay server') : $this->l10n->t('Sent via the relay server %s <%s>', $row['causer-name'], $row['causer-link']))];
897 case ItemModel::PR_FETCHED:
898 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Fetched') : $this->l10n->t('Fetched because of %s <%s>', $row['causer-name'], $row['causer-link']))];
900 case ItemModel::PR_COMPLETION:
901 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
903 case ItemModel::PR_DIRECT:
904 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
906 case ItemModel::PR_ACTIVITY:
907 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
909 case ItemModel::PR_DISTRIBUTE:
910 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
912 case ItemModel::PR_PUSHED:
913 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
917 $row['thr-parent-row'] = $thr_parent;
919 $this->profiler->stopRecording();
924 * Add comments to top level entries that had been fetched before
926 * The system will fetch the comments for the local user whenever possible.
927 * This behaviour is currently needed to allow commenting on Friendica posts.
929 * @param array $parents Parent items
930 * @param bool $block_authors
933 * @param string $mode
934 * @return array items with parents and comments
935 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
937 private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode): array
939 $this->profiler->startRecording('rendering');
940 if (count($parents) > 1) {
941 $max_comments = $this->config->get('system', 'max_comments', 100);
943 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
948 $commentcounter = [];
949 $activitycounter = [];
951 foreach ($parents as $parent) {
952 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
953 $uriid = $parent['thr-parent-id'];
954 if (!empty($parent['author-id'])) {
955 $activities[$uriid] = ['causer-id' => $parent['author-id']];
956 foreach (['commented', 'received', 'created'] as $orderfields) {
957 if (!empty($parent[$orderfields])) {
958 $activities[$uriid][$orderfields] = $parent[$orderfields];
963 $uriid = $parent['uri-id'];
967 $commentcounter[$uriid] = 0;
968 $activitycounter[$uriid] = 0;
971 $condition = ['parent-uri-id' => $uriids];
972 if ($block_authors) {
973 $condition['author-hidden'] = false;
976 $condition = DBA::mergeConditions($condition,
977 ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
979 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
983 while ($row = Post::fetch($thread_parents)) {
984 $thr_parent[$row['uri-id']] = $row;
986 DBA::close($thread_parents);
988 $params = ['order' => ['uri-id' => true, 'uid' => true]];
990 $thread_items = Post::selectForUser($uid, array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
994 while ($row = Post::fetch($thread_items)) {
995 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
999 if (($mode != 'contacts') && !$row['origin']) {
1000 $row['featured'] = false;
1003 if ($max_comments > 0) {
1004 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
1007 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
1012 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
1015 DBA::close($thread_items);
1017 $items = $this->convSort($items, $order);
1019 $this->profiler->stopRecording();
1024 * Plucks the children of the given parent from a given item list.
1026 * @param array $item_list
1027 * @param array $parent
1028 * @param bool $recursive
1031 private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1033 $this->profiler->startRecording('rendering');
1035 foreach ($item_list as $i => $item) {
1036 if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1038 // Fallback to parent-uri if thr-parent is not set
1039 $thr_parent = $item['thr-parent-id'];
1040 if ($thr_parent == '') {
1041 $thr_parent = $item['parent-uri-id'];
1044 if ($thr_parent == $parent['uri-id']) {
1045 $item['children'] = $this->getItemChildren($item_list, $item);
1047 $children[] = $item;
1048 unset($item_list[$i]);
1050 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1051 $children[] = $item;
1052 unset($item_list[$i]);
1056 $this->profiler->stopRecording();
1061 * Recursively sorts a tree-like item array
1063 * @param array $items
1066 private function sortItemChildren(array $items): array
1068 $this->profiler->startRecording('rendering');
1070 usort($result, [$this, 'sortThrReceivedRev']);
1071 foreach ($result as $k => $i) {
1072 if (isset($result[$k]['children'])) {
1073 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1076 $this->profiler->stopRecording();
1081 * Recursively add all children items at the top level of a list
1083 * @param array $children List of items to append
1084 * @param array $item_list
1086 private function addChildrenToList(array $children, array &$item_list)
1088 foreach ($children as $child) {
1089 $item_list[] = $child;
1090 if (isset($child['children'])) {
1091 $this->addChildrenToList($child['children'], $item_list);
1097 * Selectively flattens a tree-like item structure to prevent threading stairs
1099 * This recursive function takes the item tree structure created by conv_sort() and
1100 * flatten the extraneous depth levels when people reply sequentially, removing the
1101 * stairs effect in threaded conversations limiting the available content width.
1103 * The basic principle is the following: if a post item has only one reply and is
1104 * the last reply of its parent, then the reply is moved to the parent.
1106 * This process is rendered somewhat more complicated because items can be either
1107 * replies or likes, and these don't factor at all in the reply count/last reply.
1109 * @param array $parent A tree-like array of items
1112 private function smartFlattenConversation(array $parent): array
1114 $this->profiler->startRecording('rendering');
1115 if (!isset($parent['children']) || count($parent['children']) == 0) {
1116 $this->profiler->stopRecording();
1120 // We use a for loop to ensure we process the newly-moved items
1121 for ($i = 0; $i < count($parent['children']); $i++) {
1122 $child = $parent['children'][$i];
1124 if (isset($child['children']) && count($child['children'])) {
1125 // This helps counting only the regular posts
1126 $count_post_closure = function ($var) {
1127 $this->profiler->stopRecording();
1128 return $var['verb'] === Activity::POST;
1131 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1133 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1135 // If there's only one child's children post and this is the last child post
1136 if ($child_post_count == 1 && $remaining_post_count == 1) {
1138 // Searches the post item in the children
1140 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1144 $moved_item = $child['children'][$j];
1145 unset($parent['children'][$i]['children'][$j]);
1146 $parent['children'][] = $moved_item;
1148 $parent['children'][$i] = $this->smartFlattenConversation($child);
1153 $this->profiler->stopRecording();
1158 * Expands a flat list of items into corresponding tree-like conversation structures.
1160 * sort the top-level posts either on "received" or "commented", and finally
1161 * append all the items at the top level (???)
1163 * @param array $item_list A list of items belonging to one or more conversations
1164 * @param string $order Either on "received" or "commented"
1166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1168 private function convSort(array $item_list, string $order): array
1170 $this->profiler->startRecording('rendering');
1173 if (!(is_array($item_list) && count($item_list))) {
1174 $this->profiler->stopRecording();
1178 $blocklist = $this->getBlocklist();
1182 // Dedupes the item list on the uri to prevent infinite loops
1183 foreach ($item_list as $item) {
1184 if (in_array($item['author-id'], $blocklist)) {
1188 $item_array[$item['uri-id']] = $item;
1191 // Extract the top level items
1192 foreach ($item_array as $item) {
1193 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1198 if (stristr($order, 'pinned_received')) {
1199 usort($parents, [$this, 'sortThrFeaturedReceived']);
1200 } elseif (stristr($order, 'pinned_commented')) {
1201 usort($parents, [$this, 'sortThrFeaturedCommented']);
1202 } elseif (stristr($order, 'received')) {
1203 usort($parents, [$this, 'sortThrReceived']);
1204 } elseif (stristr($order, 'commented')) {
1205 usort($parents, [$this, 'sortThrCommented']);
1206 } elseif (stristr($order, 'created')) {
1207 usort($parents, [$this, 'sortThrCreated']);
1211 * Plucks children from the item_array, second pass collects eventual orphan
1212 * items and add them as children of their top-level post.
1214 foreach ($parents as $i => $parent) {
1215 $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1216 $this->getItemChildren($item_array, $parent, false));
1219 foreach ($parents as $i => $parent) {
1220 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1223 if (!$this->pConfig->get($this->userSession->getLocalUserId(), 'system', 'no_smart_threading', 0)) {
1224 foreach ($parents as $i => $parent) {
1225 $parents[$i] = $this->smartFlattenConversation($parent);
1229 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1230 /// However, this apparently ensures responses (likes, attendance) display (?!)
1231 foreach ($parents as $parent) {
1232 if (count($parent['children'])) {
1233 $this->addChildrenToList($parent['children'], $parents);
1237 $this->profiler->stopRecording();
1242 * usort() callback to sort item arrays by featured and the received key
1248 private function sortThrFeaturedReceived(array $a, array $b): int
1250 if ($b['featured'] && !$a['featured']) {
1252 } elseif (!$b['featured'] && $a['featured']) {
1256 return strcmp($b['received'], $a['received']);
1260 * usort() callback to sort item arrays by featured and the received key
1266 private function sortThrFeaturedCommented(array $a, array $b): int
1268 if ($b['featured'] && !$a['featured']) {
1270 } elseif (!$b['featured'] && $a['featured']) {
1274 return strcmp($b['commented'], $a['commented']);
1278 * usort() callback to sort item arrays by the received key
1284 private function sortThrReceived(array $a, array $b): int
1286 return strcmp($b['received'], $a['received']);
1290 * usort() callback to reverse sort item arrays by the received key
1296 private function sortThrReceivedRev(array $a, array $b): int
1298 return strcmp($a['received'], $b['received']);
1302 * usort() callback to sort item arrays by the commented key
1308 private function sortThrCommented(array $a, array $b): int
1310 return strcmp($b['commented'], $a['commented']);
1314 * usort() callback to sort item arrays by the created key
1320 private function sortThrCreated(array $a, array $b): int
1322 return strcmp($b['created'], $a['created']);