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\IHandleUserSessions;
36 use Friendica\Core\Theme;
37 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Item as ItemModel;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Model\Verb;
44 use Friendica\Object\Post as PostObject;
45 use Friendica\Object\Thread;
46 use Friendica\Protocol\Activity;
47 use Friendica\Util\Crypto;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Profiler;
50 use Friendica\Util\Strings;
51 use Friendica\Util\Temporal;
52 use Psr\Log\LoggerInterface;
62 /** @var LoggerInterface */
66 /** @var App\Arguments */
68 /** @var IManagePersonalConfigValues */
72 /** @var IManageConfigValues */
80 /** @var IHandleUserSessions */
83 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, IHandleUserSessions $session)
85 $this->activity = $activity;
87 $this->config = $config;
89 $this->baseURL = $baseURL;
90 $this->profiler = $profiler;
91 $this->logger = $logger;
94 $this->pConfig = $pConfig;
97 $this->session = $session;
101 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
103 * Increments the count of each matching activity and adds a link to the author as needed.
105 * @param array $activity
106 * @param array &$conv_responses (already created with builtin activity structure)
108 * @throws ImagickException
109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
111 public function builtinActivityPuller(array $activity, array &$conv_responses)
113 $thread_parent = $activity['thr-parent-row'] ?? [];
115 foreach ($conv_responses as $mode => $v) {
120 $verb = Activity::LIKE;
123 $verb = Activity::DISLIKE;
126 $verb = Activity::ATTEND;
129 $verb = Activity::ATTENDNO;
132 $verb = Activity::ATTENDMAYBE;
135 $verb = Activity::ANNOUNCE;
141 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
144 'id' => $activity['author-id'],
145 'network' => $activity['author-network'],
146 'url' => $activity['author-link']
148 $url = Contact::magicLinkByContact($author);
149 if (strpos($url, 'contact/redir/') === 0) {
150 $sparkle = ' class="sparkle" ';
153 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
155 if (empty($activity['thr-parent-id'])) {
156 $activity['thr-parent-id'] = $activity['parent-uri-id'];
159 // Skip when the causer of the parent is the same as the author of the announce
160 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
164 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
165 $conv_responses[$mode][$activity['thr-parent-id']] = [
169 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
170 // only list each unique author once
174 if ($this->session->getPublicContactId() == $activity['author-id']) {
175 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
178 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
180 // there can only be one activity verb per item so if we found anything, we can stop looking
187 * Format the activity text for an item/photo/video
189 * @param array $links = array of pre-linked names of actors
190 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
191 * @param int $id = item id
192 * @return string formatted text
193 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
195 public function formatActivity(array $links, string $verb, int $id): string
197 $this->profiler->startRecording('rendering');
202 $total = count($links);
206 // Phrase if there is only one liker. In other cases it will be uses for the expanded
207 // list which show all likers
210 $phrase = $this->l10n->t('%s likes this.', $likers);
213 $phrase = $this->l10n->t('%s doesn\'t like this.', $likers);
216 $phrase = $this->l10n->t('%s attends.', $likers);
219 $phrase = $this->l10n->t('%s doesn\'t attend.', $likers);
222 $phrase = $this->l10n->t('%s attends maybe.', $likers);
225 $phrase = $this->l10n->t('%s reshared this.', $likers);
228 } elseif ($total > 1) {
229 if ($total < $this->config->get('system', 'max_likers')) {
230 $likers = implode(', ', array_slice($links, 0, -1));
231 $likers .= ' ' . $this->l10n->t('and') . ' ' . $links[count($links) - 1];
233 $likers = implode(', ', array_slice($links, 0, $this->config->get('system', 'max_likers') - 1));
234 $likers .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
237 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
242 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
243 $explikers = $this->l10n->t('%s like this.', $likers);
246 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
247 $explikers = $this->l10n->t('%s don\'t like this.', $likers);
250 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
251 $explikers = $this->l10n->t('%s attend.', $likers);
254 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
255 $explikers = $this->l10n->t('%s don\'t attend.', $likers);
258 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
259 $explikers = $this->l10n->t('%s attend maybe.', $likers);
262 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
263 $explikers = $this->l10n->t('%s reshared this.', $likers);
267 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
270 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
271 '$phrase' => $phrase,
277 $this->profiler->stopRecording();
281 public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
283 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
284 if (empty($user['uid'])) {
288 $this->profiler->startRecording('rendering');
291 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
292 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
293 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
294 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
295 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
296 $x['bang'] = $x['bang'] ?? '';
297 $x['visitor'] = $x['visitor'] ?? 'block';
298 $x['is_owner'] = $x['is_owner'] ?? true;
299 $x['profile_uid'] = $x['profile_uid'] ?? $this->session->getLocalUserId();
302 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
304 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
305 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
306 '$newpost' => 'true',
307 '$baseurl' => $this->baseURL->get(true),
308 '$geotag' => $geotag,
309 '$nickname' => $x['nickname'],
310 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
311 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
312 '$term' => $this->l10n->t('Tag term:'),
313 '$fileas' => $this->l10n->t('Save to Folder:'),
314 '$whereareu' => $this->l10n->t('Where are you right now?'),
315 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
316 '$is_mobile' => $this->mode->isMobile(),
320 Hook::callAll('jot_tool', $jotplugins);
322 if ($this->config->get('system', 'set_creation_date')) {
323 $created_at = Temporal::getDateTimeField(
324 new \DateTime(DBA::NULL_DATETIME),
325 new \DateTime('now'),
327 $this->l10n->t('Created at'),
334 $tpl = Renderer::getMarkupTemplate('jot.tpl');
336 $o .= Renderer::replaceMacros($tpl, [
337 '$new_post' => $this->l10n->t('New Post'),
338 '$return_path' => $this->args->getQueryString(),
340 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
341 '$loading' => $this->l10n->t('Loading...'),
342 '$upload' => $this->l10n->t('Upload photo'),
343 '$shortupload' => $this->l10n->t('upload photo'),
344 '$attach' => $this->l10n->t('Attach file'),
345 '$shortattach' => $this->l10n->t('attach file'),
346 '$edbold' => $this->l10n->t('Bold'),
347 '$editalic' => $this->l10n->t('Italic'),
348 '$eduline' => $this->l10n->t('Underline'),
349 '$edquote' => $this->l10n->t('Quote'),
350 '$edcode' => $this->l10n->t('Code'),
351 '$edimg' => $this->l10n->t('Image'),
352 '$edurl' => $this->l10n->t('Link'),
353 '$edattach' => $this->l10n->t('Link or Media'),
354 '$edvideo' => $this->l10n->t('Video'),
355 '$setloc' => $this->l10n->t('Set your location'),
356 '$shortsetloc' => $this->l10n->t('set location'),
357 '$noloc' => $this->l10n->t('Clear browser location'),
358 '$shortnoloc' => $this->l10n->t('clear location'),
359 '$title' => $x['title'] ?? '',
360 '$placeholdertitle' => $this->l10n->t('Set title'),
361 '$category' => $x['category'] ?? '',
362 '$placeholdercategory' => Feature::isEnabled($this->session->getLocalUserId(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
363 '$scheduled_at' => Temporal::getDateTimeField(
365 new \DateTime('now + 6 months'),
367 $this->l10n->t('Scheduled at'),
370 '$created_at' => $created_at,
371 '$wait' => $this->l10n->t('Please wait'),
372 '$permset' => $this->l10n->t('Permission settings'),
373 '$shortpermset' => $this->l10n->t('Permissions'),
374 '$wall' => $notes_cid ? 0 : 1,
375 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
376 '$content' => $x['content'] ?? '',
377 '$post_id' => $x['post_id'] ?? '',
378 '$baseurl' => $this->baseURL->get(true),
379 '$defloc' => $x['default_location'],
380 '$visitor' => $x['visitor'],
381 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
382 '$public' => $this->l10n->t('Public post'),
383 '$lockstate' => $x['lockstate'],
384 '$bang' => $x['bang'],
385 '$profile_uid' => $x['profile_uid'],
386 '$preview' => $this->l10n->t('Preview'),
387 '$jotplugins' => $jotplugins,
388 '$notes_cid' => $notes_cid,
389 '$cancel' => $this->l10n->t('Cancel'),
390 '$rand_num' => Crypto::randomDigits(12),
392 // ACL permissions box
395 //jot nav tab (used in some themes)
396 '$message' => $this->l10n->t('Message'),
397 '$browser' => $this->l10n->t('Browser'),
399 '$compose_link_title' => $this->l10n->t('Open Compose page'),
400 '$always_open_compose' => $this->pConfig->get($this->session->getLocalUserId(), 'frio', 'always_open_compose', false),
404 if ($popup == true) {
405 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
408 $this->profiler->stopRecording();
413 * "Render" a conversation or list of items for HTML display.
414 * There are two major forms of display:
415 * - Sequential or unthreaded ("New Item View" or search results)
416 * - conversation view
417 * The $mode parameter decides between the various renderings and also
418 * figures out how to determine page owner and other contextual items
419 * that are based on unique features of the calling module.
420 * @param array $items
421 * @param string $mode
422 * @param $update @TODO Which type?
423 * @param bool $preview
424 * @param string $order
427 * @throws ImagickException
428 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
430 public function create(array $items, string $mode, $update, bool $preview = false, string $order = 'commented', int $uid = 0): string
432 $this->profiler->startRecording('rendering');
434 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
435 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
436 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
437 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
439 $ssl_state = (bool)$this->session->getLocalUserId();
441 $live_update_div = '';
443 $blocklist = $this->getBlocklist();
445 $previewing = (($preview) ? ' preview ' : '');
447 if ($mode === 'network') {
448 $items = $this->addChildren($items, false, $order, $uid, $mode);
451 * The special div is needed for liveUpdate to kick in for this page.
452 * We only launch liveUpdate if you aren't filtering in some incompatible
453 * way and also you aren't writing a comment (discovered in javascript).
455 $live_update_div = '<div id="live-network"></div>' . "\r\n"
456 . "<script> var profile_uid = " . $_SESSION['uid']
457 . "; var netargs = '" . substr($this->args->getCommand(), 8)
459 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
460 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
461 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
462 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
463 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
464 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
465 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
466 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
467 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
468 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
469 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
471 . "'; </script>\r\n";
473 } elseif ($mode === 'profile') {
474 $items = $this->addChildren($items, false, $order, $uid, $mode);
477 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
479 if ($tab === 'posts') {
481 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
482 * because browser prefetching might change it on us. We have to deliver it with the page.
485 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
486 . "<script> var profile_uid = " . $uid
487 . "; var netargs = '?f='; </script>\r\n";
490 } elseif ($mode === 'notes') {
491 $items = $this->addChildren($items, false, $order, $this->session->getLocalUserId(), $mode);
494 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
495 . "<script> var profile_uid = " . $this->session->getLocalUserId()
496 . "; var netargs = '?f='; </script>\r\n";
498 } elseif ($mode === 'display') {
499 $items = $this->addChildren($items, false, $order, $uid, $mode);
502 $live_update_div = '<div id="live-display"></div>' . "\r\n"
503 . "<script> var profile_uid = " . ($this->session->getLocalUserId() ?: 0) . ";"
506 } elseif ($mode === 'community') {
507 $items = $this->addChildren($items, true, $order, $uid, $mode);
510 $live_update_div = '<div id="live-community"></div>' . "\r\n"
511 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
513 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
514 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
515 . "'; </script>\r\n";
517 } elseif ($mode === 'contacts') {
518 $items = $this->addChildren($items, false, $order, $uid, $mode);
521 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
522 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
523 ."?f='; </script>\r\n";
525 } elseif ($mode === 'search') {
526 $live_update_div = '<div id="live-search"></div>' . "\r\n";
529 $page_dropping = $this->session->getLocalUserId() && $this->session->getLocalUserId() == $uid && $mode != 'search';
532 $_SESSION['return_path'] = $this->args->getQueryString();
535 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
536 Hook::callAll('conversation_start', $cb);
538 $items = $cb['items'];
549 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
550 unset($conv_responses['dislike']);
553 // array with html for each thread (parent+comments)
557 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
558 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
560 if (!empty($items)) {
561 if (in_array($mode, ['community', 'contacts', 'profile'])) {
564 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
567 if (!$this->session->getLocalUserId()) {
571 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
574 * "New Item View" on network page or search page results
575 * - just loop through the items and format them minimally for display
578 $tpl = 'search_item.tpl';
582 foreach ($items as $item) {
583 if (in_array($item['uri-id'], $uriids)) {
587 $uriids[] = $item['uri-id'];
589 if (!$this->item->isVisibleActivity($item)) {
593 if (in_array($item['author-id'], $blocklist)) {
599 // prevent private email from leaking.
600 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
604 $profile_name = $item['author-name'];
605 if (!empty($item['author-link']) && empty($item['author-name'])) {
606 $profile_name = $item['author-link'];
609 $tags = Tag::populateFromItem($item);
611 $author = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
612 $profile_link = Contact::magicLinkByContact($author);
615 if (strpos($profile_link, 'contact/redir/') === 0) {
616 $sparkle = ' sparkle';
619 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
620 Hook::callAll('render_location', $locate);
621 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
623 $this->item->localize($item);
624 if ($mode === 'filed') {
631 'dropping' => $dropping,
632 'pagedrop' => $page_dropping,
633 'select' => $this->l10n->t('Select'),
634 'delete' => $this->l10n->t('Delete'),
644 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
645 unset($likebuttons['dislike']);
648 $body_html = ItemModel::prepareBody($item, true, $preview);
650 [$categories, $folders] = $this->item->determineCategoriesTerms($item, $this->session->getLocalUserId());
652 if (!empty($item['title'])) {
653 $title = $item['title'];
654 } elseif (!empty($item['content-warning']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'disable_cw', false)) {
655 $title = ucfirst($item['content-warning']);
660 if (!empty($item['featured'])) {
661 $pinned = $this->l10n->t('Pinned item');
668 'id' => ($preview ? 'P0' : $item['id']),
669 'guid' => ($preview ? 'Q0' : $item['guid']),
670 'commented' => $item['commented'],
671 'received' => $item['received'],
672 'created_date' => $item['created'],
673 'uriid' => $item['uri-id'],
674 'network' => $item['network'],
675 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
676 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
677 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
678 'profile_url' => $profile_link,
679 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
680 'name' => $profile_name,
681 'sparkle' => $sparkle,
683 'thumb' => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
685 'body_html' => $body_html,
686 'tags' => $tags['tags'],
687 'hashtags' => $tags['hashtags'],
688 'mentions' => $tags['mentions'],
689 'implicit_mentions' => $tags['implicit_mentions'],
690 'txt_cats' => $this->l10n->t('Categories:'),
691 'txt_folders' => $this->l10n->t('Filed under:'),
692 'has_cats' => ((count($categories)) ? 'true' : ''),
693 'has_folders' => ((count($folders)) ? 'true' : ''),
694 'categories' => $categories,
695 'folders' => $folders,
696 'text' => strip_tags($body_html),
697 'localtime' => DateTimeFormat::local($item['created'], 'r'),
698 'utc' => DateTimeFormat::utc($item['created'], 'c'),
699 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
700 'location_html' => $location_html,
704 'owner_photo' => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
705 'plink' => ItemModel::getPlink($item),
708 'isstarred' => 'unstarred',
711 'vote' => $likebuttons,
713 'dislike_html ' => '',
714 'comment_html' => '',
715 'conv' => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
716 'previewing' => $previewing,
717 'wait' => $this->l10n->t('Please wait'),
721 $arr = ['item' => $item, 'output' => $tmp_item];
722 Hook::callAll('display_item', $arr);
724 $threads[$threadsid]['id'] = $item['id'];
725 $threads[$threadsid]['network'] = $item['network'];
726 $threads[$threadsid]['items'] = [$arr['output']];
730 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
732 $conv = new Thread($mode, $preview, $writable);
735 * get all the topmost parents
736 * this shouldn't be needed, as we should have only them in our array
737 * But for now, this array respects the old style, just in case
739 foreach ($items as $item) {
740 if (in_array($item['author-id'], $blocklist)) {
744 // Can we put this after the visibility check?
745 $this->builtinActivityPuller($item, $conv_responses);
747 // Only add what is visible
748 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
752 if (!$this->item->isVisibleActivity($item)) {
756 /// @todo Check if this call is needed or not
757 $arr = ['item' => $item];
758 Hook::callAll('display_item', $arr);
760 $item['pagedrop'] = $page_dropping;
762 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
763 $item_object = new PostObject($item);
764 $conv->addParent($item_object);
768 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
770 $this->logger->info('[ERROR] conversation : Failed to get template data.');
776 $o = Renderer::replaceMacros($page_template, [
777 '$baseurl' => $this->baseURL->get($ssl_state),
778 '$return_path' => $this->args->getQueryString(),
779 '$live_update' => $live_update_div,
780 '$remove' => $this->l10n->t('remove'),
782 '$update' => $update,
783 '$threads' => $threads,
784 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
787 $this->profiler->stopRecording();
791 private function getBlocklist(): array
793 if (!$this->session->getLocalUserId()) {
797 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get($this->session->getLocalUserId(), 'system', 'blocked') ?? '');
798 if (empty($str_blocked)) {
804 foreach (explode(',', $str_blocked) as $entry) {
805 $cid = Contact::getIdForURL(trim($entry), 0, false);
815 * Adds some information (Causer, post reason, direction) to the fetched post row.
817 * @param array $row Post row
818 * @param array $activity Contact data of the resharer
819 * @param array $thr_parent Thread parent row
821 * @return array items with parents and comments
823 private function addRowInformation(array $row, array $activity, array $thr_parent): array
825 $this->profiler->startRecording('rendering');
827 if (!$row['writable']) {
828 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
831 if (!empty($activity)) {
832 if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
833 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
835 $row = array_merge($row, $activity);
836 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
838 $row['causer-link'] = $contact['url'];
839 $row['causer-avatar'] = $contact['thumb'];
840 $row['causer-name'] = $contact['name'];
841 } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
842 ($row['author-id'] == $activity['causer-id'])) {
847 switch ($row['post-reason']) {
848 case ItemModel::PR_TO:
849 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
851 case ItemModel::PR_CC:
852 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
854 case ItemModel::PR_BTO:
855 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
857 case ItemModel::PR_BCC:
858 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
860 case ItemModel::PR_FOLLOWER:
861 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
863 case ItemModel::PR_TAG:
864 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
866 case ItemModel::PR_ANNOUNCEMENT:
867 if (!empty($row['causer-id']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'display_resharer')) {
868 $row['owner-id'] = $row['causer-id'];
869 $row['owner-link'] = $row['causer-link'];
870 $row['owner-avatar'] = $row['causer-avatar'];
871 $row['owner-name'] = $row['causer-name'];
874 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
875 $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
877 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
879 $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']))];
881 case ItemModel::PR_COMMENT:
882 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
884 case ItemModel::PR_STORED:
885 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
887 case ItemModel::PR_GLOBAL:
888 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
890 case ItemModel::PR_RELAY:
891 $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']))];
893 case ItemModel::PR_FETCHED:
894 $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']))];
896 case ItemModel::PR_COMPLETION:
897 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
899 case ItemModel::PR_DIRECT:
900 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
902 case ItemModel::PR_ACTIVITY:
903 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
905 case ItemModel::PR_DISTRIBUTE:
906 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
908 case ItemModel::PR_PUSHED:
909 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
913 $row['thr-parent-row'] = $thr_parent;
915 $this->profiler->stopRecording();
920 * Add comments to top level entries that had been fetched before
922 * The system will fetch the comments for the local user whenever possible.
923 * This behaviour is currently needed to allow commenting on Friendica posts.
925 * @param array $parents Parent items
926 * @param bool $block_authors
929 * @param string $mode
930 * @return array items with parents and comments
931 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
933 private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode): array
935 $this->profiler->startRecording('rendering');
936 if (count($parents) > 1) {
937 $max_comments = $this->config->get('system', 'max_comments', 100);
939 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
944 $commentcounter = [];
945 $activitycounter = [];
947 foreach ($parents as $parent) {
948 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
949 $uriid = $parent['thr-parent-id'];
950 if (!empty($parent['author-id'])) {
951 $activities[$uriid] = ['causer-id' => $parent['author-id']];
952 foreach (['commented', 'received', 'created'] as $orderfields) {
953 if (!empty($parent[$orderfields])) {
954 $activities[$uriid][$orderfields] = $parent[$orderfields];
959 $uriid = $parent['uri-id'];
963 $commentcounter[$uriid] = 0;
964 $activitycounter[$uriid] = 0;
967 $condition = ['parent-uri-id' => $uriids];
968 if ($block_authors) {
969 $condition['author-hidden'] = false;
972 $condition = DBA::mergeConditions($condition,
973 ["`uid` IN (0, ?) AND (NOT `vid` IN (?, ?) OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW), Verb::getID(Activity::VIEW)]);
975 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
979 while ($row = Post::fetch($thread_parents)) {
980 $thr_parent[$row['uri-id']] = $row;
982 DBA::close($thread_parents);
984 $params = ['order' => ['uri-id' => true, 'uid' => true]];
986 $thread_items = Post::selectForUser($uid, array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
991 while ($row = Post::fetch($thread_items)) {
992 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
996 if (($mode != 'contacts') && !$row['origin']) {
997 $row['featured'] = false;
1000 if ($max_comments > 0) {
1001 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
1004 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
1009 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT])) {
1010 $quoteuriids[$row['uri-id']] = [
1011 'uri-id' => $row['uri-id'],
1012 'uri' => $row['uri'],
1013 'parent-uri-id' => $row['parent-uri-id'],
1014 'parent-uri' => $row['parent-uri'],
1018 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
1021 DBA::close($thread_items);
1023 $quotes = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), ['quote-uri-id' => array_column($quoteuriids, 'uri-id'), 'body' => '', 'uid' => 0]);
1024 while ($quote = Post::fetch($quotes)) {
1028 $row['verb'] = $row['body'] = $row['raw-body'] = Activity::ANNOUNCE;
1029 $row['gravity'] = ItemModel::GRAVITY_ACTIVITY;
1030 $row['object-type'] = Activity\ObjectType::NOTE;
1031 $row['parent-uri'] = $quoteuriids[$quote['quote-uri-id']]['parent-uri'];
1032 $row['parent-uri-id'] = $quoteuriids[$quote['quote-uri-id']]['parent-uri-id'];
1033 $row['thr-parent'] = $quoteuriids[$quote['quote-uri-id']]['uri'];
1034 $row['thr-parent-id'] = $quoteuriids[$quote['quote-uri-id']]['uri-id'];
1036 $items[$row['uri-id']] = $this->addRowInformation($row, [], []);
1038 DBA::close($quotes);
1040 $items = $this->convSort($items, $order);
1042 $this->profiler->stopRecording();
1047 * Plucks the children of the given parent from a given item list.
1049 * @param array $item_list
1050 * @param array $parent
1051 * @param bool $recursive
1054 private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1056 $this->profiler->startRecording('rendering');
1058 foreach ($item_list as $i => $item) {
1059 if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1061 // Fallback to parent-uri if thr-parent is not set
1062 $thr_parent = $item['thr-parent-id'];
1063 if ($thr_parent == '') {
1064 $thr_parent = $item['parent-uri-id'];
1067 if ($thr_parent == $parent['uri-id']) {
1068 $item['children'] = $this->getItemChildren($item_list, $item);
1070 $children[] = $item;
1071 unset($item_list[$i]);
1073 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1074 $children[] = $item;
1075 unset($item_list[$i]);
1079 $this->profiler->stopRecording();
1084 * Recursively sorts a tree-like item array
1086 * @param array $items
1089 private function sortItemChildren(array $items): array
1091 $this->profiler->startRecording('rendering');
1093 usort($result, [$this, 'sortThrReceivedRev']);
1094 foreach ($result as $k => $i) {
1095 if (isset($result[$k]['children'])) {
1096 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1099 $this->profiler->stopRecording();
1104 * Recursively add all children items at the top level of a list
1106 * @param array $children List of items to append
1107 * @param array $item_list
1109 private function addChildrenToList(array $children, array &$item_list)
1111 foreach ($children as $child) {
1112 $item_list[] = $child;
1113 if (isset($child['children'])) {
1114 $this->addChildrenToList($child['children'], $item_list);
1120 * Selectively flattens a tree-like item structure to prevent threading stairs
1122 * This recursive function takes the item tree structure created by conv_sort() and
1123 * flatten the extraneous depth levels when people reply sequentially, removing the
1124 * stairs effect in threaded conversations limiting the available content width.
1126 * The basic principle is the following: if a post item has only one reply and is
1127 * the last reply of its parent, then the reply is moved to the parent.
1129 * This process is rendered somewhat more complicated because items can be either
1130 * replies or likes, and these don't factor at all in the reply count/last reply.
1132 * @param array $parent A tree-like array of items
1135 private function smartFlattenConversation(array $parent): array
1137 $this->profiler->startRecording('rendering');
1138 if (!isset($parent['children']) || count($parent['children']) == 0) {
1139 $this->profiler->stopRecording();
1143 // We use a for loop to ensure we process the newly-moved items
1144 for ($i = 0; $i < count($parent['children']); $i++) {
1145 $child = $parent['children'][$i];
1147 if (isset($child['children']) && count($child['children'])) {
1148 // This helps counting only the regular posts
1149 $count_post_closure = function ($var) {
1150 $this->profiler->stopRecording();
1151 return $var['verb'] === Activity::POST;
1154 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1156 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1158 // If there's only one child's children post and this is the last child post
1159 if ($child_post_count == 1 && $remaining_post_count == 1) {
1161 // Searches the post item in the children
1163 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1167 $moved_item = $child['children'][$j];
1168 unset($parent['children'][$i]['children'][$j]);
1169 $parent['children'][] = $moved_item;
1171 $parent['children'][$i] = $this->smartFlattenConversation($child);
1176 $this->profiler->stopRecording();
1181 * Expands a flat list of items into corresponding tree-like conversation structures.
1183 * sort the top-level posts either on "received" or "commented", and finally
1184 * append all the items at the top level (???)
1186 * @param array $item_list A list of items belonging to one or more conversations
1187 * @param string $order Either on "received" or "commented"
1189 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1191 private function convSort(array $item_list, string $order): array
1193 $this->profiler->startRecording('rendering');
1196 if (!(is_array($item_list) && count($item_list))) {
1197 $this->profiler->stopRecording();
1201 $blocklist = $this->getBlocklist();
1205 // Dedupes the item list on the uri to prevent infinite loops
1206 foreach ($item_list as $item) {
1207 if (in_array($item['author-id'], $blocklist)) {
1211 $item_array[$item['uri-id']] = $item;
1214 // Extract the top level items
1215 foreach ($item_array as $item) {
1216 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1221 if (stristr($order, 'pinned_received')) {
1222 usort($parents, [$this, 'sortThrFeaturedReceived']);
1223 } elseif (stristr($order, 'pinned_commented')) {
1224 usort($parents, [$this, 'sortThrFeaturedCommented']);
1225 } elseif (stristr($order, 'received')) {
1226 usort($parents, [$this, 'sortThrReceived']);
1227 } elseif (stristr($order, 'commented')) {
1228 usort($parents, [$this, 'sortThrCommented']);
1229 } elseif (stristr($order, 'created')) {
1230 usort($parents, [$this, 'sortThrCreated']);
1234 * Plucks children from the item_array, second pass collects eventual orphan
1235 * items and add them as children of their top-level post.
1237 foreach ($parents as $i => $parent) {
1238 $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1239 $this->getItemChildren($item_array, $parent, false));
1242 foreach ($parents as $i => $parent) {
1243 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1246 if (!$this->pConfig->get($this->session->getLocalUserId(), 'system', 'no_smart_threading', 0)) {
1247 foreach ($parents as $i => $parent) {
1248 $parents[$i] = $this->smartFlattenConversation($parent);
1252 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1253 /// However, this apparently ensures responses (likes, attendance) display (?!)
1254 foreach ($parents as $parent) {
1255 if (count($parent['children'])) {
1256 $this->addChildrenToList($parent['children'], $parents);
1260 $this->profiler->stopRecording();
1265 * usort() callback to sort item arrays by featured and the received key
1271 private function sortThrFeaturedReceived(array $a, array $b): int
1273 if ($b['featured'] && !$a['featured']) {
1275 } elseif (!$b['featured'] && $a['featured']) {
1279 return strcmp($b['received'], $a['received']);
1283 * usort() callback to sort item arrays by featured and the received key
1289 private function sortThrFeaturedCommented(array $a, array $b): int
1291 if ($b['featured'] && !$a['featured']) {
1293 } elseif (!$b['featured'] && $a['featured']) {
1297 return strcmp($b['commented'], $a['commented']);
1301 * usort() callback to sort item arrays by the received key
1307 private function sortThrReceived(array $a, array $b): int
1309 return strcmp($b['received'], $a['received']);
1313 * usort() callback to reverse sort item arrays by the received key
1319 private function sortThrReceivedRev(array $a, array $b): int
1321 return strcmp($a['received'], $b['received']);
1325 * usort() callback to sort item arrays by the commented key
1331 private function sortThrCommented(array $a, array $b): int
1333 return strcmp($b['commented'], $a['commented']);
1337 * usort() callback to sort item arrays by the created key
1343 private function sortThrCreated(array $a, array $b): int
1345 return strcmp($b['created'], $a['created']);