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