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_CHANNEL = 'channel';
61 const MODE_COMMUNITY = 'community';
62 const MODE_CONTACTS = 'contacts';
63 const MODE_CONTACT_POSTS = 'contact-posts';
64 const MODE_DISPLAY = 'display';
65 const MODE_FILED = 'filed';
66 const MODE_NETWORK = 'network';
67 const MODE_NOTES = 'notes';
68 const MODE_SEARCH = 'search';
69 const MODE_PROFILE = 'profile';
77 /** @var LoggerInterface */
81 /** @var App\Arguments */
83 /** @var IManagePersonalConfigValues */
87 /** @var IManageConfigValues */
95 /** @var IHandleUserSessions */
97 /** @var Repository\UserGServer */
100 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)
102 $this->activity = $activity;
104 $this->config = $config;
106 $this->baseURL = $baseURL;
107 $this->profiler = $profiler;
108 $this->logger = $logger;
111 $this->pConfig = $pConfig;
114 $this->session = $session;
115 $this->userGServer = $userGServer;
119 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
121 * Increments the count of each matching activity and adds a link to the author as needed.
123 * @param array $activity
124 * @param array &$conv_responses (already created with builtin activity structure)
126 * @throws ImagickException
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 public function builtinActivityPuller(array $activity, array &$conv_responses)
131 $thread_parent = $activity['thr-parent-row'] ?? [];
133 foreach ($conv_responses as $mode => $v) {
138 $verb = Activity::LIKE;
141 $verb = Activity::DISLIKE;
144 $verb = Activity::ATTEND;
147 $verb = Activity::ATTENDNO;
150 $verb = Activity::ATTENDMAYBE;
153 $verb = Activity::ANNOUNCE;
159 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
162 'id' => $activity['author-id'],
163 'network' => $activity['author-network'],
164 'url' => $activity['author-link'],
165 'alias' => $activity['author-alias'],
167 $url = Contact::magicLinkByContact($author);
168 if (strpos($url, 'contact/redir/') === 0) {
169 $sparkle = ' class="sparkle" ';
172 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
174 if (empty($activity['thr-parent-id'])) {
175 $activity['thr-parent-id'] = $activity['parent-uri-id'];
178 // Skip when the causer of the parent is the same as the author of the announce
179 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
183 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
184 $conv_responses[$mode][$activity['thr-parent-id']] = [
188 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
189 // only list each unique author once
193 if ($this->session->getPublicContactId() == $activity['author-id']) {
194 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
197 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
199 // there can only be one activity verb per item so if we found anything, we can stop looking
206 * Returns the liker phrase based on a list of likers
208 * @param string $verb the activity verb
209 * @param array $likers a list of likers
211 * @return string the liker phrase
213 * @throws InternalServerErrorException in case either the verb is invalid or the list of likers is empty
215 private function getLikerPhrase(string $verb, array $likers): string
217 $total = count($likers);
220 throw new InternalServerErrorException(sprintf('There has to be at least one Liker for verb "%s"', $verb));
221 } else if ($total === 1) {
222 $likerString = $likers[0];
224 if ($total < $this->config->get('system', 'max_likers')) {
225 $likerString = implode(', ', array_slice($likers, 0, -1));
226 $likerString .= ' ' . $this->l10n->t('and') . ' ' . $likers[count($likers) - 1];
228 $likerString = implode(', ', array_slice($likers, 0, $this->config->get('system', 'max_likers') - 1));
229 $likerString .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
235 return $this->l10n->tt('%2$s likes this.', '%2$s like this.', $total, $likerString);
237 return $this->l10n->tt('%2$s doesn\'t like this.', '%2$s don\'t like this.', $total, $likerString);
239 return $this->l10n->tt('%2$s attends.', '%2$s attend.', $total, $likerString);
241 return $this->l10n->tt('%2$s doesn\'t attend.', '%2$s don\'t attend.', $total, $likerString);
243 return $this->l10n->tt('%2$s attends maybe.', '%2$s attend maybe.', $total, $likerString);
245 return $this->l10n->tt('%2$s reshared this.', '%2$s reshared this.', $total, $likerString);
247 throw new InternalServerErrorException(sprintf('Unknown verb "%s"', $verb));
252 * Format the activity text for an item/photo/video
254 * @param array $links array of pre-linked names of actors
255 * @param string $verb one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
256 * @param int $id item id
257 * @param string $activity Activity URI
258 * @param array $emojis Array with emoji reactions
259 * @return string formatted text
260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
262 public function formatActivity(array $links, string $verb, int $id, string $activity, array $emojis): string
264 $this->profiler->startRecording('rendering');
267 $phrase = $this->getLikerPhrase($verb, $links);
268 $total = max(count($links), $emojis[$activity]['total'] ?? 0);
271 $spanatts = "class=\"btn btn-link fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
272 $explikers = $phrase;
276 $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);
279 $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);
282 $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);
285 $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);
288 $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);
291 $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);
295 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
298 $output = Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
299 '$phrase' => $phrase,
303 $output .= $expanded;
305 $this->profiler->stopRecording();
309 public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
311 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
312 if (empty($user['uid'])) {
316 $this->profiler->startRecording('rendering');
319 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
320 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
321 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
322 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
323 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
324 $x['bang'] = $x['bang'] ?? '';
325 $x['visitor'] = $x['visitor'] ?? 'block';
326 $x['is_owner'] = $x['is_owner'] ?? true;
327 $x['profile_uid'] = $x['profile_uid'] ?? $this->session->getLocalUserId();
330 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
332 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
333 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
334 '$newpost' => 'true',
335 '$baseurl' => $this->baseURL,
336 '$geotag' => $geotag,
337 '$nickname' => $x['nickname'],
338 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
339 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
340 '$term' => $this->l10n->t('Tag term:'),
341 '$fileas' => $this->l10n->t('Save to Folder:'),
342 '$whereareu' => $this->l10n->t('Where are you right now?'),
343 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
344 '$is_mobile' => $this->mode->isMobile(),
348 Hook::callAll('jot_tool', $jotplugins);
350 if ($this->config->get('system', 'set_creation_date')) {
351 $created_at = Temporal::getDateTimeField(
352 new \DateTime(DBA::NULL_DATETIME),
353 new \DateTime('now'),
355 $this->l10n->t('Created at'),
362 $tpl = Renderer::getMarkupTemplate('jot.tpl');
364 $o .= Renderer::replaceMacros($tpl, [
365 '$new_post' => $this->l10n->t('New Post'),
366 '$return_path' => $this->args->getQueryString(),
368 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
369 '$loading' => $this->l10n->t('Loading...'),
370 '$upload' => $this->l10n->t('Upload photo'),
371 '$shortupload' => $this->l10n->t('upload photo'),
372 '$attach' => $this->l10n->t('Attach file'),
373 '$shortattach' => $this->l10n->t('attach file'),
374 '$edbold' => $this->l10n->t('Bold'),
375 '$editalic' => $this->l10n->t('Italic'),
376 '$eduline' => $this->l10n->t('Underline'),
377 '$edquote' => $this->l10n->t('Quote'),
378 '$edemojis' => $this->l10n->t('Add emojis'),
379 '$contentwarn' => $this->l10n->t('Content Warning'),
380 '$edcode' => $this->l10n->t('Code'),
381 '$edimg' => $this->l10n->t('Image'),
382 '$edurl' => $this->l10n->t('Link'),
383 '$edattach' => $this->l10n->t('Link or Media'),
384 '$edvideo' => $this->l10n->t('Video'),
385 '$setloc' => $this->l10n->t('Set your location'),
386 '$shortsetloc' => $this->l10n->t('set location'),
387 '$noloc' => $this->l10n->t('Clear browser location'),
388 '$shortnoloc' => $this->l10n->t('clear location'),
389 '$title' => $x['title'] ?? '',
390 '$placeholdertitle' => $this->l10n->t('Set title'),
391 '$category' => $x['category'] ?? '',
392 '$placeholdercategory' => Feature::isEnabled($this->session->getLocalUserId(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
393 '$scheduled_at' => Temporal::getDateTimeField(
395 new \DateTime('now + 6 months'),
397 $this->l10n->t('Scheduled at'),
400 '$created_at' => $created_at,
401 '$wait' => $this->l10n->t('Please wait'),
402 '$permset' => $this->l10n->t('Permission settings'),
403 '$shortpermset' => $this->l10n->t('Permissions'),
404 '$wall' => $notes_cid ? 0 : 1,
405 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
406 '$content' => $x['content'] ?? '',
407 '$post_id' => $x['post_id'] ?? '',
408 '$baseurl' => $this->baseURL,
409 '$defloc' => $x['default_location'],
410 '$visitor' => $x['visitor'],
411 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
412 '$public' => $this->l10n->t('Public post'),
413 '$lockstate' => $x['lockstate'],
414 '$bang' => $x['bang'],
415 '$profile_uid' => $x['profile_uid'],
416 '$preview' => $this->l10n->t('Preview'),
417 '$jotplugins' => $jotplugins,
418 '$notes_cid' => $notes_cid,
419 '$cancel' => $this->l10n->t('Cancel'),
420 '$rand_num' => Crypto::randomDigits(12),
422 // ACL permissions box
425 //jot nav tab (used in some themes)
426 '$message' => $this->l10n->t('Message'),
427 '$browser' => $this->l10n->t('Browser'),
429 '$compose_link_title' => $this->l10n->t('Open Compose page'),
430 '$always_open_compose' => $this->pConfig->get($this->session->getLocalUserId(), 'frio', 'always_open_compose', false),
434 if ($popup == true) {
435 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
438 $this->profiler->stopRecording();
443 * "Render" a conversation or list of items for HTML display.
444 * There are two major forms of display:
445 * - Sequential or unthreaded ("New Item View" or search results)
446 * - conversation view
447 * The $mode parameter decides between the various renderings and also
448 * figures out how to determine page owner and other contextual items
449 * that are based on unique features of the calling module.
450 * @param array $items An array of Posts
451 * @param string $mode One of self::MODE_*
452 * @param bool $update Asynchronous update rendering
453 * @param bool $preview Post preview (no actual database record)
454 * @param string $order Either "received" or "commented"
457 * @throws ImagickException
458 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
460 public function render(array $items, string $mode, bool $update = false, bool $preview = false, string $order = 'commented', int $uid = 0): string
462 $this->profiler->startRecording('rendering');
464 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
465 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
466 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
467 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
469 $live_update_div = '';
471 $userGservers = $this->userGServer->listIgnoredByUser($this->session->getLocalUserId());
473 $ignoredGsids = array_map(function (UserGServer $userGServer) {
474 return $userGServer->gsid;
475 }, $userGservers->getArrayCopy());
477 if ($mode === self::MODE_NETWORK) {
478 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
481 * The special div is needed for liveUpdate to kick in for this page.
482 * We only launch liveUpdate if you aren't filtering in some incompatible
483 * way and also you aren't writing a comment (discovered in javascript).
485 $live_update_div = '<div id="live-network"></div>' . "\r\n"
486 . "<script> var profile_uid = " . $_SESSION['uid']
487 . "; var netargs = '" . substr($this->args->getCommand(), 8)
489 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
490 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
491 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
492 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
493 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
494 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
495 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
496 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
497 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
498 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
499 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
500 . (!empty($_GET['channel']) ? '&channel=' . rawurlencode($_GET['channel']) : '')
501 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
502 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
503 . "'; </script>\r\n";
505 } elseif ($mode === self::MODE_PROFILE) {
506 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
509 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
511 if ($tab === 'posts') {
513 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
514 * because browser prefetching might change it on us. We have to deliver it with the page.
517 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
518 . "<script> var profile_uid = " . $uid
519 . "; var netargs = '?f='; </script>\r\n";
522 } elseif ($mode === self::MODE_NOTES) {
523 $items = $this->addChildren($items, false, $order, $this->session->getLocalUserId(), $mode);
526 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
527 . "<script> var profile_uid = " . $this->session->getLocalUserId()
528 . "; var netargs = '?f='; </script>\r\n";
530 } elseif ($mode === self::MODE_DISPLAY) {
531 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
534 $live_update_div = '<div id="live-display"></div>' . "\r\n"
535 . "<script> var profile_uid = " . ($this->session->getLocalUserId() ?: 0) . ";"
538 } elseif ($mode === self::MODE_CHANNEL) {
539 $items = $this->addChildren($items, true, $order, $uid, $mode, $ignoredGsids);
542 $live_update_div = '<div id="live-channel"></div>' . "\r\n"
543 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
545 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
546 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
547 . "'; </script>\r\n";
549 } elseif ($mode === self::MODE_COMMUNITY) {
550 $items = $this->addChildren($items, true, $order, $uid, $mode, $ignoredGsids);
553 $live_update_div = '<div id="live-community"></div>' . "\r\n"
554 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
556 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
557 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
558 . "'; </script>\r\n";
560 } elseif ($mode === self::MODE_CONTACTS) {
561 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
564 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
565 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
566 . "?f='; </script>\r\n";
568 } elseif ($mode === self::MODE_SEARCH) {
569 $live_update_div = '<div id="live-search"></div>' . "\r\n";
572 $page_dropping = $this->session->getLocalUserId() && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'show_page_drop', true) && ($this->session->getLocalUserId() == $uid && $mode != self::MODE_SEARCH);
575 $_SESSION['return_path'] = $this->args->getQueryString();
578 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
579 Hook::callAll('conversation_start', $cb);
581 $items = $cb['items'];
583 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
585 $threads = $this->getThreadList($items, $mode, $preview, $page_dropping, $formSecurityToken);
587 if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
588 $page_template = Renderer::getMarkupTemplate('conversation.tpl');
590 $page_template = Renderer::getMarkupTemplate('threaded_conversation.tpl');
593 $o = Renderer::replaceMacros($page_template, [
594 '$baseurl' => $this->baseURL,
595 '$return_path' => $this->args->getQueryString(),
596 '$live_update' => $live_update_div,
597 '$remove' => $this->l10n->t('remove'),
599 '$update' => $update,
600 '$threads' => $threads,
601 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
604 $this->profiler->stopRecording();
609 * @param array $items
610 * @param string $mode One of self::MODE_*
611 * @param bool $preview
612 * @param bool $pagedrop Whether to enable the user to select the thread for deletion
613 * @param string $formSecurityToken A 'contact_action' form security token
615 * @throws InternalServerErrorException
616 * @throws \ImagickException
618 public function getThreadList(array $items, string $mode, bool $preview, bool $pagedrop, string $formSecurityToken): array
624 if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
625 $threads = $this->getContextLessThreadList($items, $mode, $preview, $pagedrop, $formSecurityToken);
636 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
637 unset($conv_responses['dislike']);
640 if (in_array($mode, [self::MODE_CHANNEL, self::MODE_COMMUNITY, self::MODE_CONTACTS, self::MODE_PROFILE])) {
643 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
646 if (!$this->session->getLocalUserId()) {
651 $conv = new Thread($mode, $preview, $writable);
654 * get all the topmost parents
655 * this shouldn't be needed, as we should have only them in our array
656 * But for now, this array respects the old style, just in case
658 foreach ($items as $item) {
659 if (in_array($item['author-id'], $this->getBlocklist())) {
663 // Can we put this after the visibility check?
664 $this->builtinActivityPuller($item, $conv_responses);
666 // Only add what is visible
667 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
671 if (!$this->item->isVisibleActivity($item)) {
675 /// @todo Check if this call is needed or not
676 $arr = ['item' => $item];
677 Hook::callAll('display_item', $arr);
679 $item['pagedrop'] = $pagedrop;
681 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
682 $item_object = new PostObject($item);
683 $conv->addParent($item_object);
687 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
689 $this->logger->info('[ERROR] conversation : Failed to get template data.');
697 private function getBlocklist(): array
699 if (!$this->session->getLocalUserId()) {
703 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get($this->session->getLocalUserId(), 'system', 'blocked') ?? '');
704 if (empty($str_blocked)) {
710 foreach (explode(',', $str_blocked) as $entry) {
711 $cid = Contact::getIdForURL(trim($entry), 0, false);
721 * Adds some information (Causer, post reason, direction) to the fetched post row.
723 * @param array $row Post row
724 * @param array $activity Contact data of the resharer
725 * @param array $thr_parent Thread parent row
727 * @return array items with parents and comments
729 private function addRowInformation(array $row, array $activity, array $thr_parent): array
731 $this->profiler->startRecording('rendering');
733 if (!$row['writable']) {
734 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
737 if (!empty($activity)) {
738 if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
739 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
741 $row = array_merge($row, $activity);
742 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
744 $row['causer-link'] = $contact['url'];
745 $row['causer-avatar'] = $contact['thumb'];
746 $row['causer-name'] = $contact['name'];
747 } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
748 ($row['author-id'] == $activity['causer-id'])
754 switch ($row['post-reason']) {
755 case ItemModel::PR_TO:
756 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
758 case ItemModel::PR_CC:
759 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
761 case ItemModel::PR_BTO:
762 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
764 case ItemModel::PR_BCC:
765 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
767 case ItemModel::PR_AUDIENCE:
768 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'audience')];
770 case ItemModel::PR_FOLLOWER:
771 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
773 case ItemModel::PR_TAG:
774 $tags = Category::getArrayByURIId($row['uri-id'], $row['uid'], Category::SUBCRIPTION);
776 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to %s.', implode(', ', $tags))];
778 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
781 case ItemModel::PR_ANNOUNCEMENT:
782 if (!empty($row['causer-id']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'display_resharer')) {
783 $row['owner-id'] = $row['causer-id'];
784 $row['owner-link'] = $row['causer-link'];
785 $row['owner-avatar'] = $row['causer-avatar'];
786 $row['owner-name'] = $row['causer-name'];
789 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
792 'id' => $row['causer-id'],
793 'network' => $row['causer-network'],
794 'url' => $row['causer-link'],
795 'alias' => $row['causer-alias'],
798 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="' . htmlentities(Contact::magicLinkByContact($causer)) . '">' . htmlentities($row['causer-name']) . '</a>');
800 $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']))];
802 case ItemModel::PR_COMMENT:
803 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
805 case ItemModel::PR_STORED:
806 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
808 case ItemModel::PR_GLOBAL:
809 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
811 case ItemModel::PR_RELAY:
812 $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']))];
814 case ItemModel::PR_FETCHED:
815 $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']))];
817 case ItemModel::PR_COMPLETION:
818 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
820 case ItemModel::PR_DIRECT:
821 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
823 case ItemModel::PR_ACTIVITY:
824 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
826 case ItemModel::PR_DISTRIBUTE:
827 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
829 case ItemModel::PR_PUSHED:
830 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
834 $row['thr-parent-row'] = $thr_parent;
836 $this->profiler->stopRecording();
841 * Add comments to top level entries that had been fetched before
843 * The system will fetch the comments for the local user whenever possible.
844 * This behaviour is currently needed to allow commenting on Friendica posts.
846 * @param array $parents Parent items
847 * @param bool $block_authors
848 * @param string $order Either "received" or "commented"
850 * @param string $mode One of self::MODE_*
851 * @param array $ignoredGsids List of ids of servers ignored by the user
852 * @return array items with parents and comments
853 * @throws InternalServerErrorException
855 private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode, array $ignoredGsids = []): array
857 $this->profiler->startRecording('rendering');
858 if (count($parents) > 1) {
859 $max_comments = $this->config->get('system', 'max_comments', 100);
861 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
866 $commentcounter = [];
867 $activitycounter = [];
869 foreach ($parents as $parent) {
870 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
871 $uriid = $parent['thr-parent-id'];
872 if (!empty($parent['author-id'])) {
873 $activities[$uriid] = ['causer-id' => $parent['author-id']];
874 foreach (['commented', 'received', 'created'] as $orderfields) {
875 if (!empty($parent[$orderfields])) {
876 $activities[$uriid][$orderfields] = $parent[$orderfields];
881 $uriid = $parent['uri-id'];
885 $commentcounter[$uriid] = 0;
886 $activitycounter[$uriid] = 0;
889 $condition = ['parent-uri-id' => $uriids];
890 if ($block_authors) {
891 $condition['author-hidden'] = false;
894 $emojis = $this->getEmojis($uriids);
895 $quoteshares = $this->getQuoteShares($uriids);
897 if (!$this->config->get('system', 'legacy_activities')) {
898 $condition = DBA::mergeConditions($condition, ["(`gravity` != ? OR `origin`)", ItemModel::GRAVITY_ACTIVITY]);
901 $condition = DBA::mergeConditions(
903 ["`uid` IN (0, ?) AND (NOT `vid` IN (?, ?, ?) OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW), Verb::getID(Activity::VIEW), Verb::getID(Activity::READ)]
906 $condition = DBA::mergeConditions($condition, ["(`uid` != ? OR `private` != ?)", 0, ItemModel::PRIVATE]);
908 $condition = DBA::mergeConditions(
911 "`visible` AND NOT `deleted` AND NOT `author-blocked` AND NOT `owner-blocked`
912 AND ((NOT `contact-pending` AND (`contact-rel` IN (?, ?))) OR `self` OR `contact-uid` = ?)",
913 Contact::SHARING, Contact::FRIEND, 0
917 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
921 while ($row = Post::fetch($thread_parents)) {
922 $thr_parent[$row['uri-id']] = $row;
924 DBA::close($thread_parents);
926 $params = ['order' => ['uri-id' => true, 'uid' => true]];
928 $thread_items = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
934 while ($row = Post::fetch($thread_items)) {
935 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
940 in_array($row['author-gsid'], $ignoredGsids)
941 || in_array($row['owner-gsid'], $ignoredGsids)
942 || in_array($row['causer-gsid'], $ignoredGsids)
947 if (($mode != self::MODE_CONTACTS) && !$row['origin']) {
948 $row['featured'] = false;
951 if ($max_comments > 0) {
952 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
955 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
960 $authors[] = $row['author-id'];
961 $authors[] = $row['owner-id'];
963 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT])) {
964 $quote_uri_ids[$row['uri-id']] = [
965 'uri-id' => $row['uri-id'],
966 'uri' => $row['uri'],
967 'parent-uri-id' => $row['parent-uri-id'],
968 'parent-uri' => $row['parent-uri'],
972 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
975 DBA::close($thread_items);
977 $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]);
978 while ($quote = Post::fetch($quotes)) {
982 $row['verb'] = $row['body'] = $row['raw-body'] = Activity::ANNOUNCE;
983 $row['gravity'] = ItemModel::GRAVITY_ACTIVITY;
984 $row['object-type'] = Activity\ObjectType::NOTE;
985 $row['parent-uri'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri'];
986 $row['parent-uri-id'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri-id'];
987 $row['thr-parent'] = $quote_uri_ids[$quote['quote-uri-id']]['uri'];
988 $row['thr-parent-id'] = $quote_uri_ids[$quote['quote-uri-id']]['uri-id'];
990 $authors[] = $row['author-id'];
991 $authors[] = $row['owner-id'];
993 $items[$row['uri-id']] = $this->addRowInformation($row, [], []);
997 $authors = array_unique($authors);
1002 if (!empty($authors)) {
1003 $usercontacts = DBA::select('user-contact', ['cid', 'blocked', 'ignored', 'collapsed'], ['uid' => $uid, 'cid' => $authors]);
1004 while ($usercontact = DBA::fetch($usercontacts)) {
1005 if ($usercontact['blocked']) {
1006 $blocks[] = $usercontact['cid'];
1008 if ($usercontact['ignored']) {
1009 $ignores[] = $usercontact['cid'];
1011 if ($usercontact['collapsed']) {
1012 $collapses[] = $usercontact['cid'];
1015 DBA::close($usercontacts);
1018 foreach ($items as $key => $row) {
1019 $items[$key]['emojis'] = $emojis[$key] ?? [];
1020 $items[$key]['quoteshares'] = $quoteshares[$key] ?? [];
1022 $always_display = in_array($mode, [self::MODE_CONTACTS, self::MODE_CONTACT_POSTS]);
1024 $items[$key]['user-blocked-author'] = !$always_display && in_array($row['author-id'], $blocks);
1025 $items[$key]['user-ignored-author'] = !$always_display && in_array($row['author-id'], $ignores);
1026 $items[$key]['user-blocked-owner'] = !$always_display && in_array($row['owner-id'], $blocks);
1027 $items[$key]['user-ignored-owner'] = !$always_display && in_array($row['owner-id'], $ignores);
1028 $items[$key]['user-collapsed-author'] = !$always_display && in_array($row['author-id'], $collapses);
1029 $items[$key]['user-collapsed-owner'] = !$always_display && in_array($row['owner-id'], $collapses);
1032 in_array($mode, [self::MODE_CHANNEL, self::MODE_COMMUNITY, self::MODE_NETWORK]) &&
1033 (in_array($row['author-id'], $blocks) || in_array($row['owner-id'], $blocks) || in_array($row['author-id'], $ignores) || in_array($row['owner-id'], $ignores))
1035 unset($items[$key]);
1039 $items = $this->convSort($items, $order);
1041 $this->profiler->stopRecording();
1046 * Fetch emoji reaction from the conversation
1048 * @param array $uriids
1051 private function getEmojis(array $uriids): array
1054 Activity::LIKE => '👍',
1055 Activity::DISLIKE => '👎',
1056 Activity::ATTEND => '✔️',
1057 Activity::ATTENDMAYBE => '❓',
1058 Activity::ATTENDNO => '❌',
1059 Activity::ANNOUNCE => '♻',
1060 Activity::VIEW => '📺',
1063 $index_list = array_values($activity_emoji);
1064 $verbs = array_merge(array_keys($activity_emoji), [Activity::EMOJIREACT, Activity::POST]);
1066 $condition = DBA::mergeConditions(['parent-uri-id' => $uriids, 'gravity' => [ItemModel::GRAVITY_ACTIVITY, ItemModel::GRAVITY_COMMENT], 'verb' => $verbs], ["NOT `deleted`"]);
1067 $separator = chr(255) . chr(255) . chr(255);
1069 $sql = "SELECT `thr-parent-id`, `body`, `verb`, `gravity`, 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`, `gravity`";
1073 $rows = DBA::p($sql, $condition);
1074 while ($row = DBA::fetch($rows)) {
1075 if ($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) {
1076 $row['verb'] = $row['body'] ? Activity::EMOJIREACT : $row['verb'];
1077 $emoji = $row['body'] ?: $activity_emoji[$row['verb']];
1082 if (!isset($index_list[$emoji])) {
1083 $index_list[] = $emoji;
1085 $index = array_search($emoji, $index_list);
1087 $emojis[$row['thr-parent-id']][$index]['emoji'] = $emoji;
1088 $emojis[$row['thr-parent-id']][$index]['verb'] = $row['verb'];
1089 $emojis[$row['thr-parent-id']][$index]['total'] = ($emojis[$row['thr-parent-id']][$index]['total'] ?? 0) + $row['total'];
1090 $emojis[$row['thr-parent-id']][$index]['title'] = array_unique(array_merge($emojis[$row['thr-parent-id']][$index]['title'] ?? [], explode($separator, $row['title'])));
1098 * Fetch quote shares from the conversation
1100 * @param array $uriids
1103 private function getQuoteShares(array $uriids): array
1105 $condition = DBA::mergeConditions(['quote-uri-id' => $uriids], ["NOT `quote-uri-id` IS NULL"]);
1106 $separator = chr(255) . chr(255) . chr(255);
1108 $sql = "SELECT `quote-uri-id`, COUNT(*) AS `total`, GROUP_CONCAT(REPLACE(`name`, '" . $separator . "', ' ') SEPARATOR '" . $separator . "' LIMIT 50) AS `title` FROM `post-content` INNER JOIN `post` ON `post`.`uri-id` = `post-content`.`uri-id` INNER JOIN `contact` ON `post`.`author-id` = `contact`.`id` WHERE " . array_shift($condition) . " GROUP BY `quote-uri-id`";
1112 $rows = DBA::p($sql, $condition);
1113 while ($row = DBA::fetch($rows)) {
1114 $quotes[$row['quote-uri-id']]['total'] = $row['total'];
1115 $quotes[$row['quote-uri-id']]['title'] = array_unique(explode($separator, $row['title']));
1123 * Plucks the children of the given parent from a given item list.
1125 * @param array $item_list
1126 * @param array $parent
1127 * @param bool $recursive
1130 private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1132 $this->profiler->startRecording('rendering');
1134 foreach ($item_list as $i => $item) {
1135 if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1137 // Fallback to parent-uri if thr-parent is not set
1138 $thr_parent = $item['thr-parent-id'];
1139 if ($thr_parent == '') {
1140 $thr_parent = $item['parent-uri-id'];
1143 if ($thr_parent == $parent['uri-id']) {
1144 $item['children'] = $this->getItemChildren($item_list, $item);
1146 $children[] = $item;
1147 unset($item_list[$i]);
1149 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1150 $children[] = $item;
1151 unset($item_list[$i]);
1155 $this->profiler->stopRecording();
1160 * Recursively sorts a tree-like item array
1162 * @param array $items
1165 private function sortItemChildren(array $items): array
1167 $this->profiler->startRecording('rendering');
1169 usort($result, [$this, 'sortThrReceivedRev']);
1170 foreach ($result as $k => $i) {
1171 if (isset($result[$k]['children'])) {
1172 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1175 $this->profiler->stopRecording();
1180 * Recursively add all children items at the top level of a list
1182 * @param array $children List of items to append
1183 * @param array $item_list
1185 private function addChildrenToList(array $children, array &$item_list)
1187 foreach ($children as $child) {
1188 $item_list[] = $child;
1189 if (isset($child['children'])) {
1190 $this->addChildrenToList($child['children'], $item_list);
1196 * Selectively flattens a tree-like item structure to prevent threading stairs
1198 * This recursive function takes the item tree structure created by conv_sort() and
1199 * flatten the extraneous depth levels when people reply sequentially, removing the
1200 * stairs effect in threaded conversations limiting the available content width.
1202 * The basic principle is the following: if a post item has only one reply and is
1203 * the last reply of its parent, then the reply is moved to the parent.
1205 * This process is rendered somewhat more complicated because items can be either
1206 * replies or likes, and these don't factor at all in the reply count/last reply.
1208 * @param array $parent A tree-like array of items
1211 private function smartFlattenConversation(array $parent): array
1213 $this->profiler->startRecording('rendering');
1214 if (!isset($parent['children']) || count($parent['children']) == 0) {
1215 $this->profiler->stopRecording();
1219 // We use a for loop to ensure we process the newly-moved items
1220 for ($i = 0; $i < count($parent['children']); $i++) {
1221 $child = $parent['children'][$i];
1223 if (isset($child['children']) && count($child['children'])) {
1224 // This helps counting only the regular posts
1225 $count_post_closure = function ($var) {
1226 $this->profiler->stopRecording();
1227 return $var['verb'] === Activity::POST;
1230 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1232 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1234 // If there's only one child's children post and this is the last child post
1235 if ($child_post_count == 1 && $remaining_post_count == 1) {
1237 // Searches the post item in the children
1239 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1243 $moved_item = $child['children'][$j];
1244 unset($parent['children'][$i]['children'][$j]);
1245 $parent['children'][] = $moved_item;
1247 $parent['children'][$i] = $this->smartFlattenConversation($child);
1252 $this->profiler->stopRecording();
1257 * Expands a flat list of items into corresponding tree-like conversation structures.
1259 * sort the top-level posts either on "received" or "commented", and finally
1260 * append all the items at the top level (???)
1262 * @param array $item_list A list of items belonging to one or more conversations
1263 * @param string $order Either on "received" or "commented"
1265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1267 private function convSort(array $item_list, string $order): array
1269 $this->profiler->startRecording('rendering');
1272 if (!(is_array($item_list) && count($item_list))) {
1273 $this->profiler->stopRecording();
1277 $blocklist = $this->getBlocklist();
1281 // Dedupes the item list on the uri to prevent infinite loops
1282 foreach ($item_list as $item) {
1283 if (in_array($item['author-id'], $blocklist)) {
1287 $item_array[$item['uri-id']] = $item;
1290 // Extract the top level items
1291 foreach ($item_array as $item) {
1292 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1297 if (stristr($order, 'pinned_received')) {
1298 usort($parents, [$this, 'sortThrFeaturedReceived']);
1299 } elseif (stristr($order, 'pinned_commented')) {
1300 usort($parents, [$this, 'sortThrFeaturedCommented']);
1301 } elseif (stristr($order, 'received')) {
1302 usort($parents, [$this, 'sortThrReceived']);
1303 } elseif (stristr($order, 'commented')) {
1304 usort($parents, [$this, 'sortThrCommented']);
1305 } elseif (stristr($order, 'created')) {
1306 usort($parents, [$this, 'sortThrCreated']);
1310 * Plucks children from the item_array, second pass collects eventual orphan
1311 * items and add them as children of their top-level post.
1313 foreach ($parents as $i => $parent) {
1314 $parents[$i]['children'] = array_merge(
1315 $this->getItemChildren($item_array, $parent, true),
1316 $this->getItemChildren($item_array, $parent, false)
1320 foreach ($parents as $i => $parent) {
1321 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1324 if (!$this->pConfig->get($this->session->getLocalUserId(), 'system', 'no_smart_threading', 0)) {
1325 foreach ($parents as $i => $parent) {
1326 $parents[$i] = $this->smartFlattenConversation($parent);
1330 /// @TODO: Stop recursively adding all children back to the top level (!!!)
1331 /// However, this apparently ensures responses (likes, attendance) display (?!)
1332 foreach ($parents as $parent) {
1333 if (count($parent['children'])) {
1334 $this->addChildrenToList($parent['children'], $parents);
1338 $this->profiler->stopRecording();
1343 * usort() callback to sort item arrays by featured and the received key
1349 private function sortThrFeaturedReceived(array $a, array $b): int
1351 if ($b['featured'] && !$a['featured']) {
1353 } elseif (!$b['featured'] && $a['featured']) {
1357 return strcmp($b['received'], $a['received']);
1361 * usort() callback to sort item arrays by featured and the received key
1367 private function sortThrFeaturedCommented(array $a, array $b): int
1369 if ($b['featured'] && !$a['featured']) {
1371 } elseif (!$b['featured'] && $a['featured']) {
1375 return strcmp($b['commented'], $a['commented']);
1379 * usort() callback to sort item arrays by the received key
1385 private function sortThrReceived(array $a, array $b): int
1387 return strcmp($b['received'], $a['received']);
1391 * usort() callback to reverse sort item arrays by the received key
1397 private function sortThrReceivedRev(array $a, array $b): int
1399 return strcmp($a['received'], $b['received']);
1403 * usort() callback to sort item arrays by the commented key
1409 private function sortThrCommented(array $a, array $b): int
1411 return strcmp($b['commented'], $a['commented']);
1415 * usort() callback to sort item arrays by the created key
1421 private function sortThrCreated(array $a, array $b): int
1423 return strcmp($b['created'], $a['created']);
1427 * "New Item View" on network page or search page results
1428 * - just loop through the items and format them minimally for display
1430 * @param array $items
1431 * @param string $mode One of self::MODE_*
1432 * @param bool $preview Whether the display is a preview
1433 * @param bool $pagedrop Whether the user can select the threads for deletion
1434 * @param string $formSecurityToken A 'contact_action' form security token
1436 * @throws InternalServerErrorException
1437 * @throws \ImagickException
1439 public function getContextLessThreadList(array $items, string $mode, bool $preview, bool $pagedrop, string $formSecurityToken): array
1444 foreach ($items as $item) {
1445 if (in_array($item['uri-id'], $uriids)) {
1449 $uriids[] = $item['uri-id'];
1451 if (!$this->item->isVisibleActivity($item)) {
1455 if (in_array($item['author-id'], $this->getBlocklist())) {
1459 // prevent private email from leaking.
1460 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
1464 $profile_name = $item['author-name'];
1465 if (!empty($item['author-link']) && empty($item['author-name'])) {
1466 $profile_name = $item['author-link'];
1469 $tags = Tag::populateFromItem($item);
1473 'id' => $item['author-id'],
1474 'network' => $item['author-network'],
1475 'url' => $item['author-link'],
1476 'alias' => $item['author-alias'],
1478 $profile_link = Contact::magicLinkByContact($author);
1481 if (strpos($profile_link, 'contact/redir/') === 0) {
1482 $sparkle = ' sparkle';
1485 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
1486 Hook::callAll('render_location', $locate);
1487 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
1489 $this->item->localize($item);
1490 if ($mode === self::MODE_FILED) {
1497 'dropping' => $dropping,
1498 'pagedrop' => $pagedrop,
1499 'select' => $this->l10n->t('Select'),
1500 'delete' => $this->l10n->t('Delete'),
1510 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
1511 unset($likebuttons['dislike']);
1514 $body_html = ItemModel::prepareBody($item, true, $preview);
1516 [$categories, $folders] = $this->item->determineCategoriesTerms($item, $this->session->getLocalUserId());
1518 if (!empty($item['title'])) {
1519 $title = $item['title'];
1520 } elseif (!empty($item['content-warning']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'disable_cw', false)) {
1521 $title = ucfirst($item['content-warning']);
1526 if (!empty($item['featured'])) {
1527 $pinned = $this->l10n->t('Pinned item');
1533 'template' => 'search_item.tpl',
1534 'id' => ($preview ? 'P0' : $item['id']),
1535 'guid' => ($preview ? 'Q0' : $item['guid']),
1536 'commented' => $item['commented'],
1537 'received' => $item['received'],
1538 'created_date' => $item['created'],
1539 'uriid' => $item['uri-id'],
1540 'author_gsid' => $item['author-gsid'],
1541 'network' => $item['network'],
1542 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
1543 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
1544 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
1545 'profile_url' => $profile_link,
1546 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
1547 'name' => $profile_name,
1548 'sparkle' => $sparkle,
1550 'thumb' => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
1552 'body_html' => $body_html,
1553 'tags' => $tags['tags'],
1554 'hashtags' => $tags['hashtags'],
1555 'mentions' => $tags['mentions'],
1556 'implicit_mentions' => $tags['implicit_mentions'],
1557 'txt_cats' => $this->l10n->t('Categories:'),
1558 'txt_folders' => $this->l10n->t('Filed under:'),
1559 'has_cats' => ((count($categories)) ? 'true' : ''),
1560 'has_folders' => ((count($folders)) ? 'true' : ''),
1561 'categories' => $categories,
1562 'folders' => $folders,
1563 'text' => strip_tags($body_html),
1564 'localtime' => DateTimeFormat::local($item['created'], 'r'),
1565 'utc' => DateTimeFormat::utc($item['created'], 'c'),
1566 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
1567 'location_html' => $location_html,
1571 'owner_photo' => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
1572 'plink' => ItemModel::getPlink($item),
1574 'pinned' => $pinned,
1575 'isstarred' => 'unstarred',
1578 'vote' => $likebuttons,
1580 'dislike_html ' => '',
1581 'comment_html' => '',
1582 'conv' => $preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')],
1583 'previewing' => $preview ? ' preview ' : '',
1584 'wait' => $this->l10n->t('Please wait'),
1585 'thread_level' => 1,
1588 $arr = ['item' => $item, 'output' => $tmp_item];
1589 Hook::callAll('display_item', $arr);
1592 'id' => $item['id'],
1593 'network' => $item['network'],
1594 'items' => [$arr['output']],