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;
36 use Friendica\Core\Session\Capability\IHandleSessions;
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 */
84 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)
86 $this->activity = $activity;
88 $this->config = $config;
90 $this->baseURL = $baseURL;
91 $this->profiler = $profiler;
92 $this->logger = $logger;
95 $this->pConfig = $pConfig;
98 $this->session = $session;
102 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
104 * Increments the count of each matching activity and adds a link to the author as needed.
106 * @param array $activity
107 * @param array &$conv_responses (already created with builtin activity structure)
109 * @throws ImagickException
110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
112 public function builtinActivityPuller(array $activity, array &$conv_responses)
114 $thread_parent = $activity['thr-parent-row'] ?? [];
116 foreach ($conv_responses as $mode => $v) {
121 $verb = Activity::LIKE;
124 $verb = Activity::DISLIKE;
127 $verb = Activity::ATTEND;
130 $verb = Activity::ATTENDNO;
133 $verb = Activity::ATTENDMAYBE;
136 $verb = Activity::ANNOUNCE;
142 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
145 'id' => $activity['author-id'],
146 'network' => $activity['author-network'],
147 'url' => $activity['author-link']
149 $url = Contact::magicLinkByContact($author);
150 if (strpos($url, 'redir/') === 0) {
151 $sparkle = ' class="sparkle" ';
154 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
156 if (empty($activity['thr-parent-id'])) {
157 $activity['thr-parent-id'] = $activity['parent-uri-id'];
160 // Skip when the causer of the parent is the same as the author of the announce
161 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
165 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
166 $conv_responses[$mode][$activity['thr-parent-id']] = [
170 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
171 // only list each unique author once
175 if (Session::getPublicContact() == $activity['author-id']) {
176 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
179 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
181 // there can only be one activity verb per item so if we found anything, we can stop looking
188 * Format the activity text for an item/photo/video
190 * @param array $links = array of pre-linked names of actors
191 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
192 * @param int $id = item id
193 * @return string formatted text
194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196 public function formatActivity(array $links, string $verb, int $id): string
198 $this->profiler->startRecording('rendering');
203 $total = count($links);
207 // Phrase if there is only one liker. In other cases it will be uses for the expanded
208 // list which show all likers
211 $phrase = $this->l10n->t('%s likes this.', $likers);
214 $phrase = $this->l10n->t('%s doesn\'t like this.', $likers);
217 $phrase = $this->l10n->t('%s attends.', $likers);
220 $phrase = $this->l10n->t('%s doesn\'t attend.', $likers);
223 $phrase = $this->l10n->t('%s attends maybe.', $likers);
226 $phrase = $this->l10n->t('%s reshared this.', $likers);
229 } elseif ($total > 1) {
230 if ($total < $this->config->get('system', 'max_likers')) {
231 $likers = implode(', ', array_slice($links, 0, -1));
232 $likers .= ' ' . $this->l10n->t('and') . ' ' . $links[count($links) - 1];
234 $likers = implode(', ', array_slice($links, 0, $this->config->get('system', 'max_likers') - 1));
235 $likers .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
238 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
243 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
244 $explikers = $this->l10n->t('%s like this.', $likers);
247 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
248 $explikers = $this->l10n->t('%s don\'t like this.', $likers);
251 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
252 $explikers = $this->l10n->t('%s attend.', $likers);
255 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
256 $explikers = $this->l10n->t('%s don\'t attend.', $likers);
259 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
260 $explikers = $this->l10n->t('%s attend maybe.', $likers);
263 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
264 $explikers = $this->l10n->t('%s reshared this.', $likers);
268 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
271 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
272 '$phrase' => $phrase,
278 $this->profiler->stopRecording();
282 public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
284 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
285 if (empty($user['uid'])) {
289 $this->profiler->startRecording('rendering');
292 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
293 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
294 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
295 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
296 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
297 $x['bang'] = $x['bang'] ?? '';
298 $x['visitor'] = $x['visitor'] ?? 'block';
299 $x['is_owner'] = $x['is_owner'] ?? true;
300 $x['profile_uid'] = $x['profile_uid'] ?? Session::getLocalUser();
303 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
305 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
306 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
307 '$newpost' => 'true',
308 '$baseurl' => $this->baseURL->get(true),
309 '$geotag' => $geotag,
310 '$nickname' => $x['nickname'],
311 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
312 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
313 '$term' => $this->l10n->t('Tag term:'),
314 '$fileas' => $this->l10n->t('Save to Folder:'),
315 '$whereareu' => $this->l10n->t('Where are you right now?'),
316 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
317 '$is_mobile' => $this->mode->isMobile(),
321 Hook::callAll('jot_tool', $jotplugins);
323 if ($this->config->get('system', 'set_creation_date')) {
324 $created_at = Temporal::getDateTimeField(
325 new \DateTime(DBA::NULL_DATETIME),
326 new \DateTime('now'),
328 $this->l10n->t('Created at'),
335 $tpl = Renderer::getMarkupTemplate('jot.tpl');
337 $o .= Renderer::replaceMacros($tpl, [
338 '$new_post' => $this->l10n->t('New Post'),
339 '$return_path' => $this->args->getQueryString(),
341 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
342 '$loading' => $this->l10n->t('Loading...'),
343 '$upload' => $this->l10n->t('Upload photo'),
344 '$shortupload' => $this->l10n->t('upload photo'),
345 '$attach' => $this->l10n->t('Attach file'),
346 '$shortattach' => $this->l10n->t('attach file'),
347 '$edbold' => $this->l10n->t('Bold'),
348 '$editalic' => $this->l10n->t('Italic'),
349 '$eduline' => $this->l10n->t('Underline'),
350 '$edquote' => $this->l10n->t('Quote'),
351 '$edcode' => $this->l10n->t('Code'),
352 '$edimg' => $this->l10n->t('Image'),
353 '$edurl' => $this->l10n->t('Link'),
354 '$edattach' => $this->l10n->t('Link or Media'),
355 '$edvideo' => $this->l10n->t('Video'),
356 '$setloc' => $this->l10n->t('Set your location'),
357 '$shortsetloc' => $this->l10n->t('set location'),
358 '$noloc' => $this->l10n->t('Clear browser location'),
359 '$shortnoloc' => $this->l10n->t('clear location'),
360 '$title' => $x['title'] ?? '',
361 '$placeholdertitle' => $this->l10n->t('Set title'),
362 '$category' => $x['category'] ?? '',
363 '$placeholdercategory' => Feature::isEnabled(Session::getLocalUser(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
364 '$scheduled_at' => Temporal::getDateTimeField(
366 new \DateTime('now + 6 months'),
368 $this->l10n->t('Scheduled at'),
371 '$created_at' => $created_at,
372 '$wait' => $this->l10n->t('Please wait'),
373 '$permset' => $this->l10n->t('Permission settings'),
374 '$shortpermset' => $this->l10n->t('Permissions'),
375 '$wall' => $notes_cid ? 0 : 1,
376 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
377 '$content' => $x['content'] ?? '',
378 '$post_id' => $x['post_id'] ?? '',
379 '$baseurl' => $this->baseURL->get(true),
380 '$defloc' => $x['default_location'],
381 '$visitor' => $x['visitor'],
382 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
383 '$public' => $this->l10n->t('Public post'),
384 '$lockstate' => $x['lockstate'],
385 '$bang' => $x['bang'],
386 '$profile_uid' => $x['profile_uid'],
387 '$preview' => $this->l10n->t('Preview'),
388 '$jotplugins' => $jotplugins,
389 '$notes_cid' => $notes_cid,
390 '$cancel' => $this->l10n->t('Cancel'),
391 '$rand_num' => Crypto::randomDigits(12),
393 // ACL permissions box
396 //jot nav tab (used in some themes)
397 '$message' => $this->l10n->t('Message'),
398 '$browser' => $this->l10n->t('Browser'),
400 '$compose_link_title' => $this->l10n->t('Open Compose page'),
401 '$always_open_compose' => $this->pConfig->get(Session::getLocalUser(), 'frio', 'always_open_compose', false),
405 if ($popup == true) {
406 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
409 $this->profiler->stopRecording();
414 * "Render" a conversation or list of items for HTML display.
415 * There are two major forms of display:
416 * - Sequential or unthreaded ("New Item View" or search results)
417 * - conversation view
418 * The $mode parameter decides between the various renderings and also
419 * figures out how to determine page owner and other contextual items
420 * that are based on unique features of the calling module.
421 * @param array $items
422 * @param string $mode
423 * @param $update @TODO Which type?
424 * @param bool $preview
425 * @param string $order
428 * @throws ImagickException
429 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
431 public function create(array $items, string $mode, $update, bool $preview = false, string $order = 'commented', int $uid = 0): string
433 $this->profiler->startRecording('rendering');
435 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
436 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
437 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
438 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
440 $ssl_state = (bool)Session::getLocalUser();
442 $live_update_div = '';
444 $blocklist = $this->getBlocklist();
446 $previewing = (($preview) ? ' preview ' : '');
448 if ($mode === 'network') {
449 $items = $this->addChildren($items, false, $order, $uid, $mode);
452 * The special div is needed for liveUpdate to kick in for this page.
453 * We only launch liveUpdate if you aren't filtering in some incompatible
454 * way and also you aren't writing a comment (discovered in javascript).
456 $live_update_div = '<div id="live-network"></div>' . "\r\n"
457 . "<script> var profile_uid = " . $_SESSION['uid']
458 . "; var netargs = '" . substr($this->args->getCommand(), 8)
460 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
461 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
462 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
463 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
464 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
465 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
466 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
467 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
468 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
469 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
470 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
472 . "'; </script>\r\n";
474 } elseif ($mode === 'profile') {
475 $items = $this->addChildren($items, false, $order, $uid, $mode);
478 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
480 if ($tab === 'posts') {
482 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
483 * because browser prefetching might change it on us. We have to deliver it with the page.
486 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
487 . "<script> var profile_uid = " . $uid
488 . "; var netargs = '?f='; </script>\r\n";
491 } elseif ($mode === 'notes') {
492 $items = $this->addChildren($items, false, $order, Session::getLocalUser(), $mode);
495 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
496 . "<script> var profile_uid = " . Session::getLocalUser()
497 . "; var netargs = '/?f='; </script>\r\n";
499 } elseif ($mode === 'display') {
500 $items = $this->addChildren($items, false, $order, $uid, $mode);
503 $live_update_div = '<div id="live-display"></div>' . "\r\n"
504 . "<script> var profile_uid = " . $this->session->get('uid', 0) . ";"
507 } elseif ($mode === 'community') {
508 $items = $this->addChildren($items, true, $order, $uid, $mode);
511 $live_update_div = '<div id="live-community"></div>' . "\r\n"
512 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
514 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
515 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
516 . "'; </script>\r\n";
518 } elseif ($mode === 'contacts') {
519 $items = $this->addChildren($items, false, $order, $uid, $mode);
522 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
523 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
524 ."/?f='; </script>\r\n";
526 } elseif ($mode === 'search') {
527 $live_update_div = '<div id="live-search"></div>' . "\r\n";
530 $page_dropping = Session::getLocalUser() && Session::getLocalUser() == $uid;
533 $_SESSION['return_path'] = $this->args->getQueryString();
536 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
537 Hook::callAll('conversation_start', $cb);
539 $items = $cb['items'];
550 if ($this->pConfig->get(Session::getLocalUser(), 'system', 'hide_dislike')) {
551 unset($conv_responses['dislike']);
554 // array with html for each thread (parent+comments)
558 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
559 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
561 if (!empty($items)) {
562 if (in_array($mode, ['community', 'contacts', 'profile'])) {
565 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
568 if (!Session::getLocalUser()) {
572 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
575 * "New Item View" on network page or search page results
576 * - just loop through the items and format them minimally for display
579 $tpl = 'search_item.tpl';
583 foreach ($items as $item) {
584 if (in_array($item['uri-id'], $uriids)) {
588 $uriids[] = $item['uri-id'];
590 if (!$this->item->isVisibleActivity($item)) {
594 if (in_array($item['author-id'], $blocklist)) {
600 // prevent private email from leaking.
601 if ($item['network'] === Protocol::MAIL && Session::getLocalUser() != $item['uid']) {
605 $profile_name = $item['author-name'];
606 if (!empty($item['author-link']) && empty($item['author-name'])) {
607 $profile_name = $item['author-link'];
610 $tags = Tag::populateFromItem($item);
612 $author = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
613 $profile_link = Contact::magicLinkByContact($author);
616 if (strpos($profile_link, 'redir/') === 0) {
617 $sparkle = ' sparkle';
620 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
621 Hook::callAll('render_location', $locate);
622 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
624 $this->item->localize($item);
625 if ($mode === 'filed') {
632 'dropping' => $dropping,
633 'pagedrop' => $page_dropping,
634 'select' => $this->l10n->t('Select'),
635 'delete' => $this->l10n->t('Delete'),
645 if ($this->pConfig->get(Session::getLocalUser(), 'system', 'hide_dislike')) {
646 unset($likebuttons['dislike']);
649 $body_html = ItemModel::prepareBody($item, true, $preview);
651 [$categories, $folders] = $this->item->determineCategoriesTerms($item, Session::getLocalUser());
653 if (!empty($item['title'])) {
654 $title = $item['title'];
655 } elseif (!empty($item['content-warning']) && $this->pConfig->get(Session::getLocalUser(), 'system', 'disable_cw', false)) {
656 $title = ucfirst($item['content-warning']);
661 if (!empty($item['featured'])) {
662 $pinned = $this->l10n->t('Pinned item');
669 'id' => ($preview ? 'P0' : $item['id']),
670 'guid' => ($preview ? 'Q0' : $item['guid']),
671 'commented' => $item['commented'],
672 'received' => $item['received'],
673 'created_date' => $item['created'],
674 'uriid' => $item['uri-id'],
675 'network' => $item['network'],
676 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
677 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
678 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
679 'profile_url' => $profile_link,
680 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
681 'name' => $profile_name,
682 'sparkle' => $sparkle,
684 'thumb' => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
686 'body_html' => $body_html,
687 'tags' => $tags['tags'],
688 'hashtags' => $tags['hashtags'],
689 'mentions' => $tags['mentions'],
690 'implicit_mentions' => $tags['implicit_mentions'],
691 'txt_cats' => $this->l10n->t('Categories:'),
692 'txt_folders' => $this->l10n->t('Filed under:'),
693 'has_cats' => ((count($categories)) ? 'true' : ''),
694 'has_folders' => ((count($folders)) ? 'true' : ''),
695 'categories' => $categories,
696 'folders' => $folders,
697 'text' => strip_tags($body_html),
698 'localtime' => DateTimeFormat::local($item['created'], 'r'),
699 'utc' => DateTimeFormat::utc($item['created'], 'c'),
700 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
701 'location_html' => $location_html,
705 'owner_photo' => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
706 'plink' => ItemModel::getPlink($item),
709 'isstarred' => 'unstarred',
712 'vote' => $likebuttons,
714 'dislike_html ' => '',
715 'comment_html' => '',
716 'conv' => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
717 'previewing' => $previewing,
718 'wait' => $this->l10n->t('Please wait'),
722 $arr = ['item' => $item, 'output' => $tmp_item];
723 Hook::callAll('display_item', $arr);
725 $threads[$threadsid]['id'] = $item['id'];
726 $threads[$threadsid]['network'] = $item['network'];
727 $threads[$threadsid]['items'] = [$arr['output']];
731 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
733 $conv = new Thread($mode, $preview, $writable);
736 * get all the topmost parents
737 * this shouldn't be needed, as we should have only them in our array
738 * But for now, this array respects the old style, just in case
740 foreach ($items as $item) {
741 if (in_array($item['author-id'], $blocklist)) {
745 // Can we put this after the visibility check?
746 $this->builtinActivityPuller($item, $conv_responses);
748 // Only add what is visible
749 if ($item['network'] === Protocol::MAIL && Session::getLocalUser() != $item['uid']) {
753 if (!$this->item->isVisibleActivity($item)) {
757 /// @todo Check if this call is needed or not
758 $arr = ['item' => $item];
759 Hook::callAll('display_item', $arr);
761 $item['pagedrop'] = $page_dropping;
763 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
764 $item_object = new PostObject($item);
765 $conv->addParent($item_object);
769 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
771 $this->logger->info('[ERROR] conversation : Failed to get template data.');
777 $o = Renderer::replaceMacros($page_template, [
778 '$baseurl' => $this->baseURL->get($ssl_state),
779 '$return_path' => $this->args->getQueryString(),
780 '$live_update' => $live_update_div,
781 '$remove' => $this->l10n->t('remove'),
783 '$update' => $update,
784 '$threads' => $threads,
785 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
788 $this->profiler->stopRecording();
792 private function getBlocklist(): array
794 if (!Session::getLocalUser()) {
798 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get(Session::getLocalUser(), 'system', 'blocked'));
799 if (empty($str_blocked)) {
805 foreach (explode(',', $str_blocked) as $entry) {
806 $cid = Contact::getIdForURL(trim($entry), 0, false);
816 * Adds some information (Causer, post reason, direction) to the fetched post row.
818 * @param array $row Post row
819 * @param array $activity Contact data of the resharer
820 * @param array $thr_parent Thread parent row
822 * @return array items with parents and comments
824 private function addRowInformation(array $row, array $activity, array $thr_parent): array
826 $this->profiler->startRecording('rendering');
828 if (!$row['writable']) {
829 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
832 if (!empty($activity)) {
833 if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
834 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
836 $row = array_merge($row, $activity);
837 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
839 $row['causer-link'] = $contact['url'];
840 $row['causer-avatar'] = $contact['thumb'];
841 $row['causer-name'] = $contact['name'];
842 } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
843 ($row['author-id'] == $activity['causer-id'])) {
848 switch ($row['post-reason']) {
849 case ItemModel::PR_TO:
850 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
852 case ItemModel::PR_CC:
853 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
855 case ItemModel::PR_BTO:
856 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
858 case ItemModel::PR_BCC:
859 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
861 case ItemModel::PR_FOLLOWER:
862 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
864 case ItemModel::PR_TAG:
865 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
867 case ItemModel::PR_ANNOUNCEMENT:
868 if (!empty($row['causer-id']) && $this->pConfig->get(Session::getLocalUser(), 'system', 'display_resharer')) {
869 $row['owner-id'] = $row['causer-id'];
870 $row['owner-link'] = $row['causer-link'];
871 $row['owner-avatar'] = $row['causer-avatar'];
872 $row['owner-name'] = $row['causer-name'];
875 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
876 $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
878 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
880 $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']))];
882 case ItemModel::PR_COMMENT:
883 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
885 case ItemModel::PR_STORED:
886 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
888 case ItemModel::PR_GLOBAL:
889 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
891 case ItemModel::PR_RELAY:
892 $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']))];
894 case ItemModel::PR_FETCHED:
895 $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']))];
897 case ItemModel::PR_COMPLETION:
898 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
900 case ItemModel::PR_DIRECT:
901 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
903 case ItemModel::PR_ACTIVITY:
904 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
906 case ItemModel::PR_DISTRIBUTE:
907 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
909 case ItemModel::PR_PUSHED:
910 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
914 $row['thr-parent-row'] = $thr_parent;
916 $this->profiler->stopRecording();
921 * Add comments to top level entries that had been fetched before
923 * The system will fetch the comments for the local user whenever possible.
924 * This behaviour is currently needed to allow commenting on Friendica posts.
926 * @param array $parents Parent items
927 * @param bool $block_authors
930 * @param string $mode
931 * @return array items with parents and comments
932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
934 private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode): array
936 $this->profiler->startRecording('rendering');
937 if (count($parents) > 1) {
938 $max_comments = $this->config->get('system', 'max_comments', 100);
940 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
945 $commentcounter = [];
946 $activitycounter = [];
948 foreach ($parents as $parent) {
949 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
950 $uriid = $parent['thr-parent-id'];
951 if (!empty($parent['author-id'])) {
952 $activities[$uriid] = ['causer-id' => $parent['author-id']];
953 foreach (['commented', 'received', 'created'] as $orderfields) {
954 if (!empty($parent[$orderfields])) {
955 $activities[$uriid][$orderfields] = $parent[$orderfields];
960 $uriid = $parent['uri-id'];
964 $commentcounter[$uriid] = 0;
965 $activitycounter[$uriid] = 0;
968 $condition = ['parent-uri-id' => $uriids];
969 if ($block_authors) {
970 $condition['author-hidden'] = false;
973 $condition = DBA::mergeConditions($condition,
974 ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
976 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
980 while ($row = Post::fetch($thread_parents)) {
981 $thr_parent[$row['uri-id']] = $row;
983 DBA::close($thread_parents);
985 $params = ['order' => ['uri-id' => true, 'uid' => true]];
987 $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 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
1012 DBA::close($thread_items);
1014 $items = $this->convSort($items, $order);
1016 $this->profiler->stopRecording();
1021 * Plucks the children of the given parent from a given item list.
1023 * @param array $item_list
1024 * @param array $parent
1025 * @param bool $recursive
1028 private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1030 $this->profiler->startRecording('rendering');
1032 foreach ($item_list as $i => $item) {
1033 if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1035 // Fallback to parent-uri if thr-parent is not set
1036 $thr_parent = $item['thr-parent-id'];
1037 if ($thr_parent == '') {
1038 $thr_parent = $item['parent-uri-id'];
1041 if ($thr_parent == $parent['uri-id']) {
1042 $item['children'] = $this->getItemChildren($item_list, $item);
1044 $children[] = $item;
1045 unset($item_list[$i]);
1047 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1048 $children[] = $item;
1049 unset($item_list[$i]);
1053 $this->profiler->stopRecording();
1058 * Recursively sorts a tree-like item array
1060 * @param array $items
1063 private function sortItemChildren(array $items): array
1065 $this->profiler->startRecording('rendering');
1067 usort($result, [$this, 'sortThrReceivedRev']);
1068 foreach ($result as $k => $i) {
1069 if (isset($result[$k]['children'])) {
1070 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1073 $this->profiler->stopRecording();
1078 * Recursively add all children items at the top level of a list
1080 * @param array $children List of items to append
1081 * @param array $item_list
1083 private function addChildrenToList(array $children, array &$item_list)
1085 foreach ($children as $child) {
1086 $item_list[] = $child;
1087 if (isset($child['children'])) {
1088 $this->addChildrenToList($child['children'], $item_list);
1094 * Selectively flattens a tree-like item structure to prevent threading stairs
1096 * This recursive function takes the item tree structure created by conv_sort() and
1097 * flatten the extraneous depth levels when people reply sequentially, removing the
1098 * stairs effect in threaded conversations limiting the available content width.
1100 * The basic principle is the following: if a post item has only one reply and is
1101 * the last reply of its parent, then the reply is moved to the parent.
1103 * This process is rendered somewhat more complicated because items can be either
1104 * replies or likes, and these don't factor at all in the reply count/last reply.
1106 * @param array $parent A tree-like array of items
1109 private function smartFlattenConversation(array $parent): array
1111 $this->profiler->startRecording('rendering');
1112 if (!isset($parent['children']) || count($parent['children']) == 0) {
1113 $this->profiler->stopRecording();
1117 // We use a for loop to ensure we process the newly-moved items
1118 for ($i = 0; $i < count($parent['children']); $i++) {
1119 $child = $parent['children'][$i];
1121 if (isset($child['children']) && count($child['children'])) {
1122 // This helps counting only the regular posts
1123 $count_post_closure = function ($var) {
1124 $this->profiler->stopRecording();
1125 return $var['verb'] === Activity::POST;
1128 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1130 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1132 // If there's only one child's children post and this is the last child post
1133 if ($child_post_count == 1 && $remaining_post_count == 1) {
1135 // Searches the post item in the children
1137 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1141 $moved_item = $child['children'][$j];
1142 unset($parent['children'][$i]['children'][$j]);
1143 $parent['children'][] = $moved_item;
1145 $parent['children'][$i] = $this->smartFlattenConversation($child);
1150 $this->profiler->stopRecording();
1155 * Expands a flat list of items into corresponding tree-like conversation structures.
1157 * sort the top-level posts either on "received" or "commented", and finally
1158 * append all the items at the top level (???)
1160 * @param array $item_list A list of items belonging to one or more conversations
1161 * @param string $order Either on "received" or "commented"
1163 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1165 private function convSort(array $item_list, string $order): array
1167 $this->profiler->startRecording('rendering');
1170 if (!(is_array($item_list) && count($item_list))) {
1171 $this->profiler->stopRecording();
1175 $blocklist = $this->getBlocklist();
1179 // Dedupes the item list on the uri to prevent infinite loops
1180 foreach ($item_list as $item) {
1181 if (in_array($item['author-id'], $blocklist)) {
1185 $item_array[$item['uri-id']] = $item;
1188 // Extract the top level items
1189 foreach ($item_array as $item) {
1190 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1195 if (stristr($order, 'pinned_received')) {
1196 usort($parents, [$this, 'sortThrFeaturedReceived']);
1197 } elseif (stristr($order, 'pinned_commented')) {
1198 usort($parents, [$this, 'sortThrFeaturedCommented']);
1199 } elseif (stristr($order, 'received')) {
1200 usort($parents, [$this, 'sortThrReceived']);
1201 } elseif (stristr($order, 'commented')) {
1202 usort($parents, [$this, 'sortThrCommented']);
1203 } elseif (stristr($order, 'created')) {
1204 usort($parents, [$this, 'sortThrCreated']);
1208 * Plucks children from the item_array, second pass collects eventual orphan
1209 * items and add them as children of their top-level post.
1211 foreach ($parents as $i => $parent) {
1212 $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1213 $this->getItemChildren($item_array, $parent, false));
1216 foreach ($parents as $i => $parent) {
1217 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1220 if (!$this->pConfig->get(Session::getLocalUser(), 'system', 'no_smart_threading', 0)) {
1221 foreach ($parents as $i => $parent) {
1222 $parents[$i] = $this->smartFlattenConversation($parent);
1226 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1227 /// However, this apparently ensures responses (likes, attendance) display (?!)
1228 foreach ($parents as $parent) {
1229 if (count($parent['children'])) {
1230 $this->addChildrenToList($parent['children'], $parents);
1234 $this->profiler->stopRecording();
1239 * usort() callback to sort item arrays by featured and the received key
1245 private function sortThrFeaturedReceived(array $a, array $b): int
1247 if ($b['featured'] && !$a['featured']) {
1249 } elseif (!$b['featured'] && $a['featured']) {
1253 return strcmp($b['received'], $a['received']);
1257 * usort() callback to sort item arrays by featured and the received key
1263 private function sortThrFeaturedCommented(array $a, array $b): int
1265 if ($b['featured'] && !$a['featured']) {
1267 } elseif (!$b['featured'] && $a['featured']) {
1271 return strcmp($b['commented'], $a['commented']);
1275 * usort() callback to sort item arrays by the received key
1281 private function sortThrReceived(array $a, array $b): int
1283 return strcmp($b['received'], $a['received']);
1287 * usort() callback to reverse sort item arrays by the received key
1293 private function sortThrReceivedRev(array $a, array $b): int
1295 return strcmp($a['received'], $b['received']);
1299 * usort() callback to sort item arrays by the commented key
1305 private function sortThrCommented(array $a, array $b): int
1307 return strcmp($b['commented'], $a['commented']);
1311 * usort() callback to sort item arrays by the created key
1317 private function sortThrCreated(array $a, array $b): int
1319 return strcmp($b['created'], $a['created']);