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 */
102 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)
104 $this->activity = $activity;
106 $this->config = $config;
108 $this->baseURL = $baseURL;
109 $this->profiler = $profiler;
110 $this->logger = $logger;
113 $this->pConfig = $pConfig;
116 $this->session = $session;
117 $this->userGServer = $userGServer;
121 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
123 * Increments the count of each matching activity and adds a link to the author as needed.
125 * @param array $activity
126 * @param array &$conv_responses (already created with builtin activity structure)
128 * @throws ImagickException
129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
131 public function builtinActivityPuller(array $activity, array &$conv_responses)
133 $thread_parent = $activity['thr-parent-row'] ?? [];
135 foreach ($conv_responses as $mode => $v) {
140 $verb = Activity::LIKE;
143 $verb = Activity::DISLIKE;
146 $verb = Activity::ATTEND;
149 $verb = Activity::ATTENDNO;
152 $verb = Activity::ATTENDMAYBE;
155 $verb = Activity::ANNOUNCE;
161 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
164 'id' => $activity['author-id'],
165 'network' => $activity['author-network'],
166 'url' => $activity['author-link'],
167 'alias' => $activity['author-alias'],
169 $url = Contact::magicLinkByContact($author);
170 if (strpos($url, 'contact/redir/') === 0) {
171 $sparkle = ' class="sparkle" ';
174 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
176 if (empty($activity['thr-parent-id'])) {
177 $activity['thr-parent-id'] = $activity['parent-uri-id'];
180 // Skip when the causer of the parent is the same as the author of the announce
181 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
185 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
186 $conv_responses[$mode][$activity['thr-parent-id']] = [
190 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
191 // only list each unique author once
195 if ($this->session->getPublicContactId() == $activity['author-id']) {
196 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
199 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
201 // there can only be one activity verb per item so if we found anything, we can stop looking
208 * Returns the liker phrase based on a list of likers
210 * @param string $verb the activity verb
211 * @param array $likers a list of likers
213 * @return string the liker phrase
215 * @throws InternalServerErrorException in case either the verb is invalid or the list of likers is empty
217 private function getLikerPhrase(string $verb, array $likers): string
219 $total = count($likers);
222 throw new InternalServerErrorException(sprintf('There has to be at least one Liker for verb "%s"', $verb));
223 } else if ($total === 1) {
224 $likerString = $likers[0];
226 if ($total < $this->config->get('system', 'max_likers')) {
227 $likerString = implode(', ', array_slice($likers, 0, -1));
228 $likerString .= ' ' . $this->l10n->t('and') . ' ' . $likers[count($likers) - 1];
230 $likerString = implode(', ', array_slice($likers, 0, $this->config->get('system', 'max_likers') - 1));
231 $likerString .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
237 return $this->l10n->tt('%2$s likes this.', '%2$s like this.', $total, $likerString);
239 return $this->l10n->tt('%2$s doesn\'t like this.', '%2$s don\'t like this.', $total, $likerString);
241 return $this->l10n->tt('%2$s attends.', '%2$s attend.', $total, $likerString);
243 return $this->l10n->tt('%2$s doesn\'t attend.', '%2$s don\'t attend.', $total, $likerString);
245 return $this->l10n->tt('%2$s attends maybe.', '%2$s attend maybe.', $total, $likerString);
247 return $this->l10n->tt('%2$s reshared this.', '%2$s reshared this.', $total, $likerString);
249 throw new InternalServerErrorException(sprintf('Unknown verb "%s"', $verb));
254 * Format the activity text for an item/photo/video
256 * @param array $links array of pre-linked names of actors
257 * @param string $verb one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
258 * @param int $id item id
259 * @param string $activity Activity URI
260 * @param array $emojis Array with emoji reactions
261 * @return string formatted text
262 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
264 public function formatActivity(array $links, string $verb, int $id, string $activity, array $emojis): string
266 $this->profiler->startRecording('rendering');
269 $phrase = $this->getLikerPhrase($verb, $links);
270 $total = max(count($links), $emojis[$activity]['total'] ?? 0);
273 $spanatts = "class=\"btn btn-link fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
274 $explikers = $phrase;
278 $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);
281 $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);
284 $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);
287 $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);
290 $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);
293 $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);
297 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
300 $output = Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
301 '$phrase' => $phrase,
305 $output .= $expanded;
307 $this->profiler->stopRecording();
311 public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
313 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
314 if (empty($user['uid'])) {
318 $this->profiler->startRecording('rendering');
321 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
322 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
323 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
324 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
325 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
326 $x['bang'] = $x['bang'] ?? '';
327 $x['visitor'] = $x['visitor'] ?? 'block';
328 $x['is_owner'] = $x['is_owner'] ?? true;
329 $x['profile_uid'] = $x['profile_uid'] ?? $this->session->getLocalUserId();
332 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
334 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
335 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
336 '$newpost' => 'true',
337 '$baseurl' => $this->baseURL,
338 '$geotag' => $geotag,
339 '$nickname' => $x['nickname'],
340 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
341 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
342 '$term' => $this->l10n->t('Tag term:'),
343 '$fileas' => $this->l10n->t('Save to Folder:'),
344 '$whereareu' => $this->l10n->t('Where are you right now?'),
345 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
346 '$is_mobile' => $this->mode->isMobile(),
350 Hook::callAll('jot_tool', $jotplugins);
352 if ($this->config->get('system', 'set_creation_date')) {
353 $created_at = Temporal::getDateTimeField(
354 new \DateTime(DBA::NULL_DATETIME),
355 new \DateTime('now'),
357 $this->l10n->t('Created at'),
364 $tpl = Renderer::getMarkupTemplate('jot.tpl');
366 $o .= Renderer::replaceMacros($tpl, [
367 '$new_post' => $this->l10n->t('New Post'),
368 '$return_path' => $this->args->getQueryString(),
370 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
371 '$loading' => $this->l10n->t('Loading...'),
372 '$upload' => $this->l10n->t('Upload photo'),
373 '$shortupload' => $this->l10n->t('upload photo'),
374 '$attach' => $this->l10n->t('Attach file'),
375 '$shortattach' => $this->l10n->t('attach file'),
376 '$edbold' => $this->l10n->t('Bold'),
377 '$editalic' => $this->l10n->t('Italic'),
378 '$eduline' => $this->l10n->t('Underline'),
379 '$edquote' => $this->l10n->t('Quote'),
380 '$edemojis' => $this->l10n->t('Add emojis'),
381 '$contentwarn' => $this->l10n->t('Content Warning'),
382 '$edcode' => $this->l10n->t('Code'),
383 '$edimg' => $this->l10n->t('Image'),
384 '$edurl' => $this->l10n->t('Link'),
385 '$edattach' => $this->l10n->t('Link or Media'),
386 '$edvideo' => $this->l10n->t('Video'),
387 '$setloc' => $this->l10n->t('Set your location'),
388 '$shortsetloc' => $this->l10n->t('set location'),
389 '$noloc' => $this->l10n->t('Clear browser location'),
390 '$shortnoloc' => $this->l10n->t('clear location'),
391 '$title' => $x['title'] ?? '',
392 '$placeholdertitle' => $this->l10n->t('Set title'),
393 '$category' => $x['category'] ?? '',
394 '$placeholdercategory' => Feature::isEnabled($this->session->getLocalUserId(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
395 '$scheduled_at' => Temporal::getDateTimeField(
397 new \DateTime('now + 6 months'),
399 $this->l10n->t('Scheduled at'),
402 '$created_at' => $created_at,
403 '$wait' => $this->l10n->t('Please wait'),
404 '$permset' => $this->l10n->t('Permission settings'),
405 '$shortpermset' => $this->l10n->t('Permissions'),
406 '$wall' => $notes_cid ? 0 : 1,
407 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
408 '$content' => $x['content'] ?? '',
409 '$post_id' => $x['post_id'] ?? '',
410 '$baseurl' => $this->baseURL,
411 '$defloc' => $x['default_location'],
412 '$visitor' => $x['visitor'],
413 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
414 '$public' => $this->l10n->t('Public post'),
415 '$lockstate' => $x['lockstate'],
416 '$bang' => $x['bang'],
417 '$profile_uid' => $x['profile_uid'],
418 '$preview' => $this->l10n->t('Preview'),
419 '$jotplugins' => $jotplugins,
420 '$notes_cid' => $notes_cid,
421 '$cancel' => $this->l10n->t('Cancel'),
422 '$rand_num' => Crypto::randomDigits(12),
424 // ACL permissions box
427 //jot nav tab (used in some themes)
428 '$message' => $this->l10n->t('Message'),
429 '$browser' => $this->l10n->t('Browser'),
431 '$compose_link_title' => $this->l10n->t('Open Compose page'),
432 '$always_open_compose' => $this->pConfig->get($this->session->getLocalUserId(), 'frio', 'always_open_compose', false),
436 if ($popup == true) {
437 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
440 $this->profiler->stopRecording();
445 * "Render" a conversation or list of items for HTML display.
446 * There are two major forms of display:
447 * - Sequential or unthreaded ("New Item View" or search results)
448 * - conversation view
449 * The $mode parameter decides between the various renderings and also
450 * figures out how to determine page owner and other contextual items
451 * that are based on unique features of the calling module.
452 * @param array $items An array of Posts
453 * @param string $mode One of self::MODE_*
454 * @param bool $update Asynchronous update rendering
455 * @param bool $preview Post preview (no actual database record)
456 * @param string $order Either "received" or "commented"
459 * @throws ImagickException
460 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462 public function render(array $items, string $mode, bool $update = false, bool $preview = false, string $order = 'commented', int $uid = 0): string
464 $this->profiler->startRecording('rendering');
466 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
467 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
468 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
469 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
471 $live_update_div = '';
473 $userGservers = $this->userGServer->listIgnoredByUser($this->session->getLocalUserId());
475 $ignoredGsids = array_map(function (UserGServer $userGServer) {
476 return $userGServer->gsid;
477 }, $userGservers->getArrayCopy());
479 if ($mode === self::MODE_NETWORK) {
480 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
483 * The special div is needed for liveUpdate to kick in for this page.
484 * We only launch liveUpdate if you aren't filtering in some incompatible
485 * way and also you aren't writing a comment (discovered in javascript).
487 $live_update_div = '<div id="live-network"></div>' . "\r\n"
488 . "<script> var profile_uid = " . $_SESSION['uid']
489 . "; var netargs = '" . substr($this->args->getCommand(), 8)
491 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
492 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
493 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
494 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
495 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
496 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
497 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
498 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
499 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
500 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
501 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
502 . (!empty($_GET['channel']) ? '&channel=' . rawurlencode($_GET['channel']) : '')
503 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
504 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
505 . "'; </script>\r\n";
507 } elseif ($mode === self::MODE_PROFILE) {
508 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
511 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
513 if ($tab === 'posts') {
515 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
516 * because browser prefetching might change it on us. We have to deliver it with the page.
519 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
520 . "<script> var profile_uid = " . $uid
521 . "; var netargs = '?f='; </script>\r\n";
524 } elseif ($mode === self::MODE_NOTES) {
525 $items = $this->addChildren($items, false, $order, $this->session->getLocalUserId(), $mode);
528 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
529 . "<script> var profile_uid = " . $this->session->getLocalUserId()
530 . "; var netargs = '?f='; </script>\r\n";
532 } elseif ($mode === self::MODE_DISPLAY) {
533 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
536 $live_update_div = '<div id="live-display"></div>' . "\r\n"
537 . "<script> var profile_uid = " . ($this->session->getLocalUserId() ?: 0) . ";"
540 } elseif ($mode === self::MODE_CHANNEL) {
541 $items = $this->addChildren($items, true, $order, $uid, $mode, $ignoredGsids);
544 $live_update_div = '<div id="live-channel"></div>' . "\r\n"
545 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
547 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
548 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
549 . "'; </script>\r\n";
551 } elseif ($mode === self::MODE_COMMUNITY) {
552 $items = $this->addChildren($items, true, $order, $uid, $mode, $ignoredGsids);
555 $live_update_div = '<div id="live-community"></div>' . "\r\n"
556 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
558 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
559 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
560 . "'; </script>\r\n";
562 } elseif ($mode === self::MODE_CONTACTS) {
563 $items = $this->addChildren($items, false, $order, $uid, $mode, $ignoredGsids);
566 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
567 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
568 . "?f='; </script>\r\n";
570 } elseif ($mode === self::MODE_SEARCH) {
571 $live_update_div = '<div id="live-search"></div>' . "\r\n";
574 $page_dropping = $this->session->getLocalUserId() && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'show_page_drop', true) && ($this->session->getLocalUserId() == $uid && $mode != self::MODE_SEARCH);
577 $_SESSION['return_path'] = $this->args->getQueryString();
580 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
581 Hook::callAll('conversation_start', $cb);
583 $items = $cb['items'];
585 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
587 $threads = $this->getThreadList($items, $mode, $preview, $page_dropping, $formSecurityToken);
589 if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
590 $page_template = Renderer::getMarkupTemplate('conversation.tpl');
592 $page_template = Renderer::getMarkupTemplate('threaded_conversation.tpl');
595 $o = Renderer::replaceMacros($page_template, [
596 '$baseurl' => $this->baseURL,
597 '$return_path' => $this->args->getQueryString(),
598 '$live_update' => $live_update_div,
599 '$remove' => $this->l10n->t('remove'),
601 '$update' => $update,
602 '$threads' => $threads,
603 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
606 $this->profiler->stopRecording();
611 * @param array $items
612 * @param string $mode One of self::MODE_*
613 * @param bool $preview
614 * @param bool $pagedrop Whether to enable the user to select the thread for deletion
615 * @param string $formSecurityToken A 'contact_action' form security token
617 * @throws InternalServerErrorException
618 * @throws \ImagickException
620 public function getThreadList(array $items, string $mode, bool $preview, bool $pagedrop, string $formSecurityToken): array
626 if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
627 $threads = $this->getContextLessThreadList($items, $mode, $preview, $pagedrop, $formSecurityToken);
638 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
639 unset($conv_responses['dislike']);
642 if (in_array($mode, [self::MODE_CHANNEL, self::MODE_COMMUNITY, self::MODE_CONTACTS, self::MODE_PROFILE])) {
645 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
648 if (!$this->session->getLocalUserId()) {
653 $conv = new Thread($mode, $preview, $writable);
656 * get all the topmost parents
657 * this shouldn't be needed, as we should have only them in our array
658 * But for now, this array respects the old style, just in case
660 foreach ($items as $item) {
661 // Can we put this after the visibility check?
662 $this->builtinActivityPuller($item, $conv_responses);
664 // Only add what is visible
665 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
669 if (!$this->item->isVisibleActivity($item)) {
673 /// @todo Check if this call is needed or not
674 $arr = ['item' => $item];
675 Hook::callAll('display_item', $arr);
677 $item['pagedrop'] = $pagedrop;
679 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
680 $item_object = new PostObject($item);
681 $conv->addParent($item_object);
685 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
687 $this->logger->info('[ERROR] conversation : Failed to get template data.');
696 * Adds some information (Causer, post reason, direction) to the fetched post row.
698 * @param array $row Post row
699 * @param array $activity Contact data of the resharer
700 * @param array $thr_parent Thread parent row
702 * @return array items with parents and comments
704 private function addRowInformation(array $row, array $activity, array $thr_parent): array
706 $this->profiler->startRecording('rendering');
708 if (!$row['writable']) {
709 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
712 if (!empty($activity)) {
713 if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
714 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
716 $row = array_merge($row, $activity);
717 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
719 $row['causer-link'] = $contact['url'];
720 $row['causer-avatar'] = $contact['thumb'];
721 $row['causer-name'] = $contact['name'];
722 } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
723 ($row['author-id'] == $activity['causer-id'])
729 switch ($row['post-reason']) {
730 case ItemModel::PR_TO:
731 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
733 case ItemModel::PR_CC:
734 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
736 case ItemModel::PR_BTO:
737 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
739 case ItemModel::PR_BCC:
740 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
742 case ItemModel::PR_AUDIENCE:
743 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'audience')];
745 case ItemModel::PR_FOLLOWER:
746 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
748 case ItemModel::PR_TAG:
749 $tags = Category::getArrayByURIId($row['uri-id'], $row['uid'], Category::SUBCRIPTION);
751 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to %s.', implode(', ', $tags))];
753 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
756 case ItemModel::PR_ANNOUNCEMENT:
757 if (!empty($row['causer-id']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'display_resharer')) {
758 $row['owner-id'] = $row['causer-id'];
759 $row['owner-link'] = $row['causer-link'];
760 $row['owner-avatar'] = $row['causer-avatar'];
761 $row['owner-name'] = $row['causer-name'];
764 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
767 'id' => $row['causer-id'],
768 'network' => $row['causer-network'],
769 'url' => $row['causer-link'],
770 'alias' => $row['causer-alias'],
773 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="' . htmlentities(Contact::magicLinkByContact($causer)) . '">' . htmlentities($row['causer-name']) . '</a>');
775 $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']))];
777 case ItemModel::PR_COMMENT:
778 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
780 case ItemModel::PR_STORED:
781 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
783 case ItemModel::PR_GLOBAL:
784 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
786 case ItemModel::PR_RELAY:
787 $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']))];
789 case ItemModel::PR_FETCHED:
790 $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']))];
792 case ItemModel::PR_COMPLETION:
793 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
795 case ItemModel::PR_DIRECT:
796 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
798 case ItemModel::PR_ACTIVITY:
799 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
801 case ItemModel::PR_DISTRIBUTE:
802 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
804 case ItemModel::PR_PUSHED:
805 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
809 $row['thr-parent-row'] = $thr_parent;
811 $this->profiler->stopRecording();
816 * Add comments to top level entries that had been fetched before
818 * The system will fetch the comments for the local user whenever possible.
819 * This behaviour is currently needed to allow commenting on Friendica posts.
821 * @param array $parents Parent items
822 * @param bool $block_authors
823 * @param string $order Either "received" or "commented"
825 * @param string $mode One of self::MODE_*
826 * @param array $ignoredGsids List of ids of servers ignored by the user
827 * @return array items with parents and comments
828 * @throws InternalServerErrorException
830 private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode, array $ignoredGsids = []): array
832 $this->profiler->startRecording('rendering');
833 if (count($parents) > 1) {
834 $max_comments = $this->config->get('system', 'max_comments', 100);
836 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
841 $commentcounter = [];
842 $activitycounter = [];
844 foreach ($parents as $parent) {
845 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
846 $uriid = $parent['thr-parent-id'];
847 if (!empty($parent['author-id'])) {
848 $activities[$uriid] = ['causer-id' => $parent['author-id']];
849 foreach (['commented', 'received', 'created'] as $orderfields) {
850 if (!empty($parent[$orderfields])) {
851 $activities[$uriid][$orderfields] = $parent[$orderfields];
856 $uriid = $parent['uri-id'];
860 $commentcounter[$uriid] = 0;
861 $activitycounter[$uriid] = 0;
864 $condition = ['parent-uri-id' => $uriids];
865 if ($block_authors) {
866 $condition['author-hidden'] = false;
869 $emojis = $this->getEmojis($uriids);
870 $quoteshares = $this->getQuoteShares($uriids);
872 if (!$this->config->get('system', 'legacy_activities')) {
873 $condition = DBA::mergeConditions($condition, ["(`gravity` != ? OR `origin`)", ItemModel::GRAVITY_ACTIVITY]);
876 $condition = DBA::mergeConditions(
878 ["`uid` IN (0, ?) AND (NOT `vid` IN (?, ?, ?) OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW), Verb::getID(Activity::VIEW), Verb::getID(Activity::READ)]
881 $condition = DBA::mergeConditions($condition, ["(`uid` != ? OR `private` != ?)", 0, ItemModel::PRIVATE]);
883 $condition = DBA::mergeConditions(
886 "`visible` AND NOT `deleted` AND NOT `author-blocked` AND NOT `owner-blocked`
887 AND ((NOT `contact-pending` AND (`contact-rel` IN (?, ?))) OR `self` OR `contact-uid` = ?)",
888 Contact::SHARING, Contact::FRIEND, 0
892 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
896 while ($row = Post::fetch($thread_parents)) {
897 $thr_parent[$row['uri-id']] = $row;
899 DBA::close($thread_parents);
901 $params = ['order' => ['uri-id' => true, 'uid' => true]];
903 $thread_items = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
909 while ($row = Post::fetch($thread_items)) {
910 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
915 in_array($row['author-gsid'], $ignoredGsids)
916 || in_array($row['owner-gsid'], $ignoredGsids)
917 || in_array($row['causer-gsid'], $ignoredGsids)
922 if (($mode != self::MODE_CONTACTS) && !$row['origin']) {
923 $row['featured'] = false;
926 if ($max_comments > 0) {
927 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
930 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
935 $authors[] = $row['author-id'];
936 $authors[] = $row['owner-id'];
938 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT])) {
939 $quote_uri_ids[$row['uri-id']] = [
940 'uri-id' => $row['uri-id'],
941 'uri' => $row['uri'],
942 'parent-uri-id' => $row['parent-uri-id'],
943 'parent-uri' => $row['parent-uri'],
947 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
950 DBA::close($thread_items);
952 $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]);
953 while ($quote = Post::fetch($quotes)) {
957 $row['verb'] = $row['body'] = $row['raw-body'] = Activity::ANNOUNCE;
958 $row['gravity'] = ItemModel::GRAVITY_ACTIVITY;
959 $row['object-type'] = Activity\ObjectType::NOTE;
960 $row['parent-uri'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri'];
961 $row['parent-uri-id'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri-id'];
962 $row['thr-parent'] = $quote_uri_ids[$quote['quote-uri-id']]['uri'];
963 $row['thr-parent-id'] = $quote_uri_ids[$quote['quote-uri-id']]['uri-id'];
965 $authors[] = $row['author-id'];
966 $authors[] = $row['owner-id'];
968 $items[$row['uri-id']] = $this->addRowInformation($row, [], []);
972 $authors = array_unique($authors);
977 if (!empty($authors)) {
978 $usercontacts = DBA::select('user-contact', ['cid', 'blocked', 'ignored', 'collapsed'], ['uid' => $uid, 'cid' => $authors]);
979 while ($usercontact = DBA::fetch($usercontacts)) {
980 if ($usercontact['blocked']) {
981 $blocks[] = $usercontact['cid'];
983 if ($usercontact['ignored']) {
984 $ignores[] = $usercontact['cid'];
986 if ($usercontact['collapsed']) {
987 $collapses[] = $usercontact['cid'];
990 DBA::close($usercontacts);
993 foreach ($items as $key => $row) {
994 $items[$key]['emojis'] = $emojis[$key] ?? [];
995 $items[$key]['quoteshares'] = $quoteshares[$key] ?? [];
997 $always_display = in_array($mode, [self::MODE_CONTACTS, self::MODE_CONTACT_POSTS]);
999 $items[$key]['user-blocked-author'] = !$always_display && in_array($row['author-id'], $blocks);
1000 $items[$key]['user-ignored-author'] = !$always_display && in_array($row['author-id'], $ignores);
1001 $items[$key]['user-blocked-owner'] = !$always_display && in_array($row['owner-id'], $blocks);
1002 $items[$key]['user-ignored-owner'] = !$always_display && in_array($row['owner-id'], $ignores);
1003 $items[$key]['user-collapsed-author'] = !$always_display && in_array($row['author-id'], $collapses);
1004 $items[$key]['user-collapsed-owner'] = !$always_display && in_array($row['owner-id'], $collapses);
1007 in_array($mode, [self::MODE_CHANNEL, self::MODE_COMMUNITY, self::MODE_NETWORK]) &&
1008 (in_array($row['author-id'], $blocks) || in_array($row['owner-id'], $blocks) || in_array($row['author-id'], $ignores) || in_array($row['owner-id'], $ignores))
1010 unset($items[$key]);
1014 $items = $this->convSort($items, $order);
1016 $this->profiler->stopRecording();
1021 * Fetch emoji reaction from the conversation
1023 * @param array $uriids
1026 private function getEmojis(array $uriids): array
1029 Activity::LIKE => '👍',
1030 Activity::DISLIKE => '👎',
1031 Activity::ATTEND => '✔️',
1032 Activity::ATTENDMAYBE => '❓',
1033 Activity::ATTENDNO => '❌',
1034 Activity::ANNOUNCE => '♻',
1035 Activity::VIEW => '📺',
1038 $index_list = array_values($activity_emoji);
1039 $verbs = array_merge(array_keys($activity_emoji), [Activity::EMOJIREACT, Activity::POST]);
1041 $condition = DBA::mergeConditions(['parent-uri-id' => $uriids, 'gravity' => [ItemModel::GRAVITY_ACTIVITY, ItemModel::GRAVITY_COMMENT], 'verb' => $verbs], ["NOT `deleted`"]);
1042 $separator = chr(255) . chr(255) . chr(255);
1044 $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`";
1048 $rows = DBA::p($sql, $condition);
1049 while ($row = DBA::fetch($rows)) {
1050 if ($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) {
1051 $row['verb'] = $row['body'] ? Activity::EMOJIREACT : $row['verb'];
1052 $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 * Fetch quote shares from the conversation
1075 * @param array $uriids
1078 private function getQuoteShares(array $uriids): array
1080 $condition = DBA::mergeConditions(['quote-uri-id' => $uriids], ["NOT `quote-uri-id` IS NULL"]);
1081 $separator = chr(255) . chr(255) . chr(255);
1083 $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`";
1087 $rows = DBA::p($sql, $condition);
1088 while ($row = DBA::fetch($rows)) {
1089 $quotes[$row['quote-uri-id']]['total'] = $row['total'];
1090 $quotes[$row['quote-uri-id']]['title'] = array_unique(explode($separator, $row['title']));
1098 * Plucks the children of the given parent from a given item list.
1100 * @param array $item_list
1101 * @param array $parent
1102 * @param bool $recursive
1105 private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1107 $this->profiler->startRecording('rendering');
1109 foreach ($item_list as $i => $item) {
1110 if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1112 // Fallback to parent-uri if thr-parent is not set
1113 $thr_parent = $item['thr-parent-id'];
1114 if ($thr_parent == '') {
1115 $thr_parent = $item['parent-uri-id'];
1118 if ($thr_parent == $parent['uri-id']) {
1119 $item['children'] = $this->getItemChildren($item_list, $item);
1121 $children[] = $item;
1122 unset($item_list[$i]);
1124 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1125 $children[] = $item;
1126 unset($item_list[$i]);
1130 $this->profiler->stopRecording();
1135 * Recursively sorts a tree-like item array
1137 * @param array $items
1140 private function sortItemChildren(array $items): array
1142 $this->profiler->startRecording('rendering');
1144 usort($result, [$this, 'sortThrReceivedRev']);
1145 foreach ($result as $k => $i) {
1146 if (isset($result[$k]['children'])) {
1147 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1150 $this->profiler->stopRecording();
1155 * Recursively add all children items at the top level of a list
1157 * @param array $children List of items to append
1158 * @param array $item_list
1160 private function addChildrenToList(array $children, array &$item_list)
1162 foreach ($children as $child) {
1163 $item_list[] = $child;
1164 if (isset($child['children'])) {
1165 $this->addChildrenToList($child['children'], $item_list);
1171 * Selectively flattens a tree-like item structure to prevent threading stairs
1173 * This recursive function takes the item tree structure created by conv_sort() and
1174 * flatten the extraneous depth levels when people reply sequentially, removing the
1175 * stairs effect in threaded conversations limiting the available content width.
1177 * The basic principle is the following: if a post item has only one reply and is
1178 * the last reply of its parent, then the reply is moved to the parent.
1180 * This process is rendered somewhat more complicated because items can be either
1181 * replies or likes, and these don't factor at all in the reply count/last reply.
1183 * @param array $parent A tree-like array of items
1186 private function smartFlattenConversation(array $parent): array
1188 $this->profiler->startRecording('rendering');
1189 if (!isset($parent['children']) || count($parent['children']) == 0) {
1190 $this->profiler->stopRecording();
1194 // We use a for loop to ensure we process the newly-moved items
1195 for ($i = 0; $i < count($parent['children']); $i++) {
1196 $child = $parent['children'][$i];
1198 if (isset($child['children']) && count($child['children'])) {
1199 // This helps counting only the regular posts
1200 $count_post_closure = function ($var) {
1201 $this->profiler->stopRecording();
1202 return $var['verb'] === Activity::POST;
1205 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1207 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1209 // If there's only one child's children post and this is the last child post
1210 if ($child_post_count == 1 && $remaining_post_count == 1) {
1212 // Searches the post item in the children
1214 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1218 $moved_item = $child['children'][$j];
1219 unset($parent['children'][$i]['children'][$j]);
1220 $parent['children'][] = $moved_item;
1222 $parent['children'][$i] = $this->smartFlattenConversation($child);
1227 $this->profiler->stopRecording();
1232 * Expands a flat list of items into corresponding tree-like conversation structures.
1234 * sort the top-level posts either on "received" or "commented", and finally
1235 * append all the items at the top level (???)
1237 * @param array $item_list A list of items belonging to one or more conversations
1238 * @param string $order Either on "received" or "commented"
1240 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1242 private function convSort(array $item_list, string $order): array
1244 $this->profiler->startRecording('rendering');
1247 if (!(is_array($item_list) && count($item_list))) {
1248 $this->profiler->stopRecording();
1254 // Dedupes the item list on the uri to prevent infinite loops
1255 foreach ($item_list as $item) {
1256 $item_array[$item['uri-id']] = $item;
1259 // Extract the top level items
1260 foreach ($item_array as $item) {
1261 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1266 if (stristr($order, 'pinned_received')) {
1267 usort($parents, [$this, 'sortThrFeaturedReceived']);
1268 } elseif (stristr($order, 'pinned_commented')) {
1269 usort($parents, [$this, 'sortThrFeaturedCommented']);
1270 } elseif (stristr($order, 'pinned_created')) {
1271 usort($parents, [$this, 'sortThrFeaturedCreated']);
1272 } elseif (stristr($order, 'received')) {
1273 usort($parents, [$this, 'sortThrReceived']);
1274 } elseif (stristr($order, 'commented')) {
1275 usort($parents, [$this, 'sortThrCommented']);
1276 } elseif (stristr($order, 'created')) {
1277 usort($parents, [$this, 'sortThrCreated']);
1281 * Plucks children from the item_array, second pass collects eventual orphan
1282 * items and add them as children of their top-level post.
1284 foreach ($parents as $i => $parent) {
1285 $parents[$i]['children'] = array_merge(
1286 $this->getItemChildren($item_array, $parent, true),
1287 $this->getItemChildren($item_array, $parent, false)
1291 foreach ($parents as $i => $parent) {
1292 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1295 if (!$this->pConfig->get($this->session->getLocalUserId(), 'system', 'no_smart_threading', 0)) {
1296 foreach ($parents as $i => $parent) {
1297 $parents[$i] = $this->smartFlattenConversation($parent);
1301 /// @TODO: Stop recursively adding all children back to the top level (!!!)
1302 /// However, this apparently ensures responses (likes, attendance) display (?!)
1303 foreach ($parents as $parent) {
1304 if (count($parent['children'])) {
1305 $this->addChildrenToList($parent['children'], $parents);
1309 $this->profiler->stopRecording();
1314 * usort() callback to sort item arrays by featured and the received key
1320 private function sortThrFeaturedReceived(array $a, array $b): int
1322 if ($b['featured'] && !$a['featured']) {
1324 } elseif (!$b['featured'] && $a['featured']) {
1328 return strcmp($b['received'], $a['received']);
1332 * usort() callback to sort item arrays by featured and the received key
1338 private function sortThrFeaturedCommented(array $a, array $b): int
1340 if ($b['featured'] && !$a['featured']) {
1342 } elseif (!$b['featured'] && $a['featured']) {
1346 return strcmp($b['commented'], $a['commented']);
1350 * usort() callback to sort item arrays by featured and the created key
1356 private function sortThrFeaturedCreated(array $a, array $b): int
1358 if ($b['featured'] && !$a['featured']) {
1360 } elseif (!$b['featured'] && $a['featured']) {
1364 return strcmp($b['created'], $a['created']);
1368 * usort() callback to sort item arrays by the received key
1374 private function sortThrReceived(array $a, array $b): int
1376 return strcmp($b['received'], $a['received']);
1380 * usort() callback to reverse sort item arrays by the received key
1386 private function sortThrReceivedRev(array $a, array $b): int
1388 return strcmp($a['received'], $b['received']);
1392 * usort() callback to sort item arrays by the commented key
1398 private function sortThrCommented(array $a, array $b): int
1400 return strcmp($b['commented'], $a['commented']);
1404 * usort() callback to sort item arrays by the created key
1410 private function sortThrCreated(array $a, array $b): int
1412 return strcmp($b['created'], $a['created']);
1416 * "New Item View" on network page or search page results
1417 * - just loop through the items and format them minimally for display
1419 * @param array $items
1420 * @param string $mode One of self::MODE_*
1421 * @param bool $preview Whether the display is a preview
1422 * @param bool $pagedrop Whether the user can select the threads for deletion
1423 * @param string $formSecurityToken A 'contact_action' form security token
1425 * @throws InternalServerErrorException
1426 * @throws \ImagickException
1428 public function getContextLessThreadList(array $items, string $mode, bool $preview, bool $pagedrop, string $formSecurityToken): array
1433 foreach ($items as $item) {
1434 if (in_array($item['uri-id'], $uriids)) {
1438 $uriids[] = $item['uri-id'];
1440 if (!$this->item->isVisibleActivity($item)) {
1444 // prevent private email from leaking.
1445 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
1449 $profile_name = $item['author-name'];
1450 if (!empty($item['author-link']) && empty($item['author-name'])) {
1451 $profile_name = $item['author-link'];
1454 $tags = Tag::populateFromItem($item);
1458 'id' => $item['author-id'],
1459 'network' => $item['author-network'],
1460 'url' => $item['author-link'],
1461 'alias' => $item['author-alias'],
1463 $profile_link = Contact::magicLinkByContact($author);
1466 if (strpos($profile_link, 'contact/redir/') === 0) {
1467 $sparkle = ' sparkle';
1470 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
1471 Hook::callAll('render_location', $locate);
1472 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
1474 $this->item->localize($item);
1475 if ($mode === self::MODE_FILED) {
1482 'dropping' => $dropping,
1483 'pagedrop' => $pagedrop,
1484 'select' => $this->l10n->t('Select'),
1485 'delete' => $this->l10n->t('Delete'),
1495 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
1496 unset($likebuttons['dislike']);
1499 $body_html = ItemModel::prepareBody($item, true, $preview);
1501 [$categories, $folders] = $this->item->determineCategoriesTerms($item, $this->session->getLocalUserId());
1503 if (!empty($item['title'])) {
1504 $title = $item['title'];
1505 } elseif (!empty($item['content-warning']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'disable_cw', false)) {
1506 $title = ucfirst($item['content-warning']);
1511 if (!empty($item['featured'])) {
1512 $pinned = $this->l10n->t('Pinned item');
1518 'template' => 'search_item.tpl',
1519 'id' => ($preview ? 'P0' : $item['id']),
1520 'guid' => ($preview ? 'Q0' : $item['guid']),
1521 'commented' => $item['commented'],
1522 'received' => $item['received'],
1523 'created_date' => $item['created'],
1524 'uriid' => $item['uri-id'],
1525 'author_gsid' => $item['author-gsid'],
1526 'network' => $item['network'],
1527 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
1528 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
1529 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
1530 'profile_url' => $profile_link,
1531 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
1532 'name' => $profile_name,
1533 'sparkle' => $sparkle,
1535 'thumb' => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
1537 'body_html' => $body_html,
1538 'tags' => $tags['tags'],
1539 'hashtags' => $tags['hashtags'],
1540 'mentions' => $tags['mentions'],
1541 'implicit_mentions' => $tags['implicit_mentions'],
1542 'txt_cats' => $this->l10n->t('Categories:'),
1543 'txt_folders' => $this->l10n->t('Filed under:'),
1544 'has_cats' => ((count($categories)) ? 'true' : ''),
1545 'has_folders' => ((count($folders)) ? 'true' : ''),
1546 'categories' => $categories,
1547 'folders' => $folders,
1548 'text' => strip_tags($body_html),
1549 'localtime' => DateTimeFormat::local($item['created'], 'r'),
1550 'utc' => DateTimeFormat::utc($item['created'], 'c'),
1551 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
1552 'location_html' => $location_html,
1556 'owner_photo' => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
1557 'plink' => ItemModel::getPlink($item),
1559 'pinned' => $pinned,
1560 'isstarred' => 'unstarred',
1563 'vote' => $likebuttons,
1565 'dislike_html ' => '',
1566 'comment_html' => '',
1567 'conv' => $preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')],
1568 'previewing' => $preview ? ' preview ' : '',
1569 'wait' => $this->l10n->t('Please wait'),
1570 'thread_level' => 1,
1573 $arr = ['item' => $item, 'output' => $tmp_item];
1574 Hook::callAll('display_item', $arr);
1577 'id' => $item['id'],
1578 'network' => $item['network'],
1579 'items' => [$arr['output']],