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\Tag;
42 use Friendica\Model\User;
43 use Friendica\Model\Verb;
44 use Friendica\Network\HTTPException\InternalServerErrorException;
45 use Friendica\Object\Post as PostObject;
46 use Friendica\Object\Thread;
47 use Friendica\Protocol\Activity;
48 use Friendica\Util\Crypto;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\Profiler;
51 use Friendica\Util\Strings;
52 use Friendica\Util\Temporal;
53 use Psr\Log\LoggerInterface;
57 const MODE_COMMUNITY = 'community';
58 const MODE_CONTACTS = 'contacts';
59 const MODE_CONTACT_POSTS = 'contact-posts';
60 const MODE_DISPLAY = 'display';
61 const MODE_FILED = 'filed';
62 const MODE_NETWORK = 'network';
63 const MODE_NOTES = 'notes';
64 const MODE_SEARCH = 'search';
65 const MODE_PROFILE = 'profile';
73 /** @var LoggerInterface */
77 /** @var App\Arguments */
79 /** @var IManagePersonalConfigValues */
83 /** @var IManageConfigValues */
91 /** @var IHandleUserSessions */
94 public function __construct(LoggerInterface $logger, Profiler $profiler, Activity $activity, L10n $l10n, Item $item, Arguments $args, BaseURL $baseURL, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, App\Page $page, App\Mode $mode, App $app, IHandleUserSessions $session)
96 $this->activity = $activity;
98 $this->config = $config;
100 $this->baseURL = $baseURL;
101 $this->profiler = $profiler;
102 $this->logger = $logger;
105 $this->pConfig = $pConfig;
108 $this->session = $session;
112 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
114 * Increments the count of each matching activity and adds a link to the author as needed.
116 * @param array $activity
117 * @param array &$conv_responses (already created with builtin activity structure)
119 * @throws ImagickException
120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
122 public function builtinActivityPuller(array $activity, array &$conv_responses)
124 $thread_parent = $activity['thr-parent-row'] ?? [];
126 foreach ($conv_responses as $mode => $v) {
131 $verb = Activity::LIKE;
134 $verb = Activity::DISLIKE;
137 $verb = Activity::ATTEND;
140 $verb = Activity::ATTENDNO;
143 $verb = Activity::ATTENDMAYBE;
146 $verb = Activity::ANNOUNCE;
152 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
155 'id' => $activity['author-id'],
156 'network' => $activity['author-network'],
157 'url' => $activity['author-link']
159 $url = Contact::magicLinkByContact($author);
160 if (strpos($url, 'contact/redir/') === 0) {
161 $sparkle = ' class="sparkle" ';
164 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
166 if (empty($activity['thr-parent-id'])) {
167 $activity['thr-parent-id'] = $activity['parent-uri-id'];
170 // Skip when the causer of the parent is the same as the author of the announce
171 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
175 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
176 $conv_responses[$mode][$activity['thr-parent-id']] = [
180 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
181 // only list each unique author once
185 if ($this->session->getPublicContactId() == $activity['author-id']) {
186 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
189 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
191 // there can only be one activity verb per item so if we found anything, we can stop looking
198 * Returns the liker phrase based on a list of likers
200 * @param string $verb the activity verb
201 * @param array $likers a list of likers
203 * @return string the liker phrase
205 * @throws InternalServerErrorException in case either the verb is invalid or the list of likers is empty
207 private function getLikerPhrase(string $verb, array $likers): string
209 $total = count($likers);
212 throw new InternalServerErrorException(sprintf('There has to be at least one Liker for verb "%s"', $verb));
213 } else if ($total === 1) {
214 $likerString = $likers[0];
216 if ($total < $this->config->get('system', 'max_likers')) {
217 $likerString = implode(', ', array_slice($likers, 0, -1));
218 $likerString .= ' ' . $this->l10n->t('and') . ' ' . $likers[count($likers) - 1];
220 $likerString = implode(', ', array_slice($likers, 0, $this->config->get('system', 'max_likers') - 1));
221 $likerString .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
227 return $this->l10n->tt('%2$s likes this.', '%2$s like this.', $total, $likerString);
229 return $this->l10n->tt('%2$s doesn\'t like this.', '%2$s don\'t like this.', $total, $likerString);
231 return $this->l10n->tt('%2$s attends.', '%2$s attend.', $total, $likerString);
233 return $this->l10n->tt('%2$s doesn\'t attend.', '%2$s don\'t attend.', $total, $likerString);
235 return $this->l10n->tt('%2$s attends maybe.', '%2$s attend maybe.', $total, $likerString);
237 return $this->l10n->tt('%2$s reshared this.', '%2$s reshared this.', $total, $likerString);
239 throw new InternalServerErrorException(sprintf('Unknown verb "%s"', $verb));
244 * Format the activity text for an item/photo/video
246 * @param array $links = array of pre-linked names of actors
247 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
248 * @param int $id = item id
249 * @return string formatted text
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 public function formatActivity(array $links, string $verb, int $id): string
254 $this->profiler->startRecording('rendering');
257 $phrase = $this->getLikerPhrase($verb, $links);
258 $total = count($links);
261 $spanatts = "class=\"btn btn-link fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
262 $explikers = $phrase;
266 $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);
269 $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);
272 $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);
275 $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);
278 $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);
281 $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);
285 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
288 $output = Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
289 '$phrase' => $phrase,
293 $output .= $expanded;
295 $this->profiler->stopRecording();
299 public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
301 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
302 if (empty($user['uid'])) {
306 $this->profiler->startRecording('rendering');
309 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
310 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
311 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
312 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
313 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
314 $x['bang'] = $x['bang'] ?? '';
315 $x['visitor'] = $x['visitor'] ?? 'block';
316 $x['is_owner'] = $x['is_owner'] ?? true;
317 $x['profile_uid'] = $x['profile_uid'] ?? $this->session->getLocalUserId();
320 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
322 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
323 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
324 '$newpost' => 'true',
325 '$baseurl' => $this->baseURL,
326 '$geotag' => $geotag,
327 '$nickname' => $x['nickname'],
328 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
329 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
330 '$term' => $this->l10n->t('Tag term:'),
331 '$fileas' => $this->l10n->t('Save to Folder:'),
332 '$whereareu' => $this->l10n->t('Where are you right now?'),
333 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
334 '$is_mobile' => $this->mode->isMobile(),
338 Hook::callAll('jot_tool', $jotplugins);
340 if ($this->config->get('system', 'set_creation_date')) {
341 $created_at = Temporal::getDateTimeField(
342 new \DateTime(DBA::NULL_DATETIME),
343 new \DateTime('now'),
345 $this->l10n->t('Created at'),
352 $tpl = Renderer::getMarkupTemplate('jot.tpl');
354 $o .= Renderer::replaceMacros($tpl, [
355 '$new_post' => $this->l10n->t('New Post'),
356 '$return_path' => $this->args->getQueryString(),
358 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
359 '$loading' => $this->l10n->t('Loading...'),
360 '$upload' => $this->l10n->t('Upload photo'),
361 '$shortupload' => $this->l10n->t('upload photo'),
362 '$attach' => $this->l10n->t('Attach file'),
363 '$shortattach' => $this->l10n->t('attach file'),
364 '$edbold' => $this->l10n->t('Bold'),
365 '$editalic' => $this->l10n->t('Italic'),
366 '$eduline' => $this->l10n->t('Underline'),
367 '$edquote' => $this->l10n->t('Quote'),
368 '$edemojis' => $this->l10n->t('Add emojis'),
369 '$edcode' => $this->l10n->t('Code'),
370 '$edimg' => $this->l10n->t('Image'),
371 '$edurl' => $this->l10n->t('Link'),
372 '$edattach' => $this->l10n->t('Link or Media'),
373 '$edvideo' => $this->l10n->t('Video'),
374 '$setloc' => $this->l10n->t('Set your location'),
375 '$shortsetloc' => $this->l10n->t('set location'),
376 '$noloc' => $this->l10n->t('Clear browser location'),
377 '$shortnoloc' => $this->l10n->t('clear location'),
378 '$title' => $x['title'] ?? '',
379 '$placeholdertitle' => $this->l10n->t('Set title'),
380 '$category' => $x['category'] ?? '',
381 '$placeholdercategory' => Feature::isEnabled($this->session->getLocalUserId(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
382 '$scheduled_at' => Temporal::getDateTimeField(
384 new \DateTime('now + 6 months'),
386 $this->l10n->t('Scheduled at'),
389 '$created_at' => $created_at,
390 '$wait' => $this->l10n->t('Please wait'),
391 '$permset' => $this->l10n->t('Permission settings'),
392 '$shortpermset' => $this->l10n->t('Permissions'),
393 '$wall' => $notes_cid ? 0 : 1,
394 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
395 '$content' => $x['content'] ?? '',
396 '$post_id' => $x['post_id'] ?? '',
397 '$baseurl' => $this->baseURL,
398 '$defloc' => $x['default_location'],
399 '$visitor' => $x['visitor'],
400 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
401 '$public' => $this->l10n->t('Public post'),
402 '$lockstate' => $x['lockstate'],
403 '$bang' => $x['bang'],
404 '$profile_uid' => $x['profile_uid'],
405 '$preview' => $this->l10n->t('Preview'),
406 '$jotplugins' => $jotplugins,
407 '$notes_cid' => $notes_cid,
408 '$cancel' => $this->l10n->t('Cancel'),
409 '$rand_num' => Crypto::randomDigits(12),
411 // ACL permissions box
414 //jot nav tab (used in some themes)
415 '$message' => $this->l10n->t('Message'),
416 '$browser' => $this->l10n->t('Browser'),
418 '$compose_link_title' => $this->l10n->t('Open Compose page'),
419 '$always_open_compose' => $this->pConfig->get($this->session->getLocalUserId(), 'frio', 'always_open_compose', false),
423 if ($popup == true) {
424 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
427 $this->profiler->stopRecording();
432 * "Render" a conversation or list of items for HTML display.
433 * There are two major forms of display:
434 * - Sequential or unthreaded ("New Item View" or search results)
435 * - conversation view
436 * The $mode parameter decides between the various renderings and also
437 * figures out how to determine page owner and other contextual items
438 * that are based on unique features of the calling module.
439 * @param array $items
440 * @param string $mode
441 * @param $update @TODO Which type?
442 * @param bool $preview
443 * @param string $order
446 * @throws ImagickException
447 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
449 public function create(array $items, string $mode, $update, bool $preview = false, string $order = 'commented', int $uid = 0): string
451 $this->profiler->startRecording('rendering');
453 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
454 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
455 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
456 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
458 $live_update_div = '';
460 $blocklist = $this->getBlocklist();
462 $previewing = (($preview) ? ' preview ' : '');
464 if ($mode === self::MODE_NETWORK) {
465 $items = $this->addChildren($items, false, $order, $uid, $mode);
468 * The special div is needed for liveUpdate to kick in for this page.
469 * We only launch liveUpdate if you aren't filtering in some incompatible
470 * way and also you aren't writing a comment (discovered in javascript).
472 $live_update_div = '<div id="live-network"></div>' . "\r\n"
473 . "<script> var profile_uid = " . $_SESSION['uid']
474 . "; var netargs = '" . substr($this->args->getCommand(), 8)
476 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
477 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
478 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
479 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
480 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
481 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
482 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
483 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
484 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
485 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
486 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
488 . "'; </script>\r\n";
490 } elseif ($mode === self::MODE_PROFILE) {
491 $items = $this->addChildren($items, false, $order, $uid, $mode);
494 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
496 if ($tab === 'posts') {
498 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
499 * because browser prefetching might change it on us. We have to deliver it with the page.
502 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
503 . "<script> var profile_uid = " . $uid
504 . "; var netargs = '?f='; </script>\r\n";
507 } elseif ($mode === self::MODE_NOTES) {
508 $items = $this->addChildren($items, false, $order, $this->session->getLocalUserId(), $mode);
511 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
512 . "<script> var profile_uid = " . $this->session->getLocalUserId()
513 . "; var netargs = '?f='; </script>\r\n";
515 } elseif ($mode === self::MODE_DISPLAY) {
516 $items = $this->addChildren($items, false, $order, $uid, $mode);
519 $live_update_div = '<div id="live-display"></div>' . "\r\n"
520 . "<script> var profile_uid = " . ($this->session->getLocalUserId() ?: 0) . ";"
523 } elseif ($mode === self::MODE_COMMUNITY) {
524 $items = $this->addChildren($items, true, $order, $uid, $mode);
527 $live_update_div = '<div id="live-community"></div>' . "\r\n"
528 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
530 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
531 . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
532 . "'; </script>\r\n";
534 } elseif ($mode === self::MODE_CONTACTS) {
535 $items = $this->addChildren($items, false, $order, $uid, $mode);
538 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
539 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
540 ."?f='; </script>\r\n";
542 } elseif ($mode === self::MODE_SEARCH) {
543 $live_update_div = '<div id="live-search"></div>' . "\r\n";
546 $page_dropping = $this->session->getLocalUserId() && $this->session->getLocalUserId() == $uid && $mode != self::MODE_SEARCH;
549 $_SESSION['return_path'] = $this->args->getQueryString();
552 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
553 Hook::callAll('conversation_start', $cb);
555 $items = $cb['items'];
566 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
567 unset($conv_responses['dislike']);
570 // array with html for each thread (parent+comments)
574 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
575 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
577 if (!empty($items)) {
578 if (in_array($mode, [self::MODE_COMMUNITY, self::MODE_CONTACTS, self::MODE_PROFILE])) {
581 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
584 if (!$this->session->getLocalUserId()) {
588 if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
591 * "New Item View" on network page or search page results
592 * - just loop through the items and format them minimally for display
595 $tpl = 'search_item.tpl';
599 foreach ($items as $item) {
600 if (in_array($item['uri-id'], $uriids)) {
604 $uriids[] = $item['uri-id'];
606 if (!$this->item->isVisibleActivity($item)) {
610 if (in_array($item['author-id'], $blocklist)) {
616 // prevent private email from leaking.
617 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
621 $profile_name = $item['author-name'];
622 if (!empty($item['author-link']) && empty($item['author-name'])) {
623 $profile_name = $item['author-link'];
626 $tags = Tag::populateFromItem($item);
628 $author = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
629 $profile_link = Contact::magicLinkByContact($author);
632 if (strpos($profile_link, 'contact/redir/') === 0) {
633 $sparkle = ' sparkle';
636 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
637 Hook::callAll('render_location', $locate);
638 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
640 $this->item->localize($item);
641 if ($mode === self::MODE_FILED) {
648 'dropping' => $dropping,
649 'pagedrop' => $page_dropping,
650 'select' => $this->l10n->t('Select'),
651 'delete' => $this->l10n->t('Delete'),
661 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
662 unset($likebuttons['dislike']);
665 $body_html = ItemModel::prepareBody($item, true, $preview);
667 [$categories, $folders] = $this->item->determineCategoriesTerms($item, $this->session->getLocalUserId());
669 if (!empty($item['title'])) {
670 $title = $item['title'];
671 } elseif (!empty($item['content-warning']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'disable_cw', false)) {
672 $title = ucfirst($item['content-warning']);
677 if (!empty($item['featured'])) {
678 $pinned = $this->l10n->t('Pinned item');
685 'id' => ($preview ? 'P0' : $item['id']),
686 'guid' => ($preview ? 'Q0' : $item['guid']),
687 'commented' => $item['commented'],
688 'received' => $item['received'],
689 'created_date' => $item['created'],
690 'uriid' => $item['uri-id'],
691 'network' => $item['network'],
692 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
693 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
694 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
695 'profile_url' => $profile_link,
696 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
697 'name' => $profile_name,
698 'sparkle' => $sparkle,
700 'thumb' => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
702 'body_html' => $body_html,
703 'tags' => $tags['tags'],
704 'hashtags' => $tags['hashtags'],
705 'mentions' => $tags['mentions'],
706 'implicit_mentions' => $tags['implicit_mentions'],
707 'txt_cats' => $this->l10n->t('Categories:'),
708 'txt_folders' => $this->l10n->t('Filed under:'),
709 'has_cats' => ((count($categories)) ? 'true' : ''),
710 'has_folders' => ((count($folders)) ? 'true' : ''),
711 'categories' => $categories,
712 'folders' => $folders,
713 'text' => strip_tags($body_html),
714 'localtime' => DateTimeFormat::local($item['created'], 'r'),
715 'utc' => DateTimeFormat::utc($item['created'], 'c'),
716 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
717 'location_html' => $location_html,
721 'owner_photo' => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
722 'plink' => ItemModel::getPlink($item),
725 'isstarred' => 'unstarred',
728 'vote' => $likebuttons,
730 'dislike_html ' => '',
731 'comment_html' => '',
732 'conv' => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
733 'previewing' => $previewing,
734 'wait' => $this->l10n->t('Please wait'),
738 $arr = ['item' => $item, 'output' => $tmp_item];
739 Hook::callAll('display_item', $arr);
741 $threads[$threadsid]['id'] = $item['id'];
742 $threads[$threadsid]['network'] = $item['network'];
743 $threads[$threadsid]['items'] = [$arr['output']];
747 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
749 $conv = new Thread($mode, $preview, $writable);
752 * get all the topmost parents
753 * this shouldn't be needed, as we should have only them in our array
754 * But for now, this array respects the old style, just in case
756 foreach ($items as $item) {
757 if (in_array($item['author-id'], $blocklist)) {
761 // Can we put this after the visibility check?
762 $this->builtinActivityPuller($item, $conv_responses);
764 // Only add what is visible
765 if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
769 if (!$this->item->isVisibleActivity($item)) {
773 /// @todo Check if this call is needed or not
774 $arr = ['item' => $item];
775 Hook::callAll('display_item', $arr);
777 $item['pagedrop'] = $page_dropping;
779 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
780 $item_object = new PostObject($item);
781 $conv->addParent($item_object);
785 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
787 $this->logger->info('[ERROR] conversation : Failed to get template data.');
793 $o = Renderer::replaceMacros($page_template, [
794 '$baseurl' => $this->baseURL,
795 '$return_path' => $this->args->getQueryString(),
796 '$live_update' => $live_update_div,
797 '$remove' => $this->l10n->t('remove'),
799 '$update' => $update,
800 '$threads' => $threads,
801 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
804 $this->profiler->stopRecording();
808 private function getBlocklist(): array
810 if (!$this->session->getLocalUserId()) {
814 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get($this->session->getLocalUserId(), 'system', 'blocked') ?? '');
815 if (empty($str_blocked)) {
821 foreach (explode(',', $str_blocked) as $entry) {
822 $cid = Contact::getIdForURL(trim($entry), 0, false);
832 * Adds some information (Causer, post reason, direction) to the fetched post row.
834 * @param array $row Post row
835 * @param array $activity Contact data of the resharer
836 * @param array $thr_parent Thread parent row
838 * @return array items with parents and comments
840 private function addRowInformation(array $row, array $activity, array $thr_parent): array
842 $this->profiler->startRecording('rendering');
844 if (!$row['writable']) {
845 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
848 if (!empty($activity)) {
849 if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
850 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
852 $row = array_merge($row, $activity);
853 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
855 $row['causer-link'] = $contact['url'];
856 $row['causer-avatar'] = $contact['thumb'];
857 $row['causer-name'] = $contact['name'];
858 } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
859 ($row['author-id'] == $activity['causer-id'])) {
864 switch ($row['post-reason']) {
865 case ItemModel::PR_TO:
866 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
868 case ItemModel::PR_CC:
869 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
871 case ItemModel::PR_BTO:
872 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
874 case ItemModel::PR_BCC:
875 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
877 case ItemModel::PR_AUDIENCE:
878 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'audience')];
880 case ItemModel::PR_FOLLOWER:
881 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
883 case ItemModel::PR_TAG:
884 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
886 case ItemModel::PR_ANNOUNCEMENT:
887 if (!empty($row['causer-id']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'display_resharer')) {
888 $row['owner-id'] = $row['causer-id'];
889 $row['owner-link'] = $row['causer-link'];
890 $row['owner-avatar'] = $row['causer-avatar'];
891 $row['owner-name'] = $row['causer-name'];
894 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
895 $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
897 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
899 $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']))];
901 case ItemModel::PR_COMMENT:
902 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
904 case ItemModel::PR_STORED:
905 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
907 case ItemModel::PR_GLOBAL:
908 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
910 case ItemModel::PR_RELAY:
911 $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']))];
913 case ItemModel::PR_FETCHED:
914 $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']))];
916 case ItemModel::PR_COMPLETION:
917 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
919 case ItemModel::PR_DIRECT:
920 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
922 case ItemModel::PR_ACTIVITY:
923 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
925 case ItemModel::PR_DISTRIBUTE:
926 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
928 case ItemModel::PR_PUSHED:
929 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
933 $row['thr-parent-row'] = $thr_parent;
935 $this->profiler->stopRecording();
940 * Add comments to top level entries that had been fetched before
942 * The system will fetch the comments for the local user whenever possible.
943 * This behaviour is currently needed to allow commenting on Friendica posts.
945 * @param array $parents Parent items
946 * @param bool $block_authors
949 * @param string $mode
950 * @return array items with parents and comments
951 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953 private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode): array
955 $this->profiler->startRecording('rendering');
956 if (count($parents) > 1) {
957 $max_comments = $this->config->get('system', 'max_comments', 100);
959 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
964 $commentcounter = [];
965 $activitycounter = [];
967 foreach ($parents as $parent) {
968 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
969 $uriid = $parent['thr-parent-id'];
970 if (!empty($parent['author-id'])) {
971 $activities[$uriid] = ['causer-id' => $parent['author-id']];
972 foreach (['commented', 'received', 'created'] as $orderfields) {
973 if (!empty($parent[$orderfields])) {
974 $activities[$uriid][$orderfields] = $parent[$orderfields];
979 $uriid = $parent['uri-id'];
983 $commentcounter[$uriid] = 0;
984 $activitycounter[$uriid] = 0;
987 $condition = ['parent-uri-id' => $uriids];
988 if ($block_authors) {
989 $condition['author-hidden'] = false;
992 if ($this->config->get('system', 'emoji_activities')) {
993 $emojis = $this->getEmojis($uriids);
994 $condition = DBA::mergeConditions($condition, ["(`gravity` != ? OR `origin`)", ItemModel::GRAVITY_ACTIVITY]);
997 $condition = DBA::mergeConditions($condition,
998 ["`uid` IN (0, ?) AND (NOT `vid` IN (?, ?, ?) OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW), Verb::getID(Activity::VIEW), Verb::getID(Activity::READ)]);
1000 $condition = DBA::mergeConditions($condition, ["(`uid` != ? OR `private` != ?)", 0, ItemModel::PRIVATE]);
1002 $condition = DBA::mergeConditions($condition,
1003 ["`visible` AND NOT `deleted` AND NOT `author-blocked` AND NOT `owner-blocked`
1004 AND ((NOT `contact-pending` AND (`contact-rel` IN (?, ?))) OR `self` OR `contact-uid` = ?)",
1005 Contact::SHARING, Contact::FRIEND, 0]);
1007 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
1011 while ($row = Post::fetch($thread_parents)) {
1012 $thr_parent[$row['uri-id']] = $row;
1014 DBA::close($thread_parents);
1016 $params = ['order' => ['uri-id' => true, 'uid' => true]];
1018 $thread_items = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
1021 $quote_uri_ids = [];
1024 while ($row = Post::fetch($thread_items)) {
1025 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
1029 if (($mode != self::MODE_CONTACTS) && !$row['origin']) {
1030 $row['featured'] = false;
1033 if ($max_comments > 0) {
1034 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
1037 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
1042 $authors[] = $row['author-id'];
1043 $authors[] = $row['owner-id'];
1045 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT])) {
1046 $quote_uri_ids[$row['uri-id']] = [
1047 'uri-id' => $row['uri-id'],
1048 'uri' => $row['uri'],
1049 'parent-uri-id' => $row['parent-uri-id'],
1050 'parent-uri' => $row['parent-uri'],
1054 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
1057 DBA::close($thread_items);
1059 $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]);
1060 while ($quote = Post::fetch($quotes)) {
1064 $row['verb'] = $row['body'] = $row['raw-body'] = Activity::ANNOUNCE;
1065 $row['gravity'] = ItemModel::GRAVITY_ACTIVITY;
1066 $row['object-type'] = Activity\ObjectType::NOTE;
1067 $row['parent-uri'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri'];
1068 $row['parent-uri-id'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri-id'];
1069 $row['thr-parent'] = $quote_uri_ids[$quote['quote-uri-id']]['uri'];
1070 $row['thr-parent-id'] = $quote_uri_ids[$quote['quote-uri-id']]['uri-id'];
1072 $authors[] = $row['author-id'];
1073 $authors[] = $row['owner-id'];
1075 $items[$row['uri-id']] = $this->addRowInformation($row, [], []);
1077 DBA::close($quotes);
1079 $authors = array_unique($authors);
1084 if (!empty($authors)) {
1085 $usercontacts = DBA::select('user-contact', ['cid', 'blocked', 'ignored', 'collapsed'], ['uid' => $uid, 'cid' => $authors]);
1086 while ($usercontact = DBA::fetch($usercontacts)) {
1087 if ($usercontact['blocked']) {
1088 $blocks[] = $usercontact['cid'];
1090 if ($usercontact['ignored']) {
1091 $ignores[] = $usercontact['cid'];
1093 if ($usercontact['collapsed']) {
1094 $collapses[] = $usercontact['cid'];
1097 DBA::close($usercontacts);
1100 foreach ($items as $key => $row) {
1101 $items[$key]['emojis'] = $emojis[$key] ?? [];
1103 $always_display = in_array($mode, [self::MODE_CONTACTS, self::MODE_CONTACT_POSTS]);
1105 $items[$key]['user-blocked-author'] = !$always_display && in_array($row['author-id'], $blocks);
1106 $items[$key]['user-ignored-author'] = !$always_display && in_array($row['author-id'], $ignores);
1107 $items[$key]['user-blocked-owner'] = !$always_display && in_array($row['owner-id'], $blocks);
1108 $items[$key]['user-ignored-owner'] = !$always_display && in_array($row['owner-id'], $ignores);
1109 $items[$key]['user-collapsed-author'] = !$always_display && in_array($row['author-id'], $collapses);
1110 $items[$key]['user-collapsed-owner'] = !$always_display && in_array($row['owner-id'], $collapses);
1112 if (in_array($mode, [self::MODE_COMMUNITY, self::MODE_NETWORK]) &&
1113 (in_array($row['author-id'], $blocks) || in_array($row['owner-id'], $blocks) || in_array($row['author-id'], $ignores) || in_array($row['owner-id'], $ignores))) {
1114 unset($items[$key]);
1118 $items = $this->convSort($items, $order);
1120 $this->profiler->stopRecording();
1125 * Fetch emoji reaction from the conversation
1127 * @param array $uriids
1130 private function getEmojis(array $uriids): array
1133 Activity::LIKE => '👍',
1134 Activity::DISLIKE => '👎',
1135 Activity::ATTEND => '✔️',
1136 Activity::ATTENDMAYBE => '❓',
1137 Activity::ATTENDNO => '❌',
1138 Activity::ANNOUNCE => '♻',
1139 Activity::VIEW => '📺',
1142 $index_list = array_values($activity_emoji);
1143 $verbs = array_merge(array_keys($activity_emoji), [Activity::EMOJIREACT]);
1145 $condition = DBA::mergeConditions(['parent-uri-id' => $uriids, 'gravity' => ItemModel::GRAVITY_ACTIVITY, 'verb' => $verbs], ["NOT `deleted`"]);
1146 $separator = chr(255) . chr(255) . chr(255);
1148 $sql = "SELECT `thr-parent-id`, `body`, `verb`, COUNT(*) AS `total`, GROUP_CONCAT(REPLACE(`author-name`, '" . $separator . "', ' ') SEPARATOR '". $separator ."' LIMIT 50) AS `title` FROM `post-view` WHERE " . array_shift($condition) . " GROUP BY `thr-parent-id`, `verb`, `body`";
1152 $rows = DBA::p($sql, $condition);
1153 while ($row = DBA::fetch($rows)) {
1154 $row['verb'] = $row['body'] ? Activity::EMOJIREACT : $row['verb'];
1155 $emoji = $row['body'] ?: $activity_emoji[$row['verb']];
1156 if (!isset($index_list[$emoji])) {
1157 $index_list[] = $emoji;
1159 $index = array_search($emoji, $index_list);
1161 $emojis[$row['thr-parent-id']][$index]['emoji'] = $emoji;
1162 $emojis[$row['thr-parent-id']][$index]['verb'] = $row['verb'];
1163 $emojis[$row['thr-parent-id']][$index]['total'] = ($emojis[$row['thr-parent-id']][$index]['total'] ?? 0) + $row['total'];
1164 $emojis[$row['thr-parent-id']][$index]['title'] = array_unique(array_merge($emojis[$row['thr-parent-id']][$index]['title'] ?? [], explode($separator, $row['title'])));
1172 * Plucks the children of the given parent from a given item list.
1174 * @param array $item_list
1175 * @param array $parent
1176 * @param bool $recursive
1179 private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1181 $this->profiler->startRecording('rendering');
1183 foreach ($item_list as $i => $item) {
1184 if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1186 // Fallback to parent-uri if thr-parent is not set
1187 $thr_parent = $item['thr-parent-id'];
1188 if ($thr_parent == '') {
1189 $thr_parent = $item['parent-uri-id'];
1192 if ($thr_parent == $parent['uri-id']) {
1193 $item['children'] = $this->getItemChildren($item_list, $item);
1195 $children[] = $item;
1196 unset($item_list[$i]);
1198 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1199 $children[] = $item;
1200 unset($item_list[$i]);
1204 $this->profiler->stopRecording();
1209 * Recursively sorts a tree-like item array
1211 * @param array $items
1214 private function sortItemChildren(array $items): array
1216 $this->profiler->startRecording('rendering');
1218 usort($result, [$this, 'sortThrReceivedRev']);
1219 foreach ($result as $k => $i) {
1220 if (isset($result[$k]['children'])) {
1221 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1224 $this->profiler->stopRecording();
1229 * Recursively add all children items at the top level of a list
1231 * @param array $children List of items to append
1232 * @param array $item_list
1234 private function addChildrenToList(array $children, array &$item_list)
1236 foreach ($children as $child) {
1237 $item_list[] = $child;
1238 if (isset($child['children'])) {
1239 $this->addChildrenToList($child['children'], $item_list);
1245 * Selectively flattens a tree-like item structure to prevent threading stairs
1247 * This recursive function takes the item tree structure created by conv_sort() and
1248 * flatten the extraneous depth levels when people reply sequentially, removing the
1249 * stairs effect in threaded conversations limiting the available content width.
1251 * The basic principle is the following: if a post item has only one reply and is
1252 * the last reply of its parent, then the reply is moved to the parent.
1254 * This process is rendered somewhat more complicated because items can be either
1255 * replies or likes, and these don't factor at all in the reply count/last reply.
1257 * @param array $parent A tree-like array of items
1260 private function smartFlattenConversation(array $parent): array
1262 $this->profiler->startRecording('rendering');
1263 if (!isset($parent['children']) || count($parent['children']) == 0) {
1264 $this->profiler->stopRecording();
1268 // We use a for loop to ensure we process the newly-moved items
1269 for ($i = 0; $i < count($parent['children']); $i++) {
1270 $child = $parent['children'][$i];
1272 if (isset($child['children']) && count($child['children'])) {
1273 // This helps counting only the regular posts
1274 $count_post_closure = function ($var) {
1275 $this->profiler->stopRecording();
1276 return $var['verb'] === Activity::POST;
1279 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1281 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1283 // If there's only one child's children post and this is the last child post
1284 if ($child_post_count == 1 && $remaining_post_count == 1) {
1286 // Searches the post item in the children
1288 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1292 $moved_item = $child['children'][$j];
1293 unset($parent['children'][$i]['children'][$j]);
1294 $parent['children'][] = $moved_item;
1296 $parent['children'][$i] = $this->smartFlattenConversation($child);
1301 $this->profiler->stopRecording();
1306 * Expands a flat list of items into corresponding tree-like conversation structures.
1308 * sort the top-level posts either on "received" or "commented", and finally
1309 * append all the items at the top level (???)
1311 * @param array $item_list A list of items belonging to one or more conversations
1312 * @param string $order Either on "received" or "commented"
1314 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1316 private function convSort(array $item_list, string $order): array
1318 $this->profiler->startRecording('rendering');
1321 if (!(is_array($item_list) && count($item_list))) {
1322 $this->profiler->stopRecording();
1326 $blocklist = $this->getBlocklist();
1330 // Dedupes the item list on the uri to prevent infinite loops
1331 foreach ($item_list as $item) {
1332 if (in_array($item['author-id'], $blocklist)) {
1336 $item_array[$item['uri-id']] = $item;
1339 // Extract the top level items
1340 foreach ($item_array as $item) {
1341 if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1346 if (stristr($order, 'pinned_received')) {
1347 usort($parents, [$this, 'sortThrFeaturedReceived']);
1348 } elseif (stristr($order, 'pinned_commented')) {
1349 usort($parents, [$this, 'sortThrFeaturedCommented']);
1350 } elseif (stristr($order, 'received')) {
1351 usort($parents, [$this, 'sortThrReceived']);
1352 } elseif (stristr($order, 'commented')) {
1353 usort($parents, [$this, 'sortThrCommented']);
1354 } elseif (stristr($order, 'created')) {
1355 usort($parents, [$this, 'sortThrCreated']);
1359 * Plucks children from the item_array, second pass collects eventual orphan
1360 * items and add them as children of their top-level post.
1362 foreach ($parents as $i => $parent) {
1363 $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1364 $this->getItemChildren($item_array, $parent, false));
1367 foreach ($parents as $i => $parent) {
1368 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1371 if (!$this->pConfig->get($this->session->getLocalUserId(), 'system', 'no_smart_threading', 0)) {
1372 foreach ($parents as $i => $parent) {
1373 $parents[$i] = $this->smartFlattenConversation($parent);
1377 /// @TODO: Stop recursively adding all children back to the top level (!!!)
1378 /// However, this apparently ensures responses (likes, attendance) display (?!)
1379 foreach ($parents as $parent) {
1380 if (count($parent['children'])) {
1381 $this->addChildrenToList($parent['children'], $parents);
1385 $this->profiler->stopRecording();
1390 * usort() callback to sort item arrays by featured and the received key
1396 private function sortThrFeaturedReceived(array $a, array $b): int
1398 if ($b['featured'] && !$a['featured']) {
1400 } elseif (!$b['featured'] && $a['featured']) {
1404 return strcmp($b['received'], $a['received']);
1408 * usort() callback to sort item arrays by featured and the received key
1414 private function sortThrFeaturedCommented(array $a, array $b): int
1416 if ($b['featured'] && !$a['featured']) {
1418 } elseif (!$b['featured'] && $a['featured']) {
1422 return strcmp($b['commented'], $a['commented']);
1426 * usort() callback to sort item arrays by the received key
1432 private function sortThrReceived(array $a, array $b): int
1434 return strcmp($b['received'], $a['received']);
1438 * usort() callback to reverse sort item arrays by the received key
1444 private function sortThrReceivedRev(array $a, array $b): int
1446 return strcmp($a['received'], $b['received']);
1450 * usort() callback to sort item arrays by the commented key
1456 private function sortThrCommented(array $a, array $b): int
1458 return strcmp($b['commented'], $a['commented']);
1462 * usort() callback to sort item arrays by the created key
1468 private function sortThrCreated(array $a, array $b): int
1470 return strcmp($b['created'], $a['created']);