]> git.mxchange.org Git - friendica.git/blob - src/Content/Conversation.php
Merge pull request #12029 from annando/warning
[friendica.git] / src / Content / Conversation.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Content;
23
24 use Friendica\App;
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\Theme;
36 use Friendica\Database\DBA;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Item as ItemModel;
39 use Friendica\Model\Post;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Model\Verb;
43 use Friendica\Object\Post as PostObject;
44 use Friendica\Object\Thread;
45 use Friendica\Protocol\Activity;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Profiler;
49 use Friendica\Util\Strings;
50 use Friendica\Util\Temporal;
51 use Psr\Log\LoggerInterface;
52
53 class Conversation
54 {
55         /** @var Activity */
56         private $activity;
57         /** @var L10n */
58         private $l10n;
59         /** @var Profiler */
60         private $profiler;
61         /** @var LoggerInterface */
62         private $logger;
63         /** @var Item */
64         private $item;
65         /** @var App\Arguments */
66         private $args;
67         /** @var IManagePersonalConfigValues */
68         private $pConfig;
69         /** @var BaseURL */
70         private $baseURL;
71         /** @var IManageConfigValues */
72         private $config;
73         /** @var App */
74         private $app;
75         /** @var App\Page */
76         private $page;
77         /** @var App\Mode */
78         private $mode;
79         /** @var Session\Capability\IHandleSessions */
80         private $session;
81
82         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, Session\Capability\IHandleSessions $session)
83         {
84                 $this->activity = $activity;
85                 $this->item     = $item;
86                 $this->config   = $config;
87                 $this->mode     = $mode;
88                 $this->baseURL  = $baseURL;
89                 $this->profiler = $profiler;
90                 $this->logger   = $logger;
91                 $this->l10n     = $l10n;
92                 $this->args     = $args;
93                 $this->pConfig  = $pConfig;
94                 $this->page     = $page;
95                 $this->app      = $app;
96                 $this->session  = $session;
97         }
98
99         /**
100          * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
101          *
102          * Increments the count of each matching activity and adds a link to the author as needed.
103          *
104          * @param array  $activity
105          * @param array &$conv_responses (already created with builtin activity structure)
106          * @return void
107          * @throws ImagickException
108          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
109          */
110         public function builtinActivityPuller(array $activity, array &$conv_responses)
111         {
112                 $thread_parent = $activity['thr-parent-row'] ?? [];
113
114                 foreach ($conv_responses as $mode => $v) {
115                         $sparkle = '';
116
117                         switch ($mode) {
118                                 case 'like':
119                                         $verb = Activity::LIKE;
120                                         break;
121                                 case 'dislike':
122                                         $verb = Activity::DISLIKE;
123                                         break;
124                                 case 'attendyes':
125                                         $verb = Activity::ATTEND;
126                                         break;
127                                 case 'attendno':
128                                         $verb = Activity::ATTENDNO;
129                                         break;
130                                 case 'attendmaybe':
131                                         $verb = Activity::ATTENDMAYBE;
132                                         break;
133                                 case 'announce':
134                                         $verb = Activity::ANNOUNCE;
135                                         break;
136                                 default:
137                                         return;
138                         }
139
140                         if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
141                                 $author = [
142                                         'uid'     => 0,
143                                         'id'      => $activity['author-id'],
144                                         'network' => $activity['author-network'],
145                                         'url'     => $activity['author-link']
146                                 ];
147                                 $url = Contact::magicLinkByContact($author);
148                                 if (strpos($url, 'redir/') === 0) {
149                                         $sparkle = ' class="sparkle" ';
150                                 }
151
152                                 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
153
154                                 if (empty($activity['thr-parent-id'])) {
155                                         $activity['thr-parent-id'] = $activity['parent-uri-id'];
156                                 }
157
158                                 // Skip when the causer of the parent is the same as the author of the announce
159                                 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
160                                         continue;
161                                 }
162
163                                 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
164                                         $conv_responses[$mode][$activity['thr-parent-id']] = [
165                                                 'links' => [],
166                                                 'self'  => 0,
167                                         ];
168                                 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
169                                         // only list each unique author once
170                                         continue;
171                                 }
172
173                                 if (public_contact() == $activity['author-id']) {
174                                         $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
175                                 }
176
177                                 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
178
179                                 // there can only be one activity verb per item so if we found anything, we can stop looking
180                                 return;
181                         }
182                 }
183         }
184
185         /**
186          * Format the activity text for an item/photo/video
187          *
188          * @param array  $links = array of pre-linked names of actors
189          * @param string $verb  = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
190          * @param int    $id    = item id
191          * @return string formatted text
192          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193          */
194         public function formatActivity(array $links, string $verb, int $id): string
195         {
196                 $this->profiler->startRecording('rendering');
197                 $o        = '';
198                 $expanded = '';
199                 $phrase   = '';
200
201                 $total = count($links);
202                 if ($total == 1) {
203                         $likers = $links[0];
204
205                         // Phrase if there is only one liker. In other cases it will be uses for the expanded
206                         // list which show all likers
207                         switch ($verb) {
208                                 case 'like':
209                                         $phrase = $this->l10n->t('%s likes this.', $likers);
210                                         break;
211                                 case 'dislike':
212                                         $phrase = $this->l10n->t('%s doesn\'t like this.', $likers);
213                                         break;
214                                 case 'attendyes':
215                                         $phrase = $this->l10n->t('%s attends.', $likers);
216                                         break;
217                                 case 'attendno':
218                                         $phrase = $this->l10n->t('%s doesn\'t attend.', $likers);
219                                         break;
220                                 case 'attendmaybe':
221                                         $phrase = $this->l10n->t('%s attends maybe.', $likers);
222                                         break;
223                                 case 'announce':
224                                         $phrase = $this->l10n->t('%s reshared this.', $likers);
225                                         break;
226                         }
227                 } elseif ($total > 1) {
228                         if ($total < $this->config->get('system', 'max_likers')) {
229                                 $likers = implode(', ', array_slice($links, 0, -1));
230                                 $likers .= ' ' . $this->l10n->t('and') . ' ' . $links[count($links) - 1];
231                         } else {
232                                 $likers = implode(', ', array_slice($links, 0, $this->config->get('system', 'max_likers') - 1));
233                                 $likers .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
234                         }
235
236                         $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
237
238                         $explikers = '';
239                         switch ($verb) {
240                                 case 'like':
241                                         $phrase    = $this->l10n->t('<span  %1$s>%2$d people</span> like this', $spanatts, $total);
242                                         $explikers = $this->l10n->t('%s like this.', $likers);
243                                         break;
244                                 case 'dislike':
245                                         $phrase    = $this->l10n->t('<span  %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
246                                         $explikers = $this->l10n->t('%s don\'t like this.', $likers);
247                                         break;
248                                 case 'attendyes':
249                                         $phrase    = $this->l10n->t('<span  %1$s>%2$d people</span> attend', $spanatts, $total);
250                                         $explikers = $this->l10n->t('%s attend.', $likers);
251                                         break;
252                                 case 'attendno':
253                                         $phrase    = $this->l10n->t('<span  %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
254                                         $explikers = $this->l10n->t('%s don\'t attend.', $likers);
255                                         break;
256                                 case 'attendmaybe':
257                                         $phrase    = $this->l10n->t('<span  %1$s>%2$d people</span> attend maybe', $spanatts, $total);
258                                         $explikers = $this->l10n->t('%s attend maybe.', $likers);
259                                         break;
260                                 case 'announce':
261                                         $phrase    = $this->l10n->t('<span  %1$s>%2$d people</span> reshared this', $spanatts, $total);
262                                         $explikers = $this->l10n->t('%s reshared this.', $likers);
263                                         break;
264                         }
265
266                         $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
267                 }
268
269                 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
270                         '$phrase' => $phrase,
271                         '$type'   => $verb,
272                         '$id'     => $id
273                 ]);
274                 $o .= $expanded;
275
276                 $this->profiler->stopRecording();
277                 return $o;
278         }
279
280         public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
281         {
282                 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
283                 if (empty($user['uid'])) {
284                         return '';
285                 }
286
287                 $this->profiler->startRecording('rendering');
288                 $o = '';
289
290                 $x['allow_location']   = $x['allow_location']   ?? $user['allow_location'];
291                 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
292                 $x['nickname']         = $x['nickname']         ?? $user['nickname'];
293                 $x['lockstate']        = $x['lockstate']        ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
294                 $x['acl']              = $x['acl']              ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
295                 $x['bang']             = $x['bang']             ?? '';
296                 $x['visitor']          = $x['visitor']          ?? 'block';
297                 $x['is_owner']         = $x['is_owner']         ?? true;
298                 $x['profile_uid']      = $x['profile_uid']      ?? local_user();
299
300
301                 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
302
303                 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
304                 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
305                         '$newpost'   => 'true',
306                         '$baseurl'   => $this->baseURL->get(true),
307                         '$geotag'    => $geotag,
308                         '$nickname'  => $x['nickname'],
309                         '$ispublic'  => $this->l10n->t('Visible to <strong>everybody</strong>'),
310                         '$linkurl'   => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
311                         '$term'      => $this->l10n->t('Tag term:'),
312                         '$fileas'    => $this->l10n->t('Save to Folder:'),
313                         '$whereareu' => $this->l10n->t('Where are you right now?'),
314                         '$delitems'  => $this->l10n->t("Delete item\x28s\x29?"),
315                         '$is_mobile' => $this->mode->isMobile(),
316                 ]);
317
318                 $jotplugins = '';
319                 Hook::callAll('jot_tool', $jotplugins);
320
321                 if ($this->config->get('system', 'set_creation_date')) {
322                         $created_at = Temporal::getDateTimeField(
323                                 new \DateTime(DBA::NULL_DATETIME),
324                                 new \DateTime('now'),
325                                 null,
326                                 $this->l10n->t('Created at'),
327                                 'created_at'
328                         );
329                 } else {
330                         $created_at = '';
331                 }
332
333                 $tpl = Renderer::getMarkupTemplate('jot.tpl');
334
335                 $o .= Renderer::replaceMacros($tpl, [
336                         '$new_post'            => $this->l10n->t('New Post'),
337                         '$return_path'         => $this->args->getQueryString(),
338                         '$action'              => 'item',
339                         '$share'               => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
340                         '$loading'             => $this->l10n->t('Loading...'),
341                         '$upload'              => $this->l10n->t('Upload photo'),
342                         '$shortupload'         => $this->l10n->t('upload photo'),
343                         '$attach'              => $this->l10n->t('Attach file'),
344                         '$shortattach'         => $this->l10n->t('attach file'),
345                         '$edbold'              => $this->l10n->t('Bold'),
346                         '$editalic'            => $this->l10n->t('Italic'),
347                         '$eduline'             => $this->l10n->t('Underline'),
348                         '$edquote'             => $this->l10n->t('Quote'),
349                         '$edcode'              => $this->l10n->t('Code'),
350                         '$edimg'               => $this->l10n->t('Image'),
351                         '$edurl'               => $this->l10n->t('Link'),
352                         '$edattach'            => $this->l10n->t('Link or Media'),
353                         '$edvideo'             => $this->l10n->t('Video'),
354                         '$setloc'              => $this->l10n->t('Set your location'),
355                         '$shortsetloc'         => $this->l10n->t('set location'),
356                         '$noloc'               => $this->l10n->t('Clear browser location'),
357                         '$shortnoloc'          => $this->l10n->t('clear location'),
358                         '$title'               => $x['title'] ?? '',
359                         '$placeholdertitle'    => $this->l10n->t('Set title'),
360                         '$category'            => $x['category'] ?? '',
361                         '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
362                         '$scheduled_at'        => Temporal::getDateTimeField(
363                                 new \DateTime(),
364                                 new \DateTime('now + 6 months'),
365                                 null,
366                                 $this->l10n->t('Scheduled at'),
367                                 'scheduled_at'
368                         ),
369                         '$created_at'   => $created_at,
370                         '$wait'         => $this->l10n->t('Please wait'),
371                         '$permset'      => $this->l10n->t('Permission settings'),
372                         '$shortpermset' => $this->l10n->t('Permissions'),
373                         '$wall'         => $notes_cid ? 0 : 1,
374                         '$posttype'     => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
375                         '$content'      => $x['content'] ?? '',
376                         '$post_id'      => $x['post_id'] ?? '',
377                         '$baseurl'      => $this->baseURL->get(true),
378                         '$defloc'       => $x['default_location'],
379                         '$visitor'      => $x['visitor'],
380                         '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
381                         '$public'       => $this->l10n->t('Public post'),
382                         '$lockstate'    => $x['lockstate'],
383                         '$bang'         => $x['bang'],
384                         '$profile_uid'  => $x['profile_uid'],
385                         '$preview'      => $this->l10n->t('Preview'),
386                         '$jotplugins'   => $jotplugins,
387                         '$notes_cid'    => $notes_cid,
388                         '$cancel'       => $this->l10n->t('Cancel'),
389                         '$rand_num'     => Crypto::randomDigits(12),
390
391                         // ACL permissions box
392                         '$acl' => $x['acl'],
393
394                         //jot nav tab (used in some themes)
395                         '$message' => $this->l10n->t('Message'),
396                         '$browser' => $this->l10n->t('Browser'),
397
398                         '$compose_link_title'  => $this->l10n->t('Open Compose page'),
399                         '$always_open_compose' => $this->pConfig->get(local_user(), 'frio', 'always_open_compose', false),
400                 ]);
401
402
403                 if ($popup == true) {
404                         $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
405                 }
406
407                 $this->profiler->stopRecording();
408                 return $o;
409         }
410
411         /**
412          * "Render" a conversation or list of items for HTML display.
413          * There are two major forms of display:
414          *      - Sequential or unthreaded ("New Item View" or search results)
415          *      - conversation view
416          * The $mode parameter decides between the various renderings and also
417          * figures out how to determine page owner and other contextual items
418          * that are based on unique features of the calling module.
419          * @param array  $items
420          * @param string $mode
421          * @param        $update @TODO Which type?
422          * @param bool   $preview
423          * @param string $order
424          * @param int    $uid
425          * @return string
426          * @throws ImagickException
427          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428          */
429         public function create(array $items, string $mode, $update, bool $preview = false, string $order = 'commented', int $uid = 0): string
430         {
431                 $this->profiler->startRecording('rendering');
432
433                 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
434                 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
435                 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
436                 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
437
438                 $ssl_state = (local_user() ? true : false);
439
440                 $live_update_div = '';
441
442                 $blocklist = $this->getBlocklist();
443
444                 $previewing = (($preview) ? ' preview ' : '');
445
446                 if ($mode === 'network') {
447                         $items = $this->addChildren($items, false, $order, $uid, $mode);
448                         if (!$update) {
449                                 /*
450                                 * The special div is needed for liveUpdate to kick in for this page.
451                                 * We only launch liveUpdate if you aren't filtering in some incompatible
452                                 * way and also you aren't writing a comment (discovered in javascript).
453                                 */
454                                 $live_update_div = '<div id="live-network"></div>' . "\r\n"
455                                         . "<script> var profile_uid = " . $_SESSION['uid']
456                                         . "; var netargs = '" . substr($this->args->getCommand(), 8)
457                                         . '?f='
458                                         . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
459                                         . (!empty($_GET['search'])    ? '&search='    . rawurlencode($_GET['search'])    : '')
460                                         . (!empty($_GET['star'])      ? '&star='      . rawurlencode($_GET['star'])      : '')
461                                         . (!empty($_GET['order'])     ? '&order='     . rawurlencode($_GET['order'])     : '')
462                                         . (!empty($_GET['bmark'])     ? '&bmark='     . rawurlencode($_GET['bmark'])     : '')
463                                         . (!empty($_GET['liked'])     ? '&liked='     . rawurlencode($_GET['liked'])     : '')
464                                         . (!empty($_GET['conv'])      ? '&conv='      . rawurlencode($_GET['conv'])      : '')
465                                         . (!empty($_GET['nets'])      ? '&nets='      . rawurlencode($_GET['nets'])      : '')
466                                         . (!empty($_GET['cmin'])      ? '&cmin='      . rawurlencode($_GET['cmin'])      : '')
467                                         . (!empty($_GET['cmax'])      ? '&cmax='      . rawurlencode($_GET['cmax'])      : '')
468                                         . (!empty($_GET['file'])      ? '&file='      . rawurlencode($_GET['file'])      : '')
469
470                                         . "'; </script>\r\n";
471                         }
472                 } elseif ($mode === 'profile') {
473                         $items = $this->addChildren($items, false, $order, $uid, $mode);
474
475                         if (!$update) {
476                                 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
477
478                                 if ($tab === 'posts') {
479                                         /*
480                                         * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
481                                         * because browser prefetching might change it on us. We have to deliver it with the page.
482                                         */
483
484                                         $live_update_div = '<div id="live-profile"></div>' . "\r\n"
485                                                 . "<script> var profile_uid = " . $uid
486                                                 . "; var netargs = '?f='; </script>\r\n";
487                                 }
488                         }
489                 } elseif ($mode === 'notes') {
490                         $items = $this->addChildren($items, false, $order, local_user(), $mode);
491
492                         if (!$update) {
493                                 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
494                                         . "<script> var profile_uid = " . local_user()
495                                         . "; var netargs = '/?f='; </script>\r\n";
496                         }
497                 } elseif ($mode === 'display') {
498                         $items = $this->addChildren($items, false, $order, $uid, $mode);
499
500                         if (!$update) {
501                                 $live_update_div = '<div id="live-display"></div>' . "\r\n"
502                                         . "<script> var profile_uid = " . $this->session->get('uid', 0) . ";"
503                                         . "</script>";
504                         }
505                 } elseif ($mode === 'community') {
506                         $items = $this->addChildren($items, true, $order, $uid, $mode);
507
508                         if (!$update) {
509                                 $live_update_div = '<div id="live-community"></div>' . "\r\n"
510                                         . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
511                                         . '?f='
512                                         . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
513                                         . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
514                                         . "'; </script>\r\n";
515                         }
516                 } elseif ($mode === 'contacts') {
517                         $items = $this->addChildren($items, false, $order, $uid, $mode);
518
519                         if (!$update) {
520                                 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
521                                         . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
522                                         ."/?f='; </script>\r\n";
523                         }
524                 } elseif ($mode === 'search') {
525                         $live_update_div = '<div id="live-search"></div>' . "\r\n";
526                 }
527
528                 $page_dropping = ((local_user() && local_user() == $uid) ? true : false);
529
530                 if (!$update) {
531                         $_SESSION['return_path'] = $this->args->getQueryString();
532                 }
533
534                 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
535                 Hook::callAll('conversation_start', $cb);
536
537                 $items = $cb['items'];
538
539                 $conv_responses = [
540                         'like'        => [],
541                         'dislike'     => [],
542                         'attendyes'   => [],
543                         'attendno'    => [],
544                         'attendmaybe' => [],
545                         'announce'    => [],
546                 ];
547
548                 if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
549                         unset($conv_responses['dislike']);
550                 }
551
552                 // array with html for each thread (parent+comments)
553                 $threads   = [];
554                 $threadsid = -1;
555
556                 $page_template     = Renderer::getMarkupTemplate("conversation.tpl");
557                 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
558
559                 if (!empty($items)) {
560                         if (in_array($mode, ['community', 'contacts', 'profile'])) {
561                                 $writable = true;
562                         } else {
563                                 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
564                         }
565
566                         if (!local_user()) {
567                                 $writable = false;
568                         }
569
570                         if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
571
572                                 /*
573                                 * "New Item View" on network page or search page results
574                                 * - just loop through the items and format them minimally for display
575                                 */
576
577                                 $tpl = 'search_item.tpl';
578
579                                 $uriids = [];
580
581                                 foreach ($items as $item) {
582                                         if (in_array($item['uri-id'], $uriids)) {
583                                                 continue;
584                                         }
585
586                                         $uriids[] = $item['uri-id'];
587
588                                         if (!$this->item->isVisibleActivity($item)) {
589                                                 continue;
590                                         }
591
592                                         if (in_array($item['author-id'], $blocklist)) {
593                                                 continue;
594                                         }
595
596                                         $threadsid++;
597
598                                         // prevent private email from leaking.
599                                         if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
600                                                 continue;
601                                         }
602
603                                         $profile_name = $item['author-name'];
604                                         if (!empty($item['author-link']) && empty($item['author-name'])) {
605                                                 $profile_name = $item['author-link'];
606                                         }
607
608                                         $tags = Tag::populateFromItem($item);
609
610                                         $author       = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
611                                         $profile_link = Contact::magicLinkByContact($author);
612
613                                         $sparkle = '';
614                                         if (strpos($profile_link, 'redir/') === 0) {
615                                                 $sparkle = ' sparkle';
616                                         }
617
618                                         $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
619                                         Hook::callAll('render_location', $locate);
620                                         $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
621
622                                         $this->item->localize($item);
623                                         if ($mode === 'filed') {
624                                                 $dropping = true;
625                                         } else {
626                                                 $dropping = false;
627                                         }
628
629                                         $drop = [
630                                                 'dropping' => $dropping,
631                                                 'pagedrop' => $page_dropping,
632                                                 'select'   => $this->l10n->t('Select'),
633                                                 'delete'   => $this->l10n->t('Delete'),
634                                         ];
635
636                                         $likebuttons = [
637                                                 'like'     => null,
638                                                 'dislike'  => null,
639                                                 'share'    => null,
640                                                 'announce' => null,
641                                         ];
642
643                                         if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
644                                                 unset($likebuttons['dislike']);
645                                         }
646
647                                         $body_html = ItemModel::prepareBody($item, true, $preview);
648
649                                         [$categories, $folders] = $this->item->determineCategoriesTerms($item, local_user());
650
651                                         if (!empty($item['title'])) {
652                                                 $title = $item['title'];
653                                         } elseif (!empty($item['content-warning']) && $this->pConfig->get(local_user(), 'system', 'disable_cw', false)) {
654                                                 $title = ucfirst($item['content-warning']);
655                                         } else {
656                                                 $title = '';
657                                         }
658
659                                         if (!empty($item['featured'])) {
660                                                 $pinned = $this->l10n->t('Pinned item');
661                                         } else {
662                                                 $pinned = '';
663                                         }
664
665                                         $tmp_item = [
666                                                 'template'             => $tpl,
667                                                 'id'                   => ($preview ? 'P0' : $item['id']),
668                                                 'guid'                 => ($preview ? 'Q0' : $item['guid']),
669                                                 'commented'            => $item['commented'],
670                                                 'received'             => $item['received'],
671                                                 'created_date'         => $item['created'],
672                                                 'uriid'                => $item['uri-id'],
673                                                 'network'              => $item['network'],
674                                                 'network_name'         => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
675                                                 'network_icon'         => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
676                                                 'linktitle'            => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
677                                                 'profile_url'          => $profile_link,
678                                                 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
679                                                 'name'                 => $profile_name,
680                                                 'sparkle'              => $sparkle,
681                                                 'lock'                 => false,
682                                                 'thumb'                => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
683                                                 'title'                => $title,
684                                                 'body_html'            => $body_html,
685                                                 'tags'                 => $tags['tags'],
686                                                 'hashtags'             => $tags['hashtags'],
687                                                 'mentions'             => $tags['mentions'],
688                                                 'implicit_mentions'    => $tags['implicit_mentions'],
689                                                 'txt_cats'             => $this->l10n->t('Categories:'),
690                                                 'txt_folders'          => $this->l10n->t('Filed under:'),
691                                                 'has_cats'             => ((count($categories)) ? 'true' : ''),
692                                                 'has_folders'          => ((count($folders)) ? 'true' : ''),
693                                                 'categories'           => $categories,
694                                                 'folders'              => $folders,
695                                                 'text'                 => strip_tags($body_html),
696                                                 'localtime'            => DateTimeFormat::local($item['created'], 'r'),
697                                                 'utc'                  => DateTimeFormat::utc($item['created'], 'c'),
698                                                 'ago'                  => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
699                                                 'location_html'        => $location_html,
700                                                 'indent'               => '',
701                                                 'owner_name'           => '',
702                                                 'owner_url'            => '',
703                                                 'owner_photo'          => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
704                                                 'plink'                => ItemModel::getPlink($item),
705                                                 'edpost'               => false,
706                                                 'pinned'               => $pinned,
707                                                 'isstarred'            => 'unstarred',
708                                                 'star'                 => false,
709                                                 'drop'                 => $drop,
710                                                 'vote'                 => $likebuttons,
711                                                 'like_html'            => '',
712                                                 'dislike_html '        => '',
713                                                 'comment_html'         => '',
714                                                 'conv'                 => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
715                                                 'previewing'           => $previewing,
716                                                 'wait'                 => $this->l10n->t('Please wait'),
717                                                 'thread_level'         => 1,
718                                         ];
719
720                                         $arr = ['item' => $item, 'output' => $tmp_item];
721                                         Hook::callAll('display_item', $arr);
722
723                                         $threads[$threadsid]['id']      = $item['id'];
724                                         $threads[$threadsid]['network'] = $item['network'];
725                                         $threads[$threadsid]['items']   = [$arr['output']];
726                                 }
727                         } else {
728                                 // Normal View
729                                 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
730
731                                 $conv = new Thread($mode, $preview, $writable);
732
733                                 /*
734                                 * get all the topmost parents
735                                 * this shouldn't be needed, as we should have only them in our array
736                                 * But for now, this array respects the old style, just in case
737                                 */
738                                 foreach ($items as $item) {
739                                         if (in_array($item['author-id'], $blocklist)) {
740                                                 continue;
741                                         }
742
743                                         // Can we put this after the visibility check?
744                                         $this->builtinActivityPuller($item, $conv_responses);
745
746                                         // Only add what is visible
747                                         if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
748                                                 continue;
749                                         }
750
751                                         if (!$this->item->isVisibleActivity($item)) {
752                                                 continue;
753                                         }
754
755                                         /// @todo Check if this call is needed or not
756                                         $arr = ['item' => $item];
757                                         Hook::callAll('display_item', $arr);
758
759                                         $item['pagedrop'] = $page_dropping;
760
761                                         if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
762                                                 $item_object = new PostObject($item);
763                                                 $conv->addParent($item_object);
764                                         }
765                                 }
766
767                                 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
768                                 if (!$threads) {
769                                         $this->logger->info('[ERROR] conversation : Failed to get template data.');
770                                         $threads = [];
771                                 }
772                         }
773                 }
774
775                 $o = Renderer::replaceMacros($page_template, [
776                         '$baseurl'     => $this->baseURL->get($ssl_state),
777                         '$return_path' => $this->args->getQueryString(),
778                         '$live_update' => $live_update_div,
779                         '$remove'      => $this->l10n->t('remove'),
780                         '$mode'        => $mode,
781                         '$update'      => $update,
782                         '$threads'     => $threads,
783                         '$dropping'    => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
784                 ]);
785
786                 $this->profiler->stopRecording();
787                 return $o;
788         }
789
790         private function getBlocklist(): array
791         {
792                 if (!local_user()) {
793                         return [];
794                 }
795
796                 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get(local_user(), 'system', 'blocked'));
797                 if (empty($str_blocked)) {
798                         return [];
799                 }
800
801                 $blocklist = [];
802
803                 foreach (explode(',', $str_blocked) as $entry) {
804                         $cid = Contact::getIdForURL(trim($entry), 0, false);
805                         if (!empty($cid)) {
806                                 $blocklist[] = $cid;
807                         }
808                 }
809
810                 return $blocklist;
811         }
812
813         /**
814          * Adds some information (Causer, post reason, direction) to the fetched post row.
815          *
816          * @param array   $row        Post row
817          * @param array   $activity   Contact data of the resharer
818          * @param array   $thr_parent Thread parent row
819          *
820          * @return array items with parents and comments
821          */
822         private function addRowInformation(array $row, array $activity, array $thr_parent): array
823         {
824                 $this->profiler->startRecording('rendering');
825
826                 if (!$row['writable']) {
827                         $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
828                 }
829
830                 if (!empty($activity)) {
831                         if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
832                                 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
833
834                                 $row     = array_merge($row, $activity);
835                                 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
836
837                                 $row['causer-link']   = $contact['url'];
838                                 $row['causer-avatar'] = $contact['thumb'];
839                                 $row['causer-name']   = $contact['name'];
840                         } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
841                                 ($row['author-id'] == $activity['causer-id'])) {
842                                 return $row;
843                         }
844                 }
845
846                 switch ($row['post-reason']) {
847                         case ItemModel::PR_TO:
848                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
849                                 break;
850                         case ItemModel::PR_CC:
851                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
852                                 break;
853                         case ItemModel::PR_BTO:
854                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
855                                 break;
856                         case ItemModel::PR_BCC:
857                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
858                                 break;
859                         case ItemModel::PR_FOLLOWER:
860                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
861                                 break;
862                         case ItemModel::PR_TAG:
863                                 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
864                                 break;
865                         case ItemModel::PR_ANNOUNCEMENT:
866                                 if (!empty($row['causer-id']) && $this->pConfig->get(local_user(), 'system', 'display_resharer')) {
867                                         $row['owner-id']     = $row['causer-id'];
868                                         $row['owner-link']   = $row['causer-link'];
869                                         $row['owner-avatar'] = $row['causer-avatar'];
870                                         $row['owner-name']   = $row['causer-name'];
871                                 }
872
873                                 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
874                                         $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
875
876                                         $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
877                                 }
878                                 $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']))];
879                                 break;
880                         case ItemModel::PR_COMMENT:
881                                 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
882                                 break;
883                         case ItemModel::PR_STORED:
884                                 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
885                                 break;
886                         case ItemModel::PR_GLOBAL:
887                                 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
888                                 break;
889                         case ItemModel::PR_RELAY:
890                                 $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']))];
891                                 break;
892                         case ItemModel::PR_FETCHED:
893                                 $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']))];
894                                 break;
895                         case ItemModel::PR_COMPLETION:
896                                 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
897                                 break;
898                         case ItemModel::PR_DIRECT:
899                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
900                                 break;
901                         case ItemModel::PR_ACTIVITY:
902                                 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
903                                 break;
904                         case ItemModel::PR_DISTRIBUTE:
905                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
906                                 break;
907                         case ItemModel::PR_PUSHED:
908                                 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
909                                 break;
910                 }
911
912                 $row['thr-parent-row'] = $thr_parent;
913
914                 $this->profiler->stopRecording();
915                 return $row;
916         }
917
918         /**
919          * Add comments to top level entries that had been fetched before
920          *
921          * The system will fetch the comments for the local user whenever possible.
922          * This behaviour is currently needed to allow commenting on Friendica posts.
923          *
924          * @param array  $parents       Parent items
925          * @param bool   $block_authors
926          * @param bool   $order
927          * @param int    $uid
928          * @param string $mode
929          * @return array items with parents and comments
930          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
931          */
932         private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode): array
933         {
934                 $this->profiler->startRecording('rendering');
935                 if (count($parents) > 1) {
936                         $max_comments = $this->config->get('system', 'max_comments', 100);
937                 } else {
938                         $max_comments = $this->config->get('system', 'max_display_comments', 1000);
939                 }
940
941                 $activities      = [];
942                 $uriids          = [];
943                 $commentcounter  = [];
944                 $activitycounter = [];
945
946                 foreach ($parents as $parent) {
947                         if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
948                                 $uriid = $parent['thr-parent-id'];
949                                 if (!empty($parent['author-id'])) {
950                                         $activities[$uriid] = ['causer-id' => $parent['author-id']];
951                                         foreach (['commented', 'received', 'created'] as $orderfields) {
952                                                 if (!empty($parent[$orderfields])) {
953                                                         $activities[$uriid][$orderfields] = $parent[$orderfields];
954                                                 }
955                                         }
956                                 }
957                         } else {
958                                 $uriid = $parent['uri-id'];
959                         }
960                         $uriids[] = $uriid;
961
962                         $commentcounter[$uriid]  = 0;
963                         $activitycounter[$uriid] = 0;
964                 }
965
966                 $condition = ['parent-uri-id' => $uriids];
967                 if ($block_authors) {
968                         $condition['author-hidden'] = false;
969                 }
970
971                 $condition = DBA::mergeConditions($condition,
972                         ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
973
974                 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
975
976                 $thr_parent = [];
977
978                 while ($row = Post::fetch($thread_parents)) {
979                         $thr_parent[$row['uri-id']] = $row;
980                 }
981                 DBA::close($thread_parents);
982
983                 $params = ['order' => ['uri-id' => true, 'uid' => true]];
984
985                 $thread_items = Post::selectForUser($uid, array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
986
987                 $items = [];
988
989                 while ($row = Post::fetch($thread_items)) {
990                         if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
991                                 continue;
992                         }
993
994                         if (($mode != 'contacts') && !$row['origin']) {
995                                 $row['featured'] = false;
996                         }
997
998                         if ($max_comments > 0) {
999                                 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
1000                                         continue;
1001                                 }
1002                                 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
1003                                         continue;
1004                                 }
1005                         }
1006
1007                         $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
1008                 }
1009
1010                 DBA::close($thread_items);
1011
1012                 $items = $this->convSort($items, $order);
1013
1014                 $this->profiler->stopRecording();
1015                 return $items;
1016         }
1017
1018         /**
1019          * Plucks the children of the given parent from a given item list.
1020          *
1021          * @param array $item_list
1022          * @param array $parent
1023          * @param bool  $recursive
1024          * @return array
1025          */
1026         private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1027         {
1028                 $this->profiler->startRecording('rendering');
1029                 $children = [];
1030                 foreach ($item_list as $i => $item) {
1031                         if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1032                                 if ($recursive) {
1033                                         // Fallback to parent-uri if thr-parent is not set
1034                                         $thr_parent = $item['thr-parent-id'];
1035                                         if ($thr_parent == '') {
1036                                                 $thr_parent = $item['parent-uri-id'];
1037                                         }
1038
1039                                         if ($thr_parent == $parent['uri-id']) {
1040                                                 $item['children'] = $this->getItemChildren($item_list, $item);
1041
1042                                                 $children[] = $item;
1043                                                 unset($item_list[$i]);
1044                                         }
1045                                 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1046                                         $children[] = $item;
1047                                         unset($item_list[$i]);
1048                                 }
1049                         }
1050                 }
1051                 $this->profiler->stopRecording();
1052                 return $children;
1053         }
1054
1055         /**
1056          * Recursively sorts a tree-like item array
1057          *
1058          * @param array $items
1059          * @return array
1060          */
1061         private function sortItemChildren(array $items): array
1062         {
1063                 $this->profiler->startRecording('rendering');
1064                 $result = $items;
1065                 usort($result, [$this, 'sortThrReceivedRev']);
1066                 foreach ($result as $k => $i) {
1067                         if (isset($result[$k]['children'])) {
1068                                 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1069                         }
1070                 }
1071                 $this->profiler->stopRecording();
1072                 return $result;
1073         }
1074
1075         /**
1076          * Recursively add all children items at the top level of a list
1077          *
1078          * @param array $children List of items to append
1079          * @param array $item_list
1080          */
1081         private function addChildrenToList(array $children, array &$item_list)
1082         {
1083                 foreach ($children as $child) {
1084                         $item_list[] = $child;
1085                         if (isset($child['children'])) {
1086                                 $this->addChildrenToList($child['children'], $item_list);
1087                         }
1088                 }
1089         }
1090
1091         /**
1092          * Selectively flattens a tree-like item structure to prevent threading stairs
1093          *
1094          * This recursive function takes the item tree structure created by conv_sort() and
1095          * flatten the extraneous depth levels when people reply sequentially, removing the
1096          * stairs effect in threaded conversations limiting the available content width.
1097          *
1098          * The basic principle is the following: if a post item has only one reply and is
1099          * the last reply of its parent, then the reply is moved to the parent.
1100          *
1101          * This process is rendered somewhat more complicated because items can be either
1102          * replies or likes, and these don't factor at all in the reply count/last reply.
1103          *
1104          * @param array $parent A tree-like array of items
1105          * @return array
1106          */
1107         private function smartFlattenConversation(array $parent): array
1108         {
1109                 $this->profiler->startRecording('rendering');
1110                 if (!isset($parent['children']) || count($parent['children']) == 0) {
1111                         $this->profiler->stopRecording();
1112                         return $parent;
1113                 }
1114
1115                 // We use a for loop to ensure we process the newly-moved items
1116                 for ($i = 0; $i < count($parent['children']); $i++) {
1117                         $child = $parent['children'][$i];
1118
1119                         if (isset($child['children']) && count($child['children'])) {
1120                                 // This helps counting only the regular posts
1121                                 $count_post_closure = function ($var) {
1122                                         $this->profiler->stopRecording();
1123                                         return $var['verb'] === Activity::POST;
1124                                 };
1125
1126                                 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1127
1128                                 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1129
1130                                 // If there's only one child's children post and this is the last child post
1131                                 if ($child_post_count == 1 && $remaining_post_count == 1) {
1132
1133                                         // Searches the post item in the children
1134                                         $j = 0;
1135                                         while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1136                                                 $j ++;
1137                                         }
1138
1139                                         $moved_item = $child['children'][$j];
1140                                         unset($parent['children'][$i]['children'][$j]);
1141                                         $parent['children'][] = $moved_item;
1142                                 } else {
1143                                         $parent['children'][$i] = $this->smartFlattenConversation($child);
1144                                 }
1145                         }
1146                 }
1147
1148                 $this->profiler->stopRecording();
1149                 return $parent;
1150         }
1151
1152         /**
1153          * Expands a flat list of items into corresponding tree-like conversation structures.
1154          *
1155          * sort the top-level posts either on "received" or "commented", and finally
1156          * append all the items at the top level (???)
1157          *
1158          * @param array  $item_list A list of items belonging to one or more conversations
1159          * @param string $order     Either on "received" or "commented"
1160          * @return array
1161          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1162          */
1163         private function convSort(array $item_list, string $order): array
1164         {
1165                 $this->profiler->startRecording('rendering');
1166                 $parents = [];
1167
1168                 if (!(is_array($item_list) && count($item_list))) {
1169                         $this->profiler->stopRecording();
1170                         return $parents;
1171                 }
1172
1173                 $blocklist = $this->getBlocklist();
1174
1175                 $item_array = [];
1176
1177                 // Dedupes the item list on the uri to prevent infinite loops
1178                 foreach ($item_list as $item) {
1179                         if (in_array($item['author-id'], $blocklist)) {
1180                                 continue;
1181                         }
1182
1183                         $item_array[$item['uri-id']] = $item;
1184                 }
1185
1186                 // Extract the top level items
1187                 foreach ($item_array as $item) {
1188                         if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1189                                 $parents[] = $item;
1190                         }
1191                 }
1192
1193                 if (stristr($order, 'pinned_received')) {
1194                         usort($parents, [$this, 'sortThrFeaturedReceived']);
1195                 } elseif (stristr($order, 'pinned_commented')) {
1196                         usort($parents, [$this, 'sortThrFeaturedCommented']);
1197                 } elseif (stristr($order, 'received')) {
1198                         usort($parents, [$this, 'sortThrReceived']);
1199                 } elseif (stristr($order, 'commented')) {
1200                         usort($parents, [$this, 'sortThrCommented']);
1201                 } elseif (stristr($order, 'created')) {
1202                         usort($parents, [$this, 'sortThrCreated']);
1203                 }
1204
1205                 /*
1206                 * Plucks children from the item_array, second pass collects eventual orphan
1207                 * items and add them as children of their top-level post.
1208                 */
1209                 foreach ($parents as $i => $parent) {
1210                         $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1211                                 $this->getItemChildren($item_array, $parent, false));
1212                 }
1213
1214                 foreach ($parents as $i => $parent) {
1215                         $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1216                 }
1217
1218                 if (!$this->pConfig->get(local_user(), 'system', 'no_smart_threading', 0)) {
1219                         foreach ($parents as $i => $parent) {
1220                                 $parents[$i] = $this->smartFlattenConversation($parent);
1221                         }
1222                 }
1223
1224                 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1225                 /// However, this apparently ensures responses (likes, attendance) display (?!)
1226                 foreach ($parents as $parent) {
1227                         if (count($parent['children'])) {
1228                                 $this->addChildrenToList($parent['children'], $parents);
1229                         }
1230                 }
1231
1232                 $this->profiler->stopRecording();
1233                 return $parents;
1234         }
1235
1236         /**
1237          * usort() callback to sort item arrays by featured and the received key
1238          *
1239          * @param array $a
1240          * @param array $b
1241          * @return int
1242          */
1243         private function sortThrFeaturedReceived(array $a, array $b): int
1244         {
1245                 if ($b['featured'] && !$a['featured']) {
1246                         return 1;
1247                 } elseif (!$b['featured'] && $a['featured']) {
1248                         return -1;
1249                 }
1250
1251                 return strcmp($b['received'], $a['received']);
1252         }
1253
1254         /**
1255          * usort() callback to sort item arrays by featured and the received key
1256          *
1257          * @param array $a
1258          * @param array $b
1259          * @return int
1260          */
1261         private function sortThrFeaturedCommented(array $a, array $b): int
1262         {
1263                 if ($b['featured'] && !$a['featured']) {
1264                         return 1;
1265                 } elseif (!$b['featured'] && $a['featured']) {
1266                         return -1;
1267                 }
1268
1269                 return strcmp($b['commented'], $a['commented']);
1270         }
1271
1272         /**
1273          * usort() callback to sort item arrays by the received key
1274          *
1275          * @param array $a
1276          * @param array $b
1277          * @return int
1278          */
1279         private function sortThrReceived(array $a, array $b): int
1280         {
1281                 return strcmp($b['received'], $a['received']);
1282         }
1283
1284         /**
1285          * usort() callback to reverse sort item arrays by the received key
1286          *
1287          * @param array $a
1288          * @param array $b
1289          * @return int
1290          */
1291         private function sortThrReceivedRev(array $a, array $b): int
1292         {
1293                 return strcmp($a['received'], $b['received']);
1294         }
1295
1296         /**
1297          * usort() callback to sort item arrays by the commented key
1298          *
1299          * @param array $a
1300          * @param array $b
1301          * @return int
1302          */
1303         private function sortThrCommented(array $a, array $b): int
1304         {
1305                 return strcmp($b['commented'], $a['commented']);
1306         }
1307
1308         /**
1309          * usort() callback to sort item arrays by the created key
1310          *
1311          * @param array $a
1312          * @param array $b
1313          * @return int
1314          */
1315         private function sortThrCreated(array $a, array $b): int
1316         {
1317                 return strcmp($b['created'], $a['created']);
1318         }
1319 }