3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\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\Post\Category;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Network\HTTPException\InternalServerErrorException;
46 use Friendica\Object\Post as PostObject;
47 use Friendica\Object\Thread;
48 use Friendica\Protocol\Activity;
49 use Friendica\User\Settings\Entity\UserGServer;
50 use Friendica\User\Settings\Repository;
51 use Friendica\Util\Crypto;
52 use Friendica\Util\DateTimeFormat;
53 use Friendica\Util\Profiler;
54 use Friendica\Util\Strings;
55 use Friendica\Util\Temporal;
56 use Psr\Log\LoggerInterface;
60 const MODE_COMMUNITY = 'community';
61 const MODE_CONTACTS = 'contacts';
62 const MODE_CONTACT_POSTS = 'contact-posts';
63 const MODE_DISPLAY = 'display';
64 const MODE_FILED = 'filed';
65 const MODE_NETWORK = 'network';
66 const MODE_NOTES = 'notes';
67 const MODE_SEARCH = 'search';
68 const MODE_PROFILE = 'profile';
76 /** @var LoggerInterface */
80 /** @var App\Arguments */
82 /** @var IManagePersonalConfigValues */
86 /** @var IManageConfigValues */
94 /** @var IHandleUserSessions */
96 /** @var Repository\UserGServer */
99 public function __construct(Repository\UserGServer $userGServer, 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)
101 $this->activity = $activity;
103 $this->config = $config;
105 $this->baseURL = $baseURL;
106 $this->profiler = $profiler;
107 $this->logger = $logger;
110 $this->pConfig = $pConfig;
113 $this->session = $session;
114 $this->userGServer = $userGServer;
118 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
120 * Increments the count of each matching activity and adds a link to the author as needed.
122 * @param array $activity
123 * @param array &$conv_responses (already created with builtin activity structure)
125 * @throws ImagickException
126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128 public function builtinActivityPuller(array $activity, array &$conv_responses)
130 $thread_parent = $activity['thr-parent-row'] ?? [];
132 foreach ($conv_responses as $mode => $v) {
137 $verb = Activity::LIKE;
140 $verb = Activity::DISLIKE;
143 $verb = Activity::ATTEND;
146 $verb = Activity::ATTENDNO;
149 $verb = Activity::ATTENDMAYBE;
152 $verb = Activity::ANNOUNCE;
158 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
161 'id' => $activity['author-id'],
162 'network' => $activity['author-network'],
163 'url' => $activity['author-link'],
164 'alias' => $activity['author-alias'],
166 $url = Contact::magicLinkByContact($author);
167 if (strpos($url, 'contact/redir/') === 0) {
168 $sparkle = ' class="sparkle" ';
171 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
173 if (empty($activity['thr-parent-id'])) {
174 $activity['thr-parent-id'] = $activity['parent-uri-id'];
177 // Skip when the causer of the parent is the same as the author of the announce
178 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
182 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
183 $conv_responses[$mode][$activity['thr-parent-id']] = [
187 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
188 // only list each unique author once
192 if ($this->session->getPublicContactId() == $activity['author-id']) {
193 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
196 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
198 // there can only be one activity verb per item so if we found anything, we can stop looking
205 * Returns the liker phrase based on a list of likers
207 * @param string $verb the activity verb
208 * @param array $likers a list of likers
210 * @return string the liker phrase
212 * @throws InternalServerErrorException in case either the verb is invalid or the list of likers is empty
214 private function getLikerPhrase(string $verb, array $likers): string
216 $total = count($likers);
219 throw new InternalServerErrorException(sprintf('There has to be at least one Liker for verb "%s"', $verb));
220 } else if ($total === 1) {
221 $likerString = $likers[0];
223 if ($total < $this->config->get('system', 'max_likers')) {
224 $likerString = implode(', ', array_slice($likers, 0, -1));
225 $likerString .= ' ' . $this->l10n->t('and') . ' ' . $likers[count($likers) - 1];
227 $likerString = implode(', ', array_slice($likers, 0, $this->config->get('system', 'max_likers') - 1));
228 $likerString .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
234 return $this->l10n->tt('%2$s likes this.', '%2$s like this.', $total, $likerString);
236 return $this->l10n->tt('%2$s doesn\'t like this.', '%2$s don\'t like this.', $total, $likerString);
238 return $this->l10n->tt('%2$s attends.', '%2$s attend.', $total, $likerString);
240 return $this->l10n->tt('%2$s doesn\'t attend.', '%2$s don\'t attend.', $total, $likerString);
242 return $this->l10n->tt('%2$s attends maybe.', '%2$s attend maybe.', $total, $likerString);
244 return $this->l10n->tt('%2$s reshared this.', '%2$s reshared this.', $total, $likerString);
246 throw new InternalServerErrorException(sprintf('Unknown verb "%s"', $verb));
251 * Format the activity text for an item/photo/video
253 * @param array $links = array of pre-linked names of actors
254 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
255 * @param int $id = item id
256 * @return string formatted text
257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259 public function formatActivity(array $links, string $verb, int $id): string
261 $this->profiler->startRecording('rendering');
264 $phrase = $this->getLikerPhrase($verb, $links);
265 $total = count($links);
268 $spanatts = "class=\"btn btn-link fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
269 $explikers = $phrase;
273 $phrase = $this->l10n->tt('<button type="button" %2$s>%1$d person</button> likes this', '<button type="button" %2$s>%1$d people</button> like this', $total, $spanatts);
276 $phrase = $this->l10n->tt('<button type="button" %2$s>%1$d person</button> doesn\'t like this', '<button type="button" %2$s>%1$d peiple</button> don\'t like this', $total, $spanatts);
279 $phrase = $this->l10n->tt('<button type="button" %2$s>%1$d person</button> attends', '<button type="button" %2$s>%1$d people</button> attend', $total, $spanatts);
282 $phrase = $this->l10n->tt('<button type="button" %2$s>%1$d person</button> doesn\'t attend', '<button type="button" %2$s>%1$d people</button> don\'t attend', $total, $spanatts);
285 $phrase = $this->l10n->tt('<button type="button" %2$s>%1$d person</button> attends maybe', '<button type="button" %2$s>%1$d people</button> attend maybe', $total, $spanatts);
288 $phrase = $this->l10n->tt('<button type="button" %2$s>%1$d person</button> reshared this', '<button type="button" %2$s>%1$d people</button> reshared this', $total, $spanatts);
292 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
295 $output = Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
296 '$phrase' => $phrase,
300 $output .= $expanded;
302 $this->profiler->stopRecording();
306 public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
308 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
309 if (empty($user['uid'])) {
313 $this->profiler->startRecording('rendering');
316 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
317 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
318 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
319 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
320 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
321 $x['bang'] = $x['bang'] ?? '';
322 $x['visitor'] = $x['visitor'] ?? 'block';
323 $x['is_owner'] = $x['is_owner'] ?? true;
324 $x['profile_uid'] = $x['profile_uid'] ?? $this->session->getLocalUserId();
327 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
329 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
330 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
331 '$newpost' => 'true',
332 '$baseurl' => $this->baseURL,
333 '$geotag' => $geotag,
334 '$nickname' => $x['nickname'],
335 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
336 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
337 '$term' => $this->l10n->t('Tag term:'),
338 '$fileas' => $this->l10n->t('Save to Folder:'),
339 '$whereareu' => $this->l10n->t('Where are you right now?'),
340 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
341 '$is_mobile' => $this->mode->isMobile(),
345 Hook::callAll('jot_tool', $jotplugins);
347 if ($this->config->get('system', 'set_creation_date')) {
348 $created_at = Temporal::getDateTimeField(
349 new \DateTime(DBA::NULL_DATETIME),
350 new \DateTime('now'),
352 $this->l10n->t('Created at'),
359 $tpl = Renderer::getMarkupTemplate('jot.tpl');
361 $o .= Renderer::replaceMacros($tpl, [
362 '$new_post' => $this->l10n->t('New Post'),
363 '$return_path' => $this->args->getQueryString(),
365 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
366 '$loading' => $this->l10n->t('Loading...'),
367 '$upload' => $this->l10n->t('Upload photo'),
368 '$shortupload' => $this->l10n->t('upload photo'),
369 '$attach' => $this->l10n->t('Attach file'),
370 '$shortattach' => $this->l10n->t('attach file'),
371 '$edbold' => $this->l10n->t('Bold'),
372 '$editalic' => $this->l10n->t('Italic'),
373 '$eduline' => $this->l10n->t('Underline'),
374 '$edquote' => $this->l10n->t('Quote'),
375 '$edemojis' => $this->l10n->t('Add emojis'),
376 '$contentwarn' => $this->l10n->t('Content Warning'),
377 '$edcode' => $this->l10n->t('Code'),
378 '$edimg' => $this->l10n->t('Image'),
379 '$edurl' => $this->l10n->t('Link'),
380 '$edattach' => $this->l10n->t('Link or Media'),
381 '$edvideo' => $this->l10n->t('Video'),
382 '$setloc' => $this->l10n->t('Set your location'),
383 '$shortsetloc' => $this->l10n->t('set location'),
384 '$noloc' => $this->l10n->t('Clear browser location'),
385 '$shortnoloc' => $this->l10n->t('clear location'),
386 '$title' => $x['title'] ?? '',
387 '$placeholdertitle' => $this->l10n->t('Set title'),
388 '$category' => $x['category'] ?? '',
389 '$placeholdercategory' => Feature::isEnabled($this->session->getLocalUserId(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
390 '$scheduled_at' => Temporal::getDateTimeField(
392 new \DateTime('now + 6 months'),
394 $this->l10n->t('Scheduled at'),
397 '$created_at' => $created_at,
398 '$wait' => $this->l10n->t('Please wait'),
399 '$permset' => $this->l10n->t('Permission settings'),
400 '$shortpermset' => $this->l10n->t('Permissions'),
401 '$wall' => $notes_cid ? 0 : 1,
402 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
403 '$content' => $x['content'] ?? '',
404 '$post_id' => $x['post_id'] ?? '',
405 '$baseurl' => $this->baseURL,
406 '$defloc' => $x['default_location'],
407 '$visitor' => $x['visitor'],
408 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
409 '$public' => $this->l10n->t('Public post'),
410 '$lockstate' => $x['lockstate'],
411 '$bang' => $x['bang'],
412 '$profile_uid' => $x['profile_uid'],
413 '$preview' => $this->l10n->t('Preview'),
414 '$jotplugins' => $jotplugins,
415 '$notes_cid' => $notes_cid,
416 '$cancel' => $this->l10n->t('Cancel'),
417 '$rand_num' => Crypto::randomDigits(12),
419 // ACL permissions box
422 //jot nav tab (used in some themes)
423 '$message' => $this->l10n->t('Message'),
424 '$browser' => $this->l10n->t('Browser'),
426 '$compose_link_title' => $this->l10n->t('Open Compose page'),
427 '$always_open_compose' => $this->pConfig->get($this->session->getLocalUserId(), 'frio', 'always_open_compose', false),
431 if ($popup == true) {
432 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
435 $this->profiler->stopRecording();
440 * "Render" a conversation or list of items for HTML display.
441 * There are two major forms of display:
442 * - Sequential or unthreaded ("New Item View" or search results)
443 * - conversation view
444 * The $mode parameter decides between the various renderings and also
445 * figures out how to determine page owner and other contextual items
446 * that are based on unique features of the calling module.
447 * @param array $items An array of Posts
448 * @param string $mode One of self::MODE_*
449 * @param bool $update Asynchronous update rendering
450 * @param bool $preview Post preview (no actual database record)
451 * @param string $order Either "received" or "commented"
454 * @throws ImagickException
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 public function render(array $items, string $mode, bool $update = false, bool $preview = false, string $order = 'commented', int $uid = 0): string
459 $this->profiler->startRecording('rendering');
461 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
462 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
463 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
464 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
466 $live_update_div = '';
468 $userGservers = $this->userGServer->listIgnoredByUser($this->session->getLocalUserId());
470 $ignoredGsids = array_map(function (UserGServer $userGServer) {
471 return $userGServer->gsid;
472 }, $userGservers->getArrayCopy());
474 if ($mode === self::MODE_NETWORK) {
475 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
478 * The special div is needed for liveUpdate to kick in for this page.
479 * We only launch liveUpdate if you aren't filtering in some incompatible
480 * way and also you aren't writing a comment (discovered in javascript).
482 $live_update_div = '<div id="live-network"></div>' . "\r\n"
483 . "<script> var profile_uid = " . $_SESSION['uid']
484 . "; var netargs = '" . substr($this->args->getCommand(), 8)
486 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
487 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
488 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
489 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
490 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
491 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
492 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
493 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
494 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
495 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
496 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
498 . "'; </script>\r\n";
500 } elseif ($mode === self::MODE_PROFILE) {
501 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
504 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
506 if ($tab === 'posts') {
508 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
509 * because browser prefetching might change it on us. We have to deliver it with the page.
512 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
513 . "<script> var profile_uid = " . $uid
514 . "; var netargs = '?f='; </script>\r\n";
517 } elseif ($mode === self::MODE_NOTES) {
518 $items = $this->addChildren($items, false, $order, $this->session->getLocalUserId(), $mode);
521 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
522 . "<script> var profile_uid = " . $this->session->getLocalUserId()
523 . "; var netargs = '?f='; </script>\r\n";
525 } elseif ($mode === self::MODE_DISPLAY) {
526 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
529 $live_update_div = '<div id="live-display"></div>' . "\r\n"
530 . "<script> var profile_uid = " . ($this->session->getLocalUserId() ?: 0) . ";"
533 } elseif ($mode === self::MODE_COMMUNITY) {
534 $items = $this->addChildren($items, true, $order, $uid, $mode, $ignoredGsids);
537 $live_update_div = '<div id="live-community"></div>' . "\r\n"
538 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
540 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
541 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
542 . "'; </script>\r\n";
544 } elseif ($mode === self::MODE_CONTACTS) {
545 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
548 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
549 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
550 . "?f='; </script>\r\n";
552 } elseif ($mode === self::MODE_SEARCH) {
553 $live_update_div = '<div id="live-search"></div>' . "\r\n";
556 $page_dropping = $this->session->getLocalUserId() && $this->session->getLocalUserId() == $uid && $mode != self::MODE_SEARCH;
559 $_SESSION['return_path'] = $this->args->getQueryString();
562 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
563 Hook::callAll('conversation_start', $cb);
565 $items = $cb['items'];
567 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
569 $threads = $this->getThreadList($items, $mode, $preview, $page_dropping, $formSecurityToken);
571 if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
572 $page_template = Renderer::getMarkupTemplate('conversation.tpl');
574 $page_template = Renderer::getMarkupTemplate('threaded_conversation.tpl');
577 $o = Renderer::replaceMacros($page_template, [
578 '$baseurl' => $this->baseURL,
579 '$return_path' => $this->args->getQueryString(),
580 '$live_update' => $live_update_div,
581 '$remove' => $this->l10n->t('remove'),
583 '$update' => $update,
584 '$threads' => $threads,
585 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
588 $this->profiler->stopRecording();
593 * @param array $items
594 * @param string $mode One of self::MODE_*
595 * @param bool $preview
596 * @param bool $pagedrop Whether to enable the user to select the thread for deletion
597 * @param string $formSecurityToken A 'contact_action' form security token
599 * @throws InternalServerErrorException
600 * @throws \ImagickException
602 public function getThreadList(array $items, string $mode, bool $preview, bool $pagedrop, string $formSecurityToken): array
608 if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
609 $threads = $this->getContextLessThreadList($items, $mode, $preview, $pagedrop, $formSecurityToken);
620 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
621 unset($conv_responses['dislike']);
624 if (in_array($mode, [self::MODE_COMMUNITY, self::MODE_CONTACTS, self::MODE_PROFILE])) {
627 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
630 if (!$this->session->getLocalUserId()) {
635 $conv = new Thread($mode, $preview, $writable);
638 * get all the topmost parents
639 * this shouldn't be needed, as we should have only them in our array
640 * But for now, this array respects the old style, just in case
642 foreach ($items as $item) {
643 if (in_array($item['author-id'], $this->getBlocklist())) {
647 // Can we put this after the visibility check?
648 $this->builtinActivityPuller($item, $conv_responses);
650 // Only add what is visible
651 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
655 if (!$this->item->isVisibleActivity($item)) {
659 /// @todo Check if this call is needed or not
660 $arr = ['item' => $item];
661 Hook::callAll('display_item', $arr);
663 $item['pagedrop'] = $pagedrop;
665 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
666 $item_object = new PostObject($item);
667 $conv->addParent($item_object);
671 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
673 $this->logger->info('[ERROR] conversation : Failed to get template data.');
681 private function getBlocklist(): array
683 if (!$this->session->getLocalUserId()) {
687 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get($this->session->getLocalUserId(), 'system', 'blocked') ?? '');
688 if (empty($str_blocked)) {
694 foreach (explode(',', $str_blocked) as $entry) {
695 $cid = Contact::getIdForURL(trim($entry), 0, false);
705 * Adds some information (Causer, post reason, direction) to the fetched post row.
707 * @param array $row Post row
708 * @param array $activity Contact data of the resharer
709 * @param array $thr_parent Thread parent row
711 * @return array items with parents and comments
713 private function addRowInformation(array $row, array $activity, array $thr_parent): array
715 $this->profiler->startRecording('rendering');
717 if (!$row['writable']) {
718 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
721 if (!empty($activity)) {
722 if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
723 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
725 $row = array_merge($row, $activity);
726 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
728 $row['causer-link'] = $contact['url'];
729 $row['causer-avatar'] = $contact['thumb'];
730 $row['causer-name'] = $contact['name'];
731 } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
732 ($row['author-id'] == $activity['causer-id'])
738 switch ($row['post-reason']) {
739 case ItemModel::PR_TO:
740 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
742 case ItemModel::PR_CC:
743 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
745 case ItemModel::PR_BTO:
746 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
748 case ItemModel::PR_BCC:
749 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
751 case ItemModel::PR_AUDIENCE:
752 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'audience')];
754 case ItemModel::PR_FOLLOWER:
755 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
757 case ItemModel::PR_TAG:
758 $tags = Category::getArrayByURIId($row['uri-id'], $row['uid'], Category::SUBCRIPTION);
760 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to %s.', implode(', ', $tags))];
762 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
765 case ItemModel::PR_ANNOUNCEMENT:
766 if (!empty($row['causer-id']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'display_resharer')) {
767 $row['owner-id'] = $row['causer-id'];
768 $row['owner-link'] = $row['causer-link'];
769 $row['owner-avatar'] = $row['causer-avatar'];
770 $row['owner-name'] = $row['causer-name'];
773 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
776 'id' => $row['causer-id'],
777 'network' => $row['causer-network'],
778 'url' => $row['causer-link'],
779 'alias' => $row['causer-alias'],
782 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="' . htmlentities(Contact::magicLinkByContact($causer)) . '">' . htmlentities($row['causer-name']) . '</a>');
784 $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']))];
786 case ItemModel::PR_COMMENT:
787 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
789 case ItemModel::PR_STORED:
790 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
792 case ItemModel::PR_GLOBAL:
793 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
795 case ItemModel::PR_RELAY:
796 $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']))];
798 case ItemModel::PR_FETCHED:
799 $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']))];
801 case ItemModel::PR_COMPLETION:
802 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
804 case ItemModel::PR_DIRECT:
805 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
807 case ItemModel::PR_ACTIVITY:
808 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
810 case ItemModel::PR_DISTRIBUTE:
811 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
813 case ItemModel::PR_PUSHED:
814 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
818 $row['thr-parent-row'] = $thr_parent;
820 $this->profiler->stopRecording();
825 * Add comments to top level entries that had been fetched before
827 * The system will fetch the comments for the local user whenever possible.
828 * This behaviour is currently needed to allow commenting on Friendica posts.
830 * @param array $parents Parent items
831 * @param bool $block_authors
832 * @param string $order Either "received" or "commented"
834 * @param string $mode One of self::MODE_*
835 * @param array $ignoredGsids List of ids of servers ignored by the user
836 * @return array items with parents and comments
837 * @throws InternalServerErrorException
839 private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode, array $ignoredGsids = []): array
841 $this->profiler->startRecording('rendering');
842 if (count($parents) > 1) {
843 $max_comments = $this->config->get('system', 'max_comments', 100);
845 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
850 $commentcounter = [];
851 $activitycounter = [];
853 foreach ($parents as $parent) {
854 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
855 $uriid = $parent['thr-parent-id'];
856 if (!empty($parent['author-id'])) {
857 $activities[$uriid] = ['causer-id' => $parent['author-id']];
858 foreach (['commented', 'received', 'created'] as $orderfields) {
859 if (!empty($parent[$orderfields])) {
860 $activities[$uriid][$orderfields] = $parent[$orderfields];
865 $uriid = $parent['uri-id'];
869 $commentcounter[$uriid] = 0;
870 $activitycounter[$uriid] = 0;
873 $condition = ['parent-uri-id' => $uriids];
874 if ($block_authors) {
875 $condition['author-hidden'] = false;
878 if ($this->config->get('system', 'emoji_activities')) {
879 $emojis = $this->getEmojis($uriids);
880 $condition = DBA::mergeConditions($condition, ["(`gravity` != ? OR `origin`)", ItemModel::GRAVITY_ACTIVITY]);
883 $condition = DBA::mergeConditions(
885 ["`uid` IN (0, ?) AND (NOT `vid` IN (?, ?, ?) OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW), Verb::getID(Activity::VIEW), Verb::getID(Activity::READ)]
888 $condition = DBA::mergeConditions($condition, ["(`uid` != ? OR `private` != ?)", 0, ItemModel::PRIVATE]);
890 $condition = DBA::mergeConditions(
893 "`visible` AND NOT `deleted` AND NOT `author-blocked` AND NOT `owner-blocked`
894 AND ((NOT `contact-pending` AND (`contact-rel` IN (?, ?))) OR `self` OR `contact-uid` = ?)",
895 Contact::SHARING, Contact::FRIEND, 0
899 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
903 while ($row = Post::fetch($thread_parents)) {
904 $thr_parent[$row['uri-id']] = $row;
906 DBA::close($thread_parents);
908 $params = ['order' => ['uri-id' => true, 'uid' => true]];
910 $thread_items = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
916 while ($row = Post::fetch($thread_items)) {
917 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
921 if (in_array($row['author-gsid'], $ignoredGsids)
922 || in_array($row['owner-gsid'], $ignoredGsids)
923 || in_array($row['causer-gsid'], $ignoredGsids)
928 if (($mode != self::MODE_CONTACTS) && !$row['origin']) {
929 $row['featured'] = false;
932 if ($max_comments > 0) {
933 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
936 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
941 $authors[] = $row['author-id'];
942 $authors[] = $row['owner-id'];
944 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT])) {
945 $quote_uri_ids[$row['uri-id']] = [
946 'uri-id' => $row['uri-id'],
947 'uri' => $row['uri'],
948 'parent-uri-id' => $row['parent-uri-id'],
949 'parent-uri' => $row['parent-uri'],
953 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
956 DBA::close($thread_items);
958 $quotes = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), ['quote-uri-id' => array_column($quote_uri_ids, 'uri-id'), 'body' => '', 'uid' => 0]);
959 while ($quote = Post::fetch($quotes)) {
963 $row['verb'] = $row['body'] = $row['raw-body'] = Activity::ANNOUNCE;
964 $row['gravity'] = ItemModel::GRAVITY_ACTIVITY;
965 $row['object-type'] = Activity\ObjectType::NOTE;
966 $row['parent-uri'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri'];
967 $row['parent-uri-id'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri-id'];
968 $row['thr-parent'] = $quote_uri_ids[$quote['quote-uri-id']]['uri'];
969 $row['thr-parent-id'] = $quote_uri_ids[$quote['quote-uri-id']]['uri-id'];
971 $authors[] = $row['author-id'];
972 $authors[] = $row['owner-id'];
974 $items[$row['uri-id']] = $this->addRowInformation($row, [], []);
978 $authors = array_unique($authors);
983 if (!empty($authors)) {
984 $usercontacts = DBA::select('user-contact', ['cid', 'blocked', 'ignored', 'collapsed'], ['uid' => $uid, 'cid' => $authors]);
985 while ($usercontact = DBA::fetch($usercontacts)) {
986 if ($usercontact['blocked']) {
987 $blocks[] = $usercontact['cid'];
989 if ($usercontact['ignored']) {
990 $ignores[] = $usercontact['cid'];
992 if ($usercontact['collapsed']) {
993 $collapses[] = $usercontact['cid'];
996 DBA::close($usercontacts);
999 foreach ($items as $key => $row) {
1000 $items[$key]['emojis'] = $emojis[$key] ?? [];
1002 $always_display = in_array($mode, [self::MODE_CONTACTS, self::MODE_CONTACT_POSTS]);
1004 $items[$key]['user-blocked-author'] = !$always_display && in_array($row['author-id'], $blocks);
1005 $items[$key]['user-ignored-author'] = !$always_display && in_array($row['author-id'], $ignores);
1006 $items[$key]['user-blocked-owner'] = !$always_display && in_array($row['owner-id'], $blocks);
1007 $items[$key]['user-ignored-owner'] = !$always_display && in_array($row['owner-id'], $ignores);
1008 $items[$key]['user-collapsed-author'] = !$always_display && in_array($row['author-id'], $collapses);
1009 $items[$key]['user-collapsed-owner'] = !$always_display && in_array($row['owner-id'], $collapses);
1012 in_array($mode, [self::MODE_COMMUNITY, self::MODE_NETWORK]) &&
1013 (in_array($row['author-id'], $blocks) || in_array($row['owner-id'], $blocks) || in_array($row['author-id'], $ignores) || in_array($row['owner-id'], $ignores))
1015 unset($items[$key]);
1019 $items = $this->convSort($items, $order);
1021 $this->profiler->stopRecording();
1026 * Fetch emoji reaction from the conversation
1028 * @param array $uriids
1031 private function getEmojis(array $uriids): array
1034 Activity::LIKE => '👍',
1035 Activity::DISLIKE => '👎',
1036 Activity::ATTEND => '✔️',
1037 Activity::ATTENDMAYBE => '❓',
1038 Activity::ATTENDNO => '❌',
1039 Activity::ANNOUNCE => '♻',
1040 Activity::VIEW => '📺',
1043 $index_list = array_values($activity_emoji);
1044 $verbs = array_merge(array_keys($activity_emoji), [Activity::EMOJIREACT]);
1046 $condition = DBA::mergeConditions(['parent-uri-id' => $uriids, 'gravity' => ItemModel::GRAVITY_ACTIVITY, 'verb' => $verbs], ["NOT `deleted`"]);
1047 $separator = chr(255) . chr(255) . chr(255);
1049 $sql = "SELECT `thr-parent-id`, `body`, `verb`, COUNT(*) AS `total`, GROUP_CONCAT(REPLACE(`author-name`, '" . $separator . "', ' ') SEPARATOR '" . $separator . "' LIMIT 50) AS `title` FROM `post-view` WHERE " . array_shift($condition) . " GROUP BY `thr-parent-id`, `verb`, `body`";
1053 $rows = DBA::p($sql, $condition);
1054 while ($row = DBA::fetch($rows)) {
1055 $row['verb'] = $row['body'] ? Activity::EMOJIREACT : $row['verb'];
1056 $emoji = $row['body'] ?: $activity_emoji[$row['verb']];
1057 if (!isset($index_list[$emoji])) {
1058 $index_list[] = $emoji;
1060 $index = array_search($emoji, $index_list);
1062 $emojis[$row['thr-parent-id']][$index]['emoji'] = $emoji;
1063 $emojis[$row['thr-parent-id']][$index]['verb'] = $row['verb'];
1064 $emojis[$row['thr-parent-id']][$index]['total'] = ($emojis[$row['thr-parent-id']][$index]['total'] ?? 0) + $row['total'];
1065 $emojis[$row['thr-parent-id']][$index]['title'] = array_unique(array_merge($emojis[$row['thr-parent-id']][$index]['title'] ?? [], explode($separator, $row['title'])));
1073 * Plucks the children of the given parent from a given item list.
1075 * @param array $item_list
1076 * @param array $parent
1077 * @param bool $recursive
1080 private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1082 $this->profiler->startRecording('rendering');
1084 foreach ($item_list as $i => $item) {
1085 if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1087 // Fallback to parent-uri if thr-parent is not set
1088 $thr_parent = $item['thr-parent-id'];
1089 if ($thr_parent == '') {
1090 $thr_parent = $item['parent-uri-id'];
1093 if ($thr_parent == $parent['uri-id']) {
1094 $item['children'] = $this->getItemChildren($item_list, $item);
1096 $children[] = $item;
1097 unset($item_list[$i]);
1099 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1100 $children[] = $item;
1101 unset($item_list[$i]);
1105 $this->profiler->stopRecording();
1110 * Recursively sorts a tree-like item array
1112 * @param array $items
1115 private function sortItemChildren(array $items): array
1117 $this->profiler->startRecording('rendering');
1119 usort($result, [$this, 'sortThrReceivedRev']);
1120 foreach ($result as $k => $i) {
1121 if (isset($result[$k]['children'])) {
1122 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1125 $this->profiler->stopRecording();
1130 * Recursively add all children items at the top level of a list
1132 * @param array $children List of items to append
1133 * @param array $item_list
1135 private function addChildrenToList(array $children, array &$item_list)
1137 foreach ($children as $child) {
1138 $item_list[] = $child;
1139 if (isset($child['children'])) {
1140 $this->addChildrenToList($child['children'], $item_list);
1146 * Selectively flattens a tree-like item structure to prevent threading stairs
1148 * This recursive function takes the item tree structure created by conv_sort() and
1149 * flatten the extraneous depth levels when people reply sequentially, removing the
1150 * stairs effect in threaded conversations limiting the available content width.
1152 * The basic principle is the following: if a post item has only one reply and is
1153 * the last reply of its parent, then the reply is moved to the parent.
1155 * This process is rendered somewhat more complicated because items can be either
1156 * replies or likes, and these don't factor at all in the reply count/last reply.
1158 * @param array $parent A tree-like array of items
1161 private function smartFlattenConversation(array $parent): array
1163 $this->profiler->startRecording('rendering');
1164 if (!isset($parent['children']) || count($parent['children']) == 0) {
1165 $this->profiler->stopRecording();
1169 // We use a for loop to ensure we process the newly-moved items
1170 for ($i = 0; $i < count($parent['children']); $i++) {
1171 $child = $parent['children'][$i];
1173 if (isset($child['children']) && count($child['children'])) {
1174 // This helps counting only the regular posts
1175 $count_post_closure = function ($var) {
1176 $this->profiler->stopRecording();
1177 return $var['verb'] === Activity::POST;
1180 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1182 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1184 // If there's only one child's children post and this is the last child post
1185 if ($child_post_count == 1 && $remaining_post_count == 1) {
1187 // Searches the post item in the children
1189 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1193 $moved_item = $child['children'][$j];
1194 unset($parent['children'][$i]['children'][$j]);
1195 $parent['children'][] = $moved_item;
1197 $parent['children'][$i] = $this->smartFlattenConversation($child);
1202 $this->profiler->stopRecording();
1207 * Expands a flat list of items into corresponding tree-like conversation structures.
1209 * sort the top-level posts either on "received" or "commented", and finally
1210 * append all the items at the top level (???)
1212 * @param array $item_list A list of items belonging to one or more conversations
1213 * @param string $order Either on "received" or "commented"
1215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1217 private function convSort(array $item_list, string $order): array
1219 $this->profiler->startRecording('rendering');
1222 if (!(is_array($item_list) && count($item_list))) {
1223 $this->profiler->stopRecording();
1227 $blocklist = $this->getBlocklist();
1231 // Dedupes the item list on the uri to prevent infinite loops
1232 foreach ($item_list as $item) {
1233 if (in_array($item['author-id'], $blocklist)) {
1237 $item_array[$item['uri-id']] = $item;
1240 // Extract the top level items
1241 foreach ($item_array as $item) {
1242 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1247 if (stristr($order, 'pinned_received')) {
1248 usort($parents, [$this, 'sortThrFeaturedReceived']);
1249 } elseif (stristr($order, 'pinned_commented')) {
1250 usort($parents, [$this, 'sortThrFeaturedCommented']);
1251 } elseif (stristr($order, 'received')) {
1252 usort($parents, [$this, 'sortThrReceived']);
1253 } elseif (stristr($order, 'commented')) {
1254 usort($parents, [$this, 'sortThrCommented']);
1255 } elseif (stristr($order, 'created')) {
1256 usort($parents, [$this, 'sortThrCreated']);
1260 * Plucks children from the item_array, second pass collects eventual orphan
1261 * items and add them as children of their top-level post.
1263 foreach ($parents as $i => $parent) {
1264 $parents[$i]['children'] = array_merge(
1265 $this->getItemChildren($item_array, $parent, true),
1266 $this->getItemChildren($item_array, $parent, false)
1270 foreach ($parents as $i => $parent) {
1271 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1274 if (!$this->pConfig->get($this->session->getLocalUserId(), 'system', 'no_smart_threading', 0)) {
1275 foreach ($parents as $i => $parent) {
1276 $parents[$i] = $this->smartFlattenConversation($parent);
1280 /// @TODO: Stop recursively adding all children back to the top level (!!!)
1281 /// However, this apparently ensures responses (likes, attendance) display (?!)
1282 foreach ($parents as $parent) {
1283 if (count($parent['children'])) {
1284 $this->addChildrenToList($parent['children'], $parents);
1288 $this->profiler->stopRecording();
1293 * usort() callback to sort item arrays by featured and the received key
1299 private function sortThrFeaturedReceived(array $a, array $b): int
1301 if ($b['featured'] && !$a['featured']) {
1303 } elseif (!$b['featured'] && $a['featured']) {
1307 return strcmp($b['received'], $a['received']);
1311 * usort() callback to sort item arrays by featured and the received key
1317 private function sortThrFeaturedCommented(array $a, array $b): int
1319 if ($b['featured'] && !$a['featured']) {
1321 } elseif (!$b['featured'] && $a['featured']) {
1325 return strcmp($b['commented'], $a['commented']);
1329 * usort() callback to sort item arrays by the received key
1335 private function sortThrReceived(array $a, array $b): int
1337 return strcmp($b['received'], $a['received']);
1341 * usort() callback to reverse sort item arrays by the received key
1347 private function sortThrReceivedRev(array $a, array $b): int
1349 return strcmp($a['received'], $b['received']);
1353 * usort() callback to sort item arrays by the commented key
1359 private function sortThrCommented(array $a, array $b): int
1361 return strcmp($b['commented'], $a['commented']);
1365 * usort() callback to sort item arrays by the created key
1371 private function sortThrCreated(array $a, array $b): int
1373 return strcmp($b['created'], $a['created']);
1377 * "New Item View" on network page or search page results
1378 * - just loop through the items and format them minimally for display
1380 * @param array $items
1381 * @param string $mode One of self::MODE_*
1382 * @param bool $preview Whether the display is a preview
1383 * @param bool $pagedrop Whether the user can select the threads for deletion
1384 * @param string $formSecurityToken A 'contact_action' form security token
1386 * @throws InternalServerErrorException
1387 * @throws \ImagickException
1389 public function getContextLessThreadList(array $items, string $mode, bool $preview, bool $pagedrop, string $formSecurityToken): array
1394 foreach ($items as $item) {
1395 if (in_array($item['uri-id'], $uriids)) {
1399 $uriids[] = $item['uri-id'];
1401 if (!$this->item->isVisibleActivity($item)) {
1405 if (in_array($item['author-id'], $this->getBlocklist())) {
1409 // prevent private email from leaking.
1410 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
1414 $profile_name = $item['author-name'];
1415 if (!empty($item['author-link']) && empty($item['author-name'])) {
1416 $profile_name = $item['author-link'];
1419 $tags = Tag::populateFromItem($item);
1423 'id' => $item['author-id'],
1424 'network' => $item['author-network'],
1425 'url' => $item['author-link'],
1426 'alias' => $item['author-alias'],
1428 $profile_link = Contact::magicLinkByContact($author);
1431 if (strpos($profile_link, 'contact/redir/') === 0) {
1432 $sparkle = ' sparkle';
1435 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
1436 Hook::callAll('render_location', $locate);
1437 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
1439 $this->item->localize($item);
1440 if ($mode === self::MODE_FILED) {
1447 'dropping' => $dropping,
1448 'pagedrop' => $pagedrop,
1449 'select' => $this->l10n->t('Select'),
1450 'delete' => $this->l10n->t('Delete'),
1460 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
1461 unset($likebuttons['dislike']);
1464 $body_html = ItemModel::prepareBody($item, true, $preview);
1466 [$categories, $folders] = $this->item->determineCategoriesTerms($item, $this->session->getLocalUserId());
1468 if (!empty($item['title'])) {
1469 $title = $item['title'];
1470 } elseif (!empty($item['content-warning']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'disable_cw', false)) {
1471 $title = ucfirst($item['content-warning']);
1476 if (!empty($item['featured'])) {
1477 $pinned = $this->l10n->t('Pinned item');
1483 'template' => 'search_item.tpl',
1484 'id' => ($preview ? 'P0' : $item['id']),
1485 'guid' => ($preview ? 'Q0' : $item['guid']),
1486 'commented' => $item['commented'],
1487 'received' => $item['received'],
1488 'created_date' => $item['created'],
1489 'uriid' => $item['uri-id'],
1490 'author_gsid' => $item['author-gsid'],
1491 'network' => $item['network'],
1492 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
1493 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
1494 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
1495 'profile_url' => $profile_link,
1496 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
1497 'name' => $profile_name,
1498 'sparkle' => $sparkle,
1500 'thumb' => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
1502 'body_html' => $body_html,
1503 'tags' => $tags['tags'],
1504 'hashtags' => $tags['hashtags'],
1505 'mentions' => $tags['mentions'],
1506 'implicit_mentions' => $tags['implicit_mentions'],
1507 'txt_cats' => $this->l10n->t('Categories:'),
1508 'txt_folders' => $this->l10n->t('Filed under:'),
1509 'has_cats' => ((count($categories)) ? 'true' : ''),
1510 'has_folders' => ((count($folders)) ? 'true' : ''),
1511 'categories' => $categories,
1512 'folders' => $folders,
1513 'text' => strip_tags($body_html),
1514 'localtime' => DateTimeFormat::local($item['created'], 'r'),
1515 'utc' => DateTimeFormat::utc($item['created'], 'c'),
1516 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
1517 'location_html' => $location_html,
1521 'owner_photo' => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
1522 'plink' => ItemModel::getPlink($item),
1524 'pinned' => $pinned,
1525 'isstarred' => 'unstarred',
1528 'vote' => $likebuttons,
1530 'dislike_html ' => '',
1531 'comment_html' => '',
1532 'conv' => $preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')],
1533 'previewing' => $preview ? ' preview ' : '',
1534 'wait' => $this->l10n->t('Please wait'),
1535 'thread_level' => 1,
1538 $arr = ['item' => $item, 'output' => $tmp_item];
1539 Hook::callAll('display_item', $arr);
1542 'id' => $item['id'],
1543 'network' => $item['network'],
1544 'items' => [$arr['output']],