]> git.mxchange.org Git - friendica.git/blob - src/Content/Conversation.php
Merge pull request #11428 from annando/issue-11425
[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\Proxy;
51 use Friendica\Util\Strings;
52 use Friendica\Util\Temporal;
53 use Psr\Log\LoggerInterface;
54
55 class Conversation
56 {
57         /** @var Activity */
58         private $activity;
59         /** @var L10n */
60         private $l10n;
61         /** @var Profiler */
62         private $profiler;
63         /** @var LoggerInterface */
64         private $logger;
65         /** @var Item */
66         private $item;
67         /** @var App\Arguments */
68         private $args;
69         /** @var IManagePersonalConfigValues */
70         private $pConfig;
71         /** @var BaseURL */
72         private $baseURL;
73         /** @var IManageConfigValues */
74         private $config;
75         /** @var App */
76         private $app;
77         /** @var App\Page */
78         private $page;
79         /** @var App\Mode */
80         private $mode;
81
82         public function __construct(LoggerInterface $logger, Profiler $profiler, Activity $activity, L10n $l10n, Item $item, Arguments $args, BaseURL $baseURL, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, App\Page $page, App\Mode $mode, App $app)
83         {
84                 $this->activity = $activity;
85                 $this->item     = $item;
86                 $this->config   = $config;
87                 $this->mode     = $mode;
88                 $this->baseURL  = $baseURL;
89                 $this->profiler = $profiler;
90                 $this->logger   = $logger;
91                 $this->l10n     = $l10n;
92                 $this->args     = $args;
93                 $this->pConfig  = $pConfig;
94                 $this->page     = $page;
95                 $this->app      = $app;
96         }
97
98         /**
99          * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
100          *
101          * Increments the count of each matching activity and adds a link to the author as needed.
102          *
103          * @param array  $activity
104          * @param array &$conv_responses (already created with builtin activity structure)
105          * @return void
106          * @throws ImagickException
107          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
108          */
109         public function builtinActivityPuller(array $activity, array &$conv_responses)
110         {
111                 foreach ($conv_responses as $mode => $v) {
112                         $sparkle = '';
113
114                         switch ($mode) {
115                                 case 'like':
116                                         $verb = Activity::LIKE;
117                                         break;
118                                 case 'dislike':
119                                         $verb = Activity::DISLIKE;
120                                         break;
121                                 case 'attendyes':
122                                         $verb = Activity::ATTEND;
123                                         break;
124                                 case 'attendno':
125                                         $verb = Activity::ATTENDNO;
126                                         break;
127                                 case 'attendmaybe':
128                                         $verb = Activity::ATTENDMAYBE;
129                                         break;
130                                 case 'announce':
131                                         $verb = Activity::ANNOUNCE;
132                                         break;
133                                 default:
134                                         return;
135                         }
136
137                         if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
138                                 $author = [
139                                         'uid'     => 0,
140                                         'id'      => $activity['author-id'],
141                                         'network' => $activity['author-network'],
142                                         'url'     => $activity['author-link']
143                                 ];
144                                 $url = Contact::magicLinkByContact($author);
145                                 if (strpos($url, 'redir/') === 0) {
146                                         $sparkle = ' class="sparkle" ';
147                                 }
148
149                                 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
150
151                                 if (empty($activity['thr-parent-id'])) {
152                                         $activity['thr-parent-id'] = $activity['parent-uri-id'];
153                                 }
154
155                                 // Skip when the causer of the parent is the same than the author of the announce
156                                 if (($verb == Activity::ANNOUNCE) && Post::exists(['uri-id' => $activity['thr-parent-id'],
157                                         'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
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, $verb, $id)
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 = [], $notes_cid = 0, $popup = false)
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        $mode
418          * @param        $update
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, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
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);
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);
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());
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);
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);
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                                         . "'; </script>\r\n";
511                         }
512                 } elseif ($mode === 'contacts') {
513                         $items = $this->addChildren($items, false, $order, $uid);
514
515                         if (!$update) {
516                                 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
517                                         . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
518                                         ."/?f='; </script>\r\n";
519                         }
520                 } elseif ($mode === 'search') {
521                         $live_update_div = '<div id="live-search"></div>' . "\r\n";
522                 }
523
524                 $page_dropping = ((local_user() && local_user() == $uid) ? true : false);
525
526                 if (!$update) {
527                         $_SESSION['return_path'] = $this->args->getQueryString();
528                 }
529
530                 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
531                 Hook::callAll('conversation_start', $cb);
532
533                 $items = $cb['items'];
534
535                 $conv_responses = [
536                         'like'        => [],
537                         'dislike'     => [],
538                         'attendyes'   => [],
539                         'attendno'    => [],
540                         'attendmaybe' => [],
541                         'announce'    => [],
542                 ];
543
544                 if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
545                         unset($conv_responses['dislike']);
546                 }
547
548                 // array with html for each thread (parent+comments)
549                 $threads   = [];
550                 $threadsid = -1;
551
552                 $page_template     = Renderer::getMarkupTemplate("conversation.tpl");
553                 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
554
555                 if (!empty($items)) {
556                         if (in_array($mode, ['community', 'contacts', 'profile'])) {
557                                 $writable = true;
558                         } else {
559                                 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
560                         }
561
562                         if (!local_user()) {
563                                 $writable = false;
564                         }
565
566                         if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
567
568                                 /*
569                                 * "New Item View" on network page or search page results
570                                 * - just loop through the items and format them minimally for display
571                                 */
572
573                                 $tpl = 'search_item.tpl';
574
575                                 $uriids = [];
576
577                                 foreach ($items as $item) {
578                                         if (in_array($item['uri-id'], $uriids)) {
579                                                 continue;
580                                         }
581
582                                         $uriids[] = $item['uri-id'];
583
584                                         if (!$this->item->visibleActivity($item)) {
585                                                 continue;
586                                         }
587
588                                         if (in_array($item['author-id'], $blocklist)) {
589                                                 continue;
590                                         }
591
592                                         $threadsid++;
593
594                                         // prevent private email from leaking.
595                                         if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
596                                                 continue;
597                                         }
598
599                                         $profile_name = $item['author-name'];
600                                         if (!empty($item['author-link']) && empty($item['author-name'])) {
601                                                 $profile_name = $item['author-link'];
602                                         }
603
604                                         $tags = Tag::populateFromItem($item);
605
606                                         $author       = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
607                                         $profile_link = Contact::magicLinkByContact($author);
608
609                                         $sparkle = '';
610                                         if (strpos($profile_link, 'redir/') === 0) {
611                                                 $sparkle = ' sparkle';
612                                         }
613
614                                         $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
615                                         Hook::callAll('render_location', $locate);
616                                         $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
617
618                                         $this->item->localize($item);
619                                         if ($mode === 'filed') {
620                                                 $dropping = true;
621                                         } else {
622                                                 $dropping = false;
623                                         }
624
625                                         $drop = [
626                                                 'dropping' => $dropping,
627                                                 'pagedrop' => $page_dropping,
628                                                 'select'   => $this->l10n->t('Select'),
629                                                 'delete'   => $this->l10n->t('Delete'),
630                                         ];
631
632                                         $likebuttons = [
633                                                 'like'     => null,
634                                                 'dislike'  => null,
635                                                 'share'    => null,
636                                                 'announce' => null,
637                                         ];
638
639                                         if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
640                                                 unset($likebuttons['dislike']);
641                                         }
642
643                                         $body_html = ItemModel::prepareBody($item, true, $preview);
644
645                                         [$categories, $folders] = $this->item->determineCategoriesTerms($item, local_user());
646
647                                         if (!empty($item['title'])) {
648                                                 $title = $item['title'];
649                                         } elseif (!empty($item['content-warning']) && $this->pConfig->get(local_user(), 'system', 'disable_cw', false)) {
650                                                 $title = ucfirst($item['content-warning']);
651                                         } else {
652                                                 $title = '';
653                                         }
654
655                                         if (!empty($item['featured'])) {
656                                                 $pinned = $this->l10n->t('Pinned item');
657                                         } else {
658                                                 $pinned = '';
659                                         }
660
661                                         $tmp_item = [
662                                                 'template'             => $tpl,
663                                                 'id'                   => ($preview ? 'P0' : $item['id']),
664                                                 'guid'                 => ($preview ? 'Q0' : $item['guid']),
665                                                 'commented'            => $item['commented'],
666                                                 'received'             => $item['received'],
667                                                 'created_date'         => $item['created'],
668                                                 'uriid'                => $item['uri-id'],
669                                                 'network'              => $item['network'],
670                                                 'network_name'         => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
671                                                 'network_icon'         => ContactSelector::networkToIcon($item['network'], $item['author-link']),
672                                                 'linktitle'            => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
673                                                 'profile_url'          => $profile_link,
674                                                 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
675                                                 'name'                 => $profile_name,
676                                                 'sparkle'              => $sparkle,
677                                                 'lock'                 => false,
678                                                 'thumb'                => $this->baseURL->remove(Contact::getAvatarUrlForUrl($item['author-link'], $item['uid'], Proxy::SIZE_THUMB)),
679                                                 'title'                => $title,
680                                                 'body_html'            => $body_html,
681                                                 'tags'                 => $tags['tags'],
682                                                 'hashtags'             => $tags['hashtags'],
683                                                 'mentions'             => $tags['mentions'],
684                                                 'implicit_mentions'    => $tags['implicit_mentions'],
685                                                 'txt_cats'             => $this->l10n->t('Categories:'),
686                                                 'txt_folders'          => $this->l10n->t('Filed under:'),
687                                                 'has_cats'             => ((count($categories)) ? 'true' : ''),
688                                                 'has_folders'          => ((count($folders)) ? 'true' : ''),
689                                                 'categories'           => $categories,
690                                                 'folders'              => $folders,
691                                                 'text'                 => strip_tags($body_html),
692                                                 'localtime'            => DateTimeFormat::local($item['created'], 'r'),
693                                                 'utc'                  => DateTimeFormat::utc($item['created'], 'c'),
694                                                 'ago'                  => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
695                                                 'location_html'        => $location_html,
696                                                 'indent'               => '',
697                                                 'owner_name'           => '',
698                                                 'owner_url'            => '',
699                                                 'owner_photo'          => $this->baseURL->remove(Contact::getAvatarUrlForUrl($item['owner-link'], $item['uid'], Proxy::SIZE_THUMB)),
700                                                 'plink'                => ItemModel::getPlink($item),
701                                                 'edpost'               => false,
702                                                 'pinned'               => $pinned,
703                                                 'isstarred'            => 'unstarred',
704                                                 'star'                 => false,
705                                                 'drop'                 => $drop,
706                                                 'vote'                 => $likebuttons,
707                                                 'like_html'            => '',
708                                                 'dislike_html '        => '',
709                                                 'comment_html'         => '',
710                                                 'conv'                 => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
711                                                 'previewing'           => $previewing,
712                                                 'wait'                 => $this->l10n->t('Please wait'),
713                                                 'thread_level'         => 1,
714                                         ];
715
716                                         $arr = ['item' => $item, 'output' => $tmp_item];
717                                         Hook::callAll('display_item', $arr);
718
719                                         $threads[$threadsid]['id']      = $item['id'];
720                                         $threads[$threadsid]['network'] = $item['network'];
721                                         $threads[$threadsid]['items']   = [$arr['output']];
722                                 }
723                         } else {
724                                 // Normal View
725                                 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
726
727                                 $conv = new Thread($mode, $preview, $writable);
728
729                                 /*
730                                 * get all the topmost parents
731                                 * this shouldn't be needed, as we should have only them in our array
732                                 * But for now, this array respects the old style, just in case
733                                 */
734                                 foreach ($items as $item) {
735                                         if (in_array($item['author-id'], $blocklist)) {
736                                                 continue;
737                                         }
738
739                                         // Can we put this after the visibility check?
740                                         $this->builtinActivityPuller($item, $conv_responses);
741
742                                         // Only add what is visible
743                                         if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
744                                                 continue;
745                                         }
746
747                                         if (!$this->item->visibleActivity($item)) {
748                                                 continue;
749                                         }
750
751                                         /// @todo Check if this call is needed or not
752                                         $arr = ['item' => $item];
753                                         Hook::callAll('display_item', $arr);
754
755                                         $item['pagedrop'] = $page_dropping;
756
757                                         if ($item['gravity'] == GRAVITY_PARENT) {
758                                                 $item_object = new PostObject($item);
759                                                 $conv->addParent($item_object);
760                                         }
761                                 }
762
763                                 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
764                                 if (!$threads) {
765                                         $this->logger->info('[ERROR] conversation : Failed to get template data.');
766                                         $threads = [];
767                                 }
768                         }
769                 }
770
771                 $o = Renderer::replaceMacros($page_template, [
772                         '$baseurl'     => $this->baseURL->get($ssl_state),
773                         '$return_path' => $this->args->getQueryString(),
774                         '$live_update' => $live_update_div,
775                         '$remove'      => $this->l10n->t('remove'),
776                         '$mode'        => $mode,
777                         '$update'      => $update,
778                         '$threads'     => $threads,
779                         '$dropping'    => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
780                 ]);
781
782                 $this->profiler->stopRecording();
783                 return $o;
784         }
785
786         private function getBlocklist()
787         {
788                 if (!local_user()) {
789                         return [];
790                 }
791
792                 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get(local_user(), 'system', 'blocked'));
793                 if (empty($str_blocked)) {
794                         return [];
795                 }
796
797                 $blocklist = [];
798
799                 foreach (explode(',', $str_blocked) as $entry) {
800                         $cid = Contact::getIdForURL(trim($entry), 0, false);
801                         if (!empty($cid)) {
802                                 $blocklist[] = $cid;
803                         }
804                 }
805
806                 return $blocklist;
807         }
808
809         /**
810          * Adds some information (Causer, post reason, direction) to the fetched post row.
811          *
812          * @param array   $row      Post row
813          * @param array   $activity Contact data of the resharer
814          *
815          * @return array items with parents and comments
816          */
817         private function addRowInformation(array $row, array $activity)
818         {
819                 $this->profiler->startRecording('rendering');
820
821                 if ($row['uid'] == 0) {
822                         $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
823                 }
824
825                 if (!empty($activity)) {
826                         if (($row['gravity'] == GRAVITY_PARENT)) {
827                                 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
828
829                                 $row     = array_merge($row, $activity);
830                                 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
831
832                                 $row['causer-link']   = $contact['url'];
833                                 $row['causer-avatar'] = $contact['thumb'];
834                                 $row['causer-name']   = $contact['name'];
835                         } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
836                                 ($row['author-id'] == $activity['causer-id'])) {
837                                 return $row;
838                         }
839                 }
840
841                 switch ($row['post-reason']) {
842                         case ItemModel::PR_TO:
843                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
844                                 break;
845                         case ItemModel::PR_CC:
846                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
847                                 break;
848                         case ItemModel::PR_BTO:
849                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
850                                 break;
851                         case ItemModel::PR_BCC:
852                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
853                                 break;
854                         case ItemModel::PR_FOLLOWER:
855                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['author-name'])];
856                                 break;
857                         case ItemModel::PR_TAG:
858                                 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('Tagged')];
859                                 break;
860                         case ItemModel::PR_ANNOUNCEMENT:
861                                 if (!empty($row['causer-id']) && $this->pConfig->get(local_user(), 'system', 'display_resharer')) {
862                                         $row['owner-id']     = $row['causer-id'];
863                                         $row['owner-link']   = $row['causer-link'];
864                                         $row['owner-avatar'] = $row['causer-avatar'];
865                                         $row['owner-name']   = $row['causer-name'];
866                                 }
867
868                                 if (in_array($row['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
869                                         $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
870
871                                         $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
872                                 }
873                                 $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']))];
874                                 break;
875                         case ItemModel::PR_COMMENT:
876                                 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
877                                 break;
878                         case ItemModel::PR_STORED:
879                                 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored')];
880                                 break;
881                         case ItemModel::PR_GLOBAL:
882                                 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global')];
883                                 break;
884                         case ItemModel::PR_RELAY:
885                                 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Relayed') : $this->l10n->t('Relayed by %s <%s>', $row['causer-name'], $row['causer-link']))];
886                                 break;
887                         case ItemModel::PR_FETCHED:
888                                 $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']))];
889                                 break;
890                 }
891
892                 $this->profiler->stopRecording();
893                 return $row;
894         }
895
896         /**
897          * Add comments to top level entries that had been fetched before
898          *
899          * The system will fetch the comments for the local user whenever possible.
900          * This behaviour is currently needed to allow commenting on Friendica posts.
901          *
902          * @param array $parents Parent items
903          *
904          * @param       $block_authors
905          * @param       $order
906          * @param       $uid
907          * @return array items with parents and comments
908          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
909          */
910         private function addChildren(array $parents, $block_authors, $order, $uid)
911         {
912                 $this->profiler->startRecording('rendering');
913                 if (count($parents) > 1) {
914                         $max_comments = $this->config->get('system', 'max_comments', 100);
915                 } else {
916                         $max_comments = $this->config->get('system', 'max_display_comments', 1000);
917                 }
918
919                 $params = ['order' => ['uri-id' => true, 'uid' => true]];
920
921                 $activities      = [];
922                 $uriids          = [];
923                 $commentcounter  = [];
924                 $activitycounter = [];
925
926                 foreach ($parents as $parent) {
927                         if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
928                                 $uriid = $parent['thr-parent-id'];
929                                 if (!empty($parent['author-id'])) {
930                                         $activities[$uriid] = ['causer-id' => $parent['author-id']];
931                                         foreach (['commented', 'received', 'created'] as $orderfields) {
932                                                 if (!empty($parent[$orderfields])) {
933                                                         $activities[$uriid][$orderfields] = $parent[$orderfields];
934                                                 }
935                                         }
936                                 }
937                         } else {
938                                 $uriid = $parent['uri-id'];
939                         }
940                         $uriids[] = $uriid;
941
942                         $commentcounter[$uriid]  = 0;
943                         $activitycounter[$uriid] = 0;
944                 }
945
946                 $condition = ['parent-uri-id' => $uriids];
947                 if ($block_authors) {
948                         $condition['author-hidden'] = false;
949                 }
950
951                 $condition = DBA::mergeConditions($condition,
952                         ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
953
954                 $thread_items = Post::selectForUser($uid, array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
955
956                 $items = [];
957
958                 while ($row = Post::fetch($thread_items)) {
959                         if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
960                                 continue;
961                         }
962
963                         if ($max_comments > 0) {
964                                 if (($row['gravity'] == GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
965                                         continue;
966                                 }
967                                 if (($row['gravity'] == GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
968                                         continue;
969                                 }
970                         }
971                         $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? []);
972                 }
973
974                 DBA::close($thread_items);
975
976                 $items = $this->convSort($items, $order);
977
978                 $this->profiler->stopRecording();
979                 return $items;
980         }
981
982         /**
983          * Plucks the children of the given parent from a given item list.
984          *
985          * @param array $item_list
986          * @param array $parent
987          * @param bool  $recursive
988          * @return array
989          */
990         private function getItemChildren(array &$item_list, array $parent, $recursive = true)
991         {
992                 $this->profiler->startRecording('rendering');
993                 $children = [];
994                 foreach ($item_list as $i => $item) {
995                         if ($item['gravity'] != GRAVITY_PARENT) {
996                                 if ($recursive) {
997                                         // Fallback to parent-uri if thr-parent is not set
998                                         $thr_parent = $item['thr-parent-id'];
999                                         if ($thr_parent == '') {
1000                                                 $thr_parent = $item['parent-uri-id'];
1001                                         }
1002
1003                                         if ($thr_parent == $parent['uri-id']) {
1004                                                 $item['children'] = $this->getItemChildren($item_list, $item);
1005
1006                                                 $children[] = $item;
1007                                                 unset($item_list[$i]);
1008                                         }
1009                                 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1010                                         $children[] = $item;
1011                                         unset($item_list[$i]);
1012                                 }
1013                         }
1014                 }
1015                 $this->profiler->stopRecording();
1016                 return $children;
1017         }
1018
1019         /**
1020          * Recursively sorts a tree-like item array
1021          *
1022          * @param array $items
1023          * @return array
1024          */
1025         private function sortItemChildren(array $items)
1026         {
1027                 $this->profiler->startRecording('rendering');
1028                 $result = $items;
1029                 usort($result, [$this, 'sortThrReceivedRev']);
1030                 foreach ($result as $k => $i) {
1031                         if (isset($result[$k]['children'])) {
1032                                 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1033                         }
1034                 }
1035                 $this->profiler->stopRecording();
1036                 return $result;
1037         }
1038
1039         /**
1040          * Recursively add all children items at the top level of a list
1041          *
1042          * @param array $children List of items to append
1043          * @param array $item_list
1044          */
1045         private function addChildrenToList(array $children, array &$item_list)
1046         {
1047                 foreach ($children as $child) {
1048                         $item_list[] = $child;
1049                         if (isset($child['children'])) {
1050                                 $this->addChildrenToList($child['children'], $item_list);
1051                         }
1052                 }
1053         }
1054
1055         /**
1056          * Selectively flattens a tree-like item structure to prevent threading stairs
1057          *
1058          * This recursive function takes the item tree structure created by conv_sort() and
1059          * flatten the extraneous depth levels when people reply sequentially, removing the
1060          * stairs effect in threaded conversations limiting the available content width.
1061          *
1062          * The basic principle is the following: if a post item has only one reply and is
1063          * the last reply of its parent, then the reply is moved to the parent.
1064          *
1065          * This process is rendered somewhat more complicated because items can be either
1066          * replies or likes, and these don't factor at all in the reply count/last reply.
1067          *
1068          * @param array $parent A tree-like array of items
1069          * @return array
1070          */
1071         private function smartFlattenConversation(array $parent)
1072         {
1073                 $this->profiler->startRecording('rendering');
1074                 if (!isset($parent['children']) || count($parent['children']) == 0) {
1075                         $this->profiler->stopRecording();
1076                         return $parent;
1077                 }
1078
1079                 // We use a for loop to ensure we process the newly-moved items
1080                 for ($i = 0; $i < count($parent['children']); $i++) {
1081                         $child = $parent['children'][$i];
1082
1083                         if (isset($child['children']) && count($child['children'])) {
1084                                 // This helps counting only the regular posts
1085                                 $count_post_closure = function ($var) {
1086                                         $this->profiler->stopRecording();
1087                                         return $var['verb'] === Activity::POST;
1088                                 };
1089
1090                                 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1091
1092                                 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1093
1094                                 // If there's only one child's children post and this is the last child post
1095                                 if ($child_post_count == 1 && $remaining_post_count == 1) {
1096
1097                                         // Searches the post item in the children
1098                                         $j = 0;
1099                                         while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1100                                                 $j ++;
1101                                         }
1102
1103                                         $moved_item = $child['children'][$j];
1104                                         unset($parent['children'][$i]['children'][$j]);
1105                                         $parent['children'][] = $moved_item;
1106                                 } else {
1107                                         $parent['children'][$i] = $this->smartFlattenConversation($child);
1108                                 }
1109                         }
1110                 }
1111
1112                 $this->profiler->stopRecording();
1113                 return $parent;
1114         }
1115
1116         /**
1117          * Expands a flat list of items into corresponding tree-like conversation structures.
1118          *
1119          * sort the top-level posts either on "received" or "commented", and finally
1120          * append all the items at the top level (???)
1121          *
1122          * @param array  $item_list A list of items belonging to one or more conversations
1123          * @param string $order     Either on "received" or "commented"
1124          * @return array
1125          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1126          */
1127         private function convSort(array $item_list, $order)
1128         {
1129                 $this->profiler->startRecording('rendering');
1130                 $parents = [];
1131
1132                 if (!(is_array($item_list) && count($item_list))) {
1133                         $this->profiler->stopRecording();
1134                         return $parents;
1135                 }
1136
1137                 $blocklist = $this->getBlocklist();
1138
1139                 $item_array = [];
1140
1141                 // Dedupes the item list on the uri to prevent infinite loops
1142                 foreach ($item_list as $item) {
1143                         if (in_array($item['author-id'], $blocklist)) {
1144                                 continue;
1145                         }
1146
1147                         $item_array[$item['uri-id']] = $item;
1148                 }
1149
1150                 // Extract the top level items
1151                 foreach ($item_array as $item) {
1152                         if ($item['gravity'] == GRAVITY_PARENT) {
1153                                 $parents[] = $item;
1154                         }
1155                 }
1156
1157                 if (stristr($order, 'pinned_received')) {
1158                         usort($parents, [$this, 'sortThrFeaturedReceived']);
1159                 } elseif (stristr($order, 'pinned_commented')) {
1160                         usort($parents, [$this, 'sortThrFeaturedCommented']);
1161                 } elseif (stristr($order, 'received')) {
1162                         usort($parents, [$this, 'sortThrReceived']);
1163                 } elseif (stristr($order, 'commented')) {
1164                         usort($parents, [$this, 'sortThrCommented']);
1165                 } elseif (stristr($order, 'created')) {
1166                         usort($parents, [$this, 'sortThrCreated']);
1167                 }
1168
1169                 /*
1170                 * Plucks children from the item_array, second pass collects eventual orphan
1171                 * items and add them as children of their top-level post.
1172                 */
1173                 foreach ($parents as $i => $parent) {
1174                         $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1175                                 $this->getItemChildren($item_array, $parent, false));
1176                 }
1177
1178                 foreach ($parents as $i => $parent) {
1179                         $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1180                 }
1181
1182                 if (!$this->pConfig->get(local_user(), 'system', 'no_smart_threading', 0)) {
1183                         foreach ($parents as $i => $parent) {
1184                                 $parents[$i] = $this->smartFlattenConversation($parent);
1185                         }
1186                 }
1187
1188                 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1189                 /// However, this apparently ensures responses (likes, attendance) display (?!)
1190                 foreach ($parents as $parent) {
1191                         if (count($parent['children'])) {
1192                                 $this->addChildrenToList($parent['children'], $parents);
1193                         }
1194                 }
1195
1196                 $this->profiler->stopRecording();
1197                 return $parents;
1198         }
1199
1200         /**
1201          * usort() callback to sort item arrays by featured and the received key
1202          *
1203          * @param array $a
1204          * @param array $b
1205          * @return int
1206          */
1207         private function sortThrFeaturedReceived(array $a, array $b)
1208         {
1209                 if ($b['featured'] && !$a['featured']) {
1210                         return 1;
1211                 } elseif (!$b['featured'] && $a['featured']) {
1212                         return -1;
1213                 }
1214
1215                 return strcmp($b['received'], $a['received']);
1216         }
1217
1218         /**
1219          * usort() callback to sort item arrays by featured and the received key
1220          *
1221          * @param array $a
1222          * @param array $b
1223          * @return int
1224          */
1225         private function sortThrFeaturedCommented(array $a, array $b)
1226         {
1227                 if ($b['featured'] && !$a['featured']) {
1228                         return 1;
1229                 } elseif (!$b['featured'] && $a['featured']) {
1230                         return -1;
1231                 }
1232
1233                 return strcmp($b['commented'], $a['commented']);
1234         }
1235
1236         /**
1237          * usort() callback to sort item arrays by the received key
1238          *
1239          * @param array $a
1240          * @param array $b
1241          * @return int
1242          */
1243         private function sortThrReceived(array $a, array $b)
1244         {
1245                 return strcmp($b['received'], $a['received']);
1246         }
1247
1248         /**
1249          * usort() callback to reverse sort item arrays by the received key
1250          *
1251          * @param array $a
1252          * @param array $b
1253          * @return int
1254          */
1255         private function sortThrReceivedRev(array $a, array $b)
1256         {
1257                 return strcmp($a['received'], $b['received']);
1258         }
1259
1260         /**
1261          * usort() callback to sort item arrays by the commented key
1262          *
1263          * @param array $a
1264          * @param array $b
1265          * @return int
1266          */
1267         private function sortThrCommented(array $a, array $b)
1268         {
1269                 return strcmp($b['commented'], $a['commented']);
1270         }
1271
1272         /**
1273          * usort() callback to sort item arrays by the created key
1274          *
1275          * @param array $a
1276          * @param array $b
1277          * @return int
1278          */
1279         private function sortThrCreated(array $a, array $b)
1280         {
1281                 return strcmp($b['created'], $a['created']);
1282         }
1283 }