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