]> git.mxchange.org Git - friendica.git/blob - src/Content/Conversation.php
Add rel="tag" to the HTML Purifier allow list in BBCode::convert
[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])) {
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                 $tpl = Renderer::getMarkupTemplate("jot.tpl");
320
321                 $o .= Renderer::replaceMacros($tpl, [
322                         '$new_post'            => $this->l10n->t('New Post'),
323                         '$return_path'         => $this->args->getQueryString(),
324                         '$action'              => 'item',
325                         '$share'               => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
326                         '$loading'             => $this->l10n->t('Loading...'),
327                         '$upload'              => $this->l10n->t('Upload photo'),
328                         '$shortupload'         => $this->l10n->t('upload photo'),
329                         '$attach'              => $this->l10n->t('Attach file'),
330                         '$shortattach'         => $this->l10n->t('attach file'),
331                         '$edbold'              => $this->l10n->t('Bold'),
332                         '$editalic'            => $this->l10n->t('Italic'),
333                         '$eduline'             => $this->l10n->t('Underline'),
334                         '$edquote'             => $this->l10n->t('Quote'),
335                         '$edcode'              => $this->l10n->t('Code'),
336                         '$edimg'               => $this->l10n->t('Image'),
337                         '$edurl'               => $this->l10n->t('Link'),
338                         '$edattach'            => $this->l10n->t('Link or Media'),
339                         '$edvideo'             => $this->l10n->t('Video'),
340                         '$setloc'              => $this->l10n->t('Set your location'),
341                         '$shortsetloc'         => $this->l10n->t('set location'),
342                         '$noloc'               => $this->l10n->t('Clear browser location'),
343                         '$shortnoloc'          => $this->l10n->t('clear location'),
344                         '$title'               => $x['title'] ?? '',
345                         '$placeholdertitle'    => $this->l10n->t('Set title'),
346                         '$category'            => $x['category'] ?? '',
347                         '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
348                         '$scheduled_at'        => Temporal::getDateTimeField(
349                                 new \DateTime(),
350                                 new \DateTime('now + 6 months'),
351                                 null,
352                                 $this->l10n->t('Scheduled at'),
353                                 'scheduled_at'
354                         ),
355                         '$wait'         => $this->l10n->t('Please wait'),
356                         '$permset'      => $this->l10n->t('Permission settings'),
357                         '$shortpermset' => $this->l10n->t('Permissions'),
358                         '$wall'         => $notes_cid ? 0 : 1,
359                         '$posttype'     => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
360                         '$content'      => $x['content'] ?? '',
361                         '$post_id'      => $x['post_id'] ?? '',
362                         '$baseurl'      => $this->baseURL->get(true),
363                         '$defloc'       => $x['default_location'],
364                         '$visitor'      => $x['visitor'],
365                         '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
366                         '$public'       => $this->l10n->t('Public post'),
367                         '$lockstate'    => $x['lockstate'],
368                         '$bang'         => $x['bang'],
369                         '$profile_uid'  => $x['profile_uid'],
370                         '$preview'      => $this->l10n->t('Preview'),
371                         '$jotplugins'   => $jotplugins,
372                         '$notes_cid'    => $notes_cid,
373                         '$cancel'       => $this->l10n->t('Cancel'),
374                         '$rand_num'     => Crypto::randomDigits(12),
375
376                         // ACL permissions box
377                         '$acl' => $x['acl'],
378
379                         //jot nav tab (used in some themes)
380                         '$message' => $this->l10n->t('Message'),
381                         '$browser' => $this->l10n->t('Browser'),
382
383                         '$compose_link_title' => $this->l10n->t('Open Compose page'),
384                 ]);
385
386
387                 if ($popup == true) {
388                         $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
389                 }
390
391                 $this->profiler->stopRecording();
392                 return $o;
393         }
394
395         /**
396          * "Render" a conversation or list of items for HTML display.
397          * There are two major forms of display:
398          *      - Sequential or unthreaded ("New Item View" or search results)
399          *      - conversation view
400          * The $mode parameter decides between the various renderings and also
401          * figures out how to determine page owner and other contextual items
402          * that are based on unique features of the calling module.
403          * @param array  $items
404          * @param        $mode
405          * @param        $update
406          * @param bool   $preview
407          * @param string $order
408          * @param int    $uid
409          * @return string
410          * @throws ImagickException
411          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
412          */
413         public function create(array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
414         {
415                 $this->profiler->startRecording('rendering');
416
417                 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
418                 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
419                 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
420                 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
421
422                 $ssl_state = (local_user() ? true : false);
423
424                 $live_update_div = '';
425
426                 $blocklist = $this->getBlocklist();
427
428                 $previewing = (($preview) ? ' preview ' : '');
429
430                 if ($mode === 'network') {
431                         $items = $this->addChildren($items, false, $order, $uid);
432                         if (!$update) {
433                                 /*
434                                 * The special div is needed for liveUpdate to kick in for this page.
435                                 * We only launch liveUpdate if you aren't filtering in some incompatible
436                                 * way and also you aren't writing a comment (discovered in javascript).
437                                 */
438                                 $live_update_div = '<div id="live-network"></div>' . "\r\n"
439                                         . "<script> var profile_uid = " . $_SESSION['uid']
440                                         . "; var netargs = '" . substr($this->args->getCommand(), 8)
441                                         . '?f='
442                                         . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
443                                         . (!empty($_GET['search'])    ? '&search='    . rawurlencode($_GET['search'])    : '')
444                                         . (!empty($_GET['star'])      ? '&star='      . rawurlencode($_GET['star'])      : '')
445                                         . (!empty($_GET['order'])     ? '&order='     . rawurlencode($_GET['order'])     : '')
446                                         . (!empty($_GET['bmark'])     ? '&bmark='     . rawurlencode($_GET['bmark'])     : '')
447                                         . (!empty($_GET['liked'])     ? '&liked='     . rawurlencode($_GET['liked'])     : '')
448                                         . (!empty($_GET['conv'])      ? '&conv='      . rawurlencode($_GET['conv'])      : '')
449                                         . (!empty($_GET['nets'])      ? '&nets='      . rawurlencode($_GET['nets'])      : '')
450                                         . (!empty($_GET['cmin'])      ? '&cmin='      . rawurlencode($_GET['cmin'])      : '')
451                                         . (!empty($_GET['cmax'])      ? '&cmax='      . rawurlencode($_GET['cmax'])      : '')
452                                         . (!empty($_GET['file'])      ? '&file='      . rawurlencode($_GET['file'])      : '')
453
454                                         . "'; </script>\r\n";
455                         }
456                 } elseif ($mode === 'profile') {
457                         $items = $this->addChildren($items, false, $order, local_user());
458
459                         if (!$update) {
460                                 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
461
462                                 if ($tab === 'posts') {
463                                         /*
464                                         * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
465                                         * because browser prefetching might change it on us. We have to deliver it with the page.
466                                         */
467
468                                         $live_update_div = '<div id="live-profile"></div>' . "\r\n"
469                                                 . "<script> var profile_uid = " . $uid
470                                                 . "; var netargs = '?f='; </script>\r\n";
471                                 }
472                         }
473                 } elseif ($mode === 'notes') {
474                         $items = $this->addChildren($items, false, $order, local_user());
475
476                         if (!$update) {
477                                 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
478                                         . "<script> var profile_uid = " . local_user()
479                                         . "; var netargs = '/?f='; </script>\r\n";
480                         }
481                 } elseif ($mode === 'display') {
482                         $items = $this->addChildren($items, false, $order, $uid);
483
484                         if (!$update) {
485                                 $live_update_div = '<div id="live-display"></div>' . "\r\n"
486                                         . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
487                                         . "</script>";
488                         }
489                 } elseif ($mode === 'community') {
490                         $items = $this->addChildren($items, true, $order, $uid);
491
492                         if (!$update) {
493                                 $live_update_div = '<div id="live-community"></div>' . "\r\n"
494                                         . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
495                                         . '?f='
496                                         . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
497                                         . "'; </script>\r\n";
498                         }
499                 } elseif ($mode === 'contacts') {
500                         $items = $this->addChildren($items, false, $order, $uid);
501
502                         if (!$update) {
503                                 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
504                                         . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
505                                         ."/?f='; </script>\r\n";
506                         }
507                 } elseif ($mode === 'search') {
508                         $live_update_div = '<div id="live-search"></div>' . "\r\n";
509                 }
510
511                 $page_dropping = ((local_user() && local_user() == $uid) ? true : false);
512
513                 if (!$update) {
514                         $_SESSION['return_path'] = $this->args->getQueryString();
515                 }
516
517                 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
518                 Hook::callAll('conversation_start', $cb);
519
520                 $items = $cb['items'];
521
522                 $conv_responses = [
523                         'like'        => [],
524                         'dislike'     => [],
525                         'attendyes'   => [],
526                         'attendno'    => [],
527                         'attendmaybe' => [],
528                         'announce'    => [],
529                 ];
530
531                 if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
532                         unset($conv_responses['dislike']);
533                 }
534
535                 // array with html for each thread (parent+comments)
536                 $threads   = [];
537                 $threadsid = -1;
538
539                 $page_template     = Renderer::getMarkupTemplate("conversation.tpl");
540                 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
541
542                 if (!empty($items)) {
543                         if (in_array($mode, ['community', 'contacts', 'profile'])) {
544                                 $writable = true;
545                         } else {
546                                 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
547                         }
548
549                         if (!local_user()) {
550                                 $writable = false;
551                         }
552
553                         if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
554
555                                 /*
556                                 * "New Item View" on network page or search page results
557                                 * - just loop through the items and format them minimally for display
558                                 */
559
560                                 $tpl = 'search_item.tpl';
561
562                                 $uriids = [];
563
564                                 foreach ($items as $item) {
565                                         if (in_array($item['uri-id'], $uriids)) {
566                                                 continue;
567                                         }
568
569                                         $uriids[] = $item['uri-id'];
570
571                                         if (!$this->item->visibleActivity($item)) {
572                                                 continue;
573                                         }
574
575                                         if (in_array($item['author-id'], $blocklist)) {
576                                                 continue;
577                                         }
578
579                                         $threadsid++;
580
581                                         // prevent private email from leaking.
582                                         if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
583                                                 continue;
584                                         }
585
586                                         $profile_name = $item['author-name'];
587                                         if (!empty($item['author-link']) && empty($item['author-name'])) {
588                                                 $profile_name = $item['author-link'];
589                                         }
590
591                                         $tags = Tag::populateFromItem($item);
592
593                                         $author       = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
594                                         $profile_link = Contact::magicLinkByContact($author);
595
596                                         $sparkle = '';
597                                         if (strpos($profile_link, 'redir/') === 0) {
598                                                 $sparkle = ' sparkle';
599                                         }
600
601                                         $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
602                                         Hook::callAll('render_location', $locate);
603                                         $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
604
605                                         $this->item->localize($item);
606                                         if ($mode === 'filed') {
607                                                 $dropping = true;
608                                         } else {
609                                                 $dropping = false;
610                                         }
611
612                                         $drop = [
613                                                 'dropping' => $dropping,
614                                                 'pagedrop' => $page_dropping,
615                                                 'select'   => $this->l10n->t('Select'),
616                                                 'delete'   => $this->l10n->t('Delete'),
617                                         ];
618
619                                         $likebuttons = [
620                                                 'like'     => null,
621                                                 'dislike'  => null,
622                                                 'share'    => null,
623                                                 'announce' => null,
624                                         ];
625
626                                         if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
627                                                 unset($likebuttons['dislike']);
628                                         }
629
630                                         $body_html = ItemModel::prepareBody($item, true, $preview);
631
632                                         [$categories, $folders] = $this->item->determineCategoriesTerms($item, local_user());
633
634                                         if (!empty($item['content-warning']) && $this->pConfig->get(local_user(), 'system', 'disable_cw', false)) {
635                                                 $title = ucfirst($item['content-warning']);
636                                         } else {
637                                                 $title = $item['title'];
638                                         }
639
640                                         $tmp_item = [
641                                                 'template'             => $tpl,
642                                                 'id'                   => ($preview ? 'P0' : $item['id']),
643                                                 'guid'                 => ($preview ? 'Q0' : $item['guid']),
644                                                 'commented'            => $item['commented'],
645                                                 'received'             => $item['received'],
646                                                 'created_date'         => $item['created'],
647                                                 'uriid'                => $item['uri-id'],
648                                                 'network'              => $item['network'],
649                                                 'network_name'         => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
650                                                 'network_icon'         => ContactSelector::networkToIcon($item['network'], $item['author-link']),
651                                                 'linktitle'            => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
652                                                 'profile_url'          => $profile_link,
653                                                 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
654                                                 'name'                 => $profile_name,
655                                                 'sparkle'              => $sparkle,
656                                                 'lock'                 => false,
657                                                 'thumb'                => $this->baseURL->remove(Contact::getAvatarUrlForUrl($item['author-link'], $item['uid'], Proxy::SIZE_THUMB)),
658                                                 'title'                => $title,
659                                                 'body_html'            => $body_html,
660                                                 'tags'                 => $tags['tags'],
661                                                 'hashtags'             => $tags['hashtags'],
662                                                 'mentions'             => $tags['mentions'],
663                                                 'implicit_mentions'    => $tags['implicit_mentions'],
664                                                 'txt_cats'             => $this->l10n->t('Categories:'),
665                                                 'txt_folders'          => $this->l10n->t('Filed under:'),
666                                                 'has_cats'             => ((count($categories)) ? 'true' : ''),
667                                                 'has_folders'          => ((count($folders)) ? 'true' : ''),
668                                                 'categories'           => $categories,
669                                                 'folders'              => $folders,
670                                                 'text'                 => strip_tags($body_html),
671                                                 'localtime'            => DateTimeFormat::local($item['created'], 'r'),
672                                                 'utc'                  => DateTimeFormat::utc($item['created'], 'c'),
673                                                 'ago'                  => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
674                                                 'location_html'        => $location_html,
675                                                 'indent'               => '',
676                                                 'owner_name'           => '',
677                                                 'owner_url'            => '',
678                                                 'owner_photo'          => $this->baseURL->remove(Contact::getAvatarUrlForUrl($item['owner-link'], $item['uid'], Proxy::SIZE_THUMB)),
679                                                 'plink'                => ItemModel::getPlink($item),
680                                                 'edpost'               => false,
681                                                 'isstarred'            => 'unstarred',
682                                                 'star'                 => false,
683                                                 'drop'                 => $drop,
684                                                 'vote'                 => $likebuttons,
685                                                 'like_html'            => '',
686                                                 'dislike_html '        => '',
687                                                 'comment_html'         => '',
688                                                 'conv'                 => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
689                                                 'previewing'           => $previewing,
690                                                 'wait'                 => $this->l10n->t('Please wait'),
691                                                 'thread_level'         => 1,
692                                         ];
693
694                                         $arr = ['item' => $item, 'output' => $tmp_item];
695                                         Hook::callAll('display_item', $arr);
696
697                                         $threads[$threadsid]['id']      = $item['id'];
698                                         $threads[$threadsid]['network'] = $item['network'];
699                                         $threads[$threadsid]['items']   = [$arr['output']];
700                                 }
701                         } else {
702                                 // Normal View
703                                 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
704
705                                 $conv = new Thread($mode, $preview, $writable);
706
707                                 /*
708                                 * get all the topmost parents
709                                 * this shouldn't be needed, as we should have only them in our array
710                                 * But for now, this array respects the old style, just in case
711                                 */
712                                 foreach ($items as $item) {
713                                         if (in_array($item['author-id'], $blocklist)) {
714                                                 continue;
715                                         }
716
717                                         // Can we put this after the visibility check?
718                                         $this->builtinActivityPuller($item, $conv_responses);
719
720                                         // Only add what is visible
721                                         if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
722                                                 continue;
723                                         }
724
725                                         if (!$this->item->visibleActivity($item)) {
726                                                 continue;
727                                         }
728
729                                         /// @todo Check if this call is needed or not
730                                         $arr = ['item' => $item];
731                                         Hook::callAll('display_item', $arr);
732
733                                         $item['pagedrop'] = $page_dropping;
734
735                                         if ($item['gravity'] == GRAVITY_PARENT) {
736                                                 $item_object = new PostObject($item);
737                                                 $conv->addParent($item_object);
738                                         }
739                                 }
740
741                                 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
742                                 if (!$threads) {
743                                         $this->logger->info('[ERROR] conversation : Failed to get template data.');
744                                         $threads = [];
745                                 }
746                         }
747                 }
748
749                 $o = Renderer::replaceMacros($page_template, [
750                         '$baseurl'     => $this->baseURL->get($ssl_state),
751                         '$return_path' => $this->args->getQueryString(),
752                         '$live_update' => $live_update_div,
753                         '$remove'      => $this->l10n->t('remove'),
754                         '$mode'        => $mode,
755                         '$update'      => $update,
756                         '$threads'     => $threads,
757                         '$dropping'    => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
758                 ]);
759
760                 $this->profiler->stopRecording();
761                 return $o;
762         }
763
764         private function getBlocklist()
765         {
766                 if (!local_user()) {
767                         return [];
768                 }
769
770                 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get(local_user(), 'system', 'blocked'));
771                 if (empty($str_blocked)) {
772                         return [];
773                 }
774
775                 $blocklist = [];
776
777                 foreach (explode(',', $str_blocked) as $entry) {
778                         $cid = Contact::getIdForURL(trim($entry), 0, false);
779                         if (!empty($cid)) {
780                                 $blocklist[] = $cid;
781                         }
782                 }
783
784                 return $blocklist;
785         }
786
787         /**
788          * Adds some information (Causer, post reason, direction) to the fetched post row.
789          *
790          * @param array   $row      Post row
791          * @param array   $activity Contact data of the resharer
792          *
793          * @return array items with parents and comments
794          */
795         private function addRowInformation(array $row, array $activity)
796         {
797                 $this->profiler->startRecording('rendering');
798
799                 if ($row['uid'] == 0) {
800                         $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
801                 }
802
803                 if (!empty($activity)) {
804                         if (($row['gravity'] == GRAVITY_PARENT)) {
805                                 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
806
807                                 $row     = array_merge($row, $activity);
808                                 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
809
810                                 $row['causer-link']   = $contact['url'];
811                                 $row['causer-avatar'] = $contact['thumb'];
812                                 $row['causer-name']   = $contact['name'];
813                         } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
814                                 ($row['author-id'] == $activity['causer-id'])) {
815                                 return $row;
816                         }
817                 }
818
819                 switch ($row['post-reason']) {
820                         case ItemModel::PR_TO:
821                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
822                                 break;
823                         case ItemModel::PR_CC:
824                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
825                                 break;
826                         case ItemModel::PR_BTO:
827                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
828                                 break;
829                         case ItemModel::PR_BCC:
830                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
831                                 break;
832                         case ItemModel::PR_FOLLOWER:
833                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['author-name'])];
834                                 break;
835                         case ItemModel::PR_TAG:
836                                 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('Tagged')];
837                                 break;
838                         case ItemModel::PR_ANNOUNCEMENT:
839                                 if (!empty($row['causer-id']) && $this->pConfig->get(local_user(), 'system', 'display_resharer')) {
840                                         $row['owner-id']     = $row['causer-id'];
841                                         $row['owner-link']   = $row['causer-link'];
842                                         $row['owner-avatar'] = $row['causer-avatar'];
843                                         $row['owner-name']   = $row['causer-name'];
844                                 }
845
846                                 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
847                                         $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
848
849                                         $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
850                                 }
851                                 $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']))];
852                                 break;
853                         case ItemModel::PR_COMMENT:
854                                 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
855                                 break;
856                         case ItemModel::PR_STORED:
857                                 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored')];
858                                 break;
859                         case ItemModel::PR_GLOBAL:
860                                 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global')];
861                                 break;
862                         case ItemModel::PR_RELAY:
863                                 $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']))];
864                                 break;
865                         case ItemModel::PR_FETCHED:
866                                 $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']))];
867                                 break;
868                 }
869
870                 $this->profiler->stopRecording();
871                 return $row;
872         }
873
874         /**
875          * Add comments to top level entries that had been fetched before
876          *
877          * The system will fetch the comments for the local user whenever possible.
878          * This behaviour is currently needed to allow commenting on Friendica posts.
879          *
880          * @param array $parents Parent items
881          *
882          * @param       $block_authors
883          * @param       $order
884          * @param       $uid
885          * @return array items with parents and comments
886          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
887          */
888         private function addChildren(array $parents, $block_authors, $order, $uid)
889         {
890                 $this->profiler->startRecording('rendering');
891                 if (count($parents) > 1) {
892                         $max_comments = $this->config->get('system', 'max_comments', 100);
893                 } else {
894                         $max_comments = $this->config->get('system', 'max_display_comments', 1000);
895                 }
896
897                 $params = ['order' => ['uri-id' => true, 'uid' => true]];
898
899                 $activities      = [];
900                 $uriids          = [];
901                 $commentcounter  = [];
902                 $activitycounter = [];
903
904                 foreach ($parents as $parent) {
905                         if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
906                                 $uriid = $parent['thr-parent-id'];
907                                 if (!empty($parent['author-id'])) {
908                                         $activities[$uriid] = ['causer-id' => $parent['author-id']];
909                                         foreach (['commented', 'received', 'created'] as $orderfields) {
910                                                 if (!empty($parent[$orderfields])) {
911                                                         $activities[$uriid][$orderfields] = $parent[$orderfields];
912                                                 }
913                                         }
914                                 }
915                         } else {
916                                 $uriid = $parent['uri-id'];
917                         }
918                         $uriids[] = $uriid;
919
920                         $commentcounter[$uriid]  = 0;
921                         $activitycounter[$uriid] = 0;
922                 }
923
924                 $condition = ['parent-uri-id' => $uriids];
925                 if ($block_authors) {
926                         $condition['author-hidden'] = false;
927                 }
928
929                 $condition = DBA::mergeConditions($condition,
930                         ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
931
932                 $thread_items = Post::selectForUser(local_user(), array_merge(ItemModel::DISPLAY_FIELDLIST, ['pinned', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
933
934                 $items = [];
935
936                 while ($row = Post::fetch($thread_items)) {
937                         if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
938                                 continue;
939                         }
940
941                         if ($max_comments > 0) {
942                                 if (($row['gravity'] == GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
943                                         continue;
944                                 }
945                                 if (($row['gravity'] == GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
946                                         continue;
947                                 }
948                         }
949                         $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? []);
950                 }
951
952                 DBA::close($thread_items);
953
954                 $items = $this->convSort($items, $order);
955
956                 $this->profiler->stopRecording();
957                 return $items;
958         }
959
960         /**
961          * Plucks the children of the given parent from a given item list.
962          *
963          * @param array $item_list
964          * @param array $parent
965          * @param bool  $recursive
966          * @return array
967          */
968         private function getItemChildren(array &$item_list, array $parent, $recursive = true)
969         {
970                 $this->profiler->startRecording('rendering');
971                 $children = [];
972                 foreach ($item_list as $i => $item) {
973                         if ($item['gravity'] != GRAVITY_PARENT) {
974                                 if ($recursive) {
975                                         // Fallback to parent-uri if thr-parent is not set
976                                         $thr_parent = $item['thr-parent-id'];
977                                         if ($thr_parent == '') {
978                                                 $thr_parent = $item['parent-uri-id'];
979                                         }
980
981                                         if ($thr_parent == $parent['uri-id']) {
982                                                 $item['children'] = $this->getItemChildren($item_list, $item);
983
984                                                 $children[] = $item;
985                                                 unset($item_list[$i]);
986                                         }
987                                 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
988                                         $children[] = $item;
989                                         unset($item_list[$i]);
990                                 }
991                         }
992                 }
993                 $this->profiler->stopRecording();
994                 return $children;
995         }
996
997         /**
998          * Recursively sorts a tree-like item array
999          *
1000          * @param array $items
1001          * @return array
1002          */
1003         private function sortItemChildren(array $items)
1004         {
1005                 $this->profiler->startRecording('rendering');
1006                 $result = $items;
1007                 usort($result, [$this, 'sortThrReceivedRev']);
1008                 foreach ($result as $k => $i) {
1009                         if (isset($result[$k]['children'])) {
1010                                 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1011                         }
1012                 }
1013                 $this->profiler->stopRecording();
1014                 return $result;
1015         }
1016
1017         /**
1018          * Recursively add all children items at the top level of a list
1019          *
1020          * @param array $children List of items to append
1021          * @param array $item_list
1022          */
1023         private function addChildrenToList(array $children, array &$item_list)
1024         {
1025                 foreach ($children as $child) {
1026                         $item_list[] = $child;
1027                         if (isset($child['children'])) {
1028                                 $this->addChildrenToList($child['children'], $item_list);
1029                         }
1030                 }
1031         }
1032
1033         /**
1034          * Selectively flattens a tree-like item structure to prevent threading stairs
1035          *
1036          * This recursive function takes the item tree structure created by conv_sort() and
1037          * flatten the extraneous depth levels when people reply sequentially, removing the
1038          * stairs effect in threaded conversations limiting the available content width.
1039          *
1040          * The basic principle is the following: if a post item has only one reply and is
1041          * the last reply of its parent, then the reply is moved to the parent.
1042          *
1043          * This process is rendered somewhat more complicated because items can be either
1044          * replies or likes, and these don't factor at all in the reply count/last reply.
1045          *
1046          * @param array $parent A tree-like array of items
1047          * @return array
1048          */
1049         private function smartFlattenConversation(array $parent)
1050         {
1051                 $this->profiler->startRecording('rendering');
1052                 if (!isset($parent['children']) || count($parent['children']) == 0) {
1053                         $this->profiler->stopRecording();
1054                         return $parent;
1055                 }
1056
1057                 // We use a for loop to ensure we process the newly-moved items
1058                 for ($i = 0; $i < count($parent['children']); $i++) {
1059                         $child = $parent['children'][$i];
1060
1061                         if (isset($child['children']) && count($child['children'])) {
1062                                 // This helps counting only the regular posts
1063                                 $count_post_closure = function ($var) {
1064                                         $this->profiler->stopRecording();
1065                                         return $var['verb'] === Activity::POST;
1066                                 };
1067
1068                                 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1069
1070                                 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1071
1072                                 // If there's only one child's children post and this is the last child post
1073                                 if ($child_post_count == 1 && $remaining_post_count == 1) {
1074
1075                                         // Searches the post item in the children
1076                                         $j = 0;
1077                                         while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1078                                                 $j ++;
1079                                         }
1080
1081                                         $moved_item = $child['children'][$j];
1082                                         unset($parent['children'][$i]['children'][$j]);
1083                                         $parent['children'][] = $moved_item;
1084                                 } else {
1085                                         $parent['children'][$i] = $this->smartFlattenConversation($child);
1086                                 }
1087                         }
1088                 }
1089
1090                 $this->profiler->stopRecording();
1091                 return $parent;
1092         }
1093
1094         /**
1095          * Expands a flat list of items into corresponding tree-like conversation structures.
1096          *
1097          * sort the top-level posts either on "received" or "commented", and finally
1098          * append all the items at the top level (???)
1099          *
1100          * @param array  $item_list A list of items belonging to one or more conversations
1101          * @param string $order     Either on "received" or "commented"
1102          * @return array
1103          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1104          */
1105         private function convSort(array $item_list, $order)
1106         {
1107                 $this->profiler->startRecording('rendering');
1108                 $parents = [];
1109
1110                 if (!(is_array($item_list) && count($item_list))) {
1111                         $this->profiler->stopRecording();
1112                         return $parents;
1113                 }
1114
1115                 $blocklist = $this->getBlocklist();
1116
1117                 $item_array = [];
1118
1119                 // Dedupes the item list on the uri to prevent infinite loops
1120                 foreach ($item_list as $item) {
1121                         if (in_array($item['author-id'], $blocklist)) {
1122                                 continue;
1123                         }
1124
1125                         $item_array[$item['uri-id']] = $item;
1126                 }
1127
1128                 // Extract the top level items
1129                 foreach ($item_array as $item) {
1130                         if ($item['gravity'] == GRAVITY_PARENT) {
1131                                 $parents[] = $item;
1132                         }
1133                 }
1134
1135                 if (stristr($order, 'pinned_received')) {
1136                         usort($parents, [$this, 'sortThrPinnedReceived']);
1137                 } elseif (stristr($order, 'received')) {
1138                         usort($parents, [$this, 'sortThrReceived']);
1139                 } elseif (stristr($order, 'commented')) {
1140                         usort($parents, [$this, 'sortThrCommented']);
1141                 }
1142
1143                 /*
1144                 * Plucks children from the item_array, second pass collects eventual orphan
1145                 * items and add them as children of their top-level post.
1146                 */
1147                 foreach ($parents as $i => $parent) {
1148                         $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1149                                 $this->getItemChildren($item_array, $parent, false));
1150                 }
1151
1152                 foreach ($parents as $i => $parent) {
1153                         $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1154                 }
1155
1156                 if (!$this->pConfig->get(local_user(), 'system', 'no_smart_threading', 0)) {
1157                         foreach ($parents as $i => $parent) {
1158                                 $parents[$i] = $this->smartFlattenConversation($parent);
1159                         }
1160                 }
1161
1162                 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1163                 /// However, this apparently ensures responses (likes, attendance) display (?!)
1164                 foreach ($parents as $parent) {
1165                         if (count($parent['children'])) {
1166                                 $this->addChildrenToList($parent['children'], $parents);
1167                         }
1168                 }
1169
1170                 $this->profiler->stopRecording();
1171                 return $parents;
1172         }
1173
1174         /**
1175          * usort() callback to sort item arrays by pinned and the received key
1176          *
1177          * @param array $a
1178          * @param array $b
1179          * @return int
1180          */
1181         private function sortThrPinnedReceived(array $a, array $b)
1182         {
1183                 if ($b['pinned'] && !$a['pinned']) {
1184                         return 1;
1185                 } elseif (!$b['pinned'] && $a['pinned']) {
1186                         return -1;
1187                 }
1188
1189                 return strcmp($b['received'], $a['received']);
1190         }
1191
1192         /**
1193          * usort() callback to sort item arrays by the received key
1194          *
1195          * @param array $a
1196          * @param array $b
1197          * @return int
1198          */
1199         private function sortThrReceived(array $a, array $b)
1200         {
1201                 return strcmp($b['received'], $a['received']);
1202         }
1203
1204         /**
1205          * usort() callback to reverse sort item arrays by the received key
1206          *
1207          * @param array $a
1208          * @param array $b
1209          * @return int
1210          */
1211         private function sortThrReceivedRev(array $a, array $b)
1212         {
1213                 return strcmp($a['received'], $b['received']);
1214         }
1215
1216         /**
1217          * usort() callback to sort item arrays by the commented key
1218          *
1219          * @param array $a
1220          * @param array $b
1221          * @return int
1222          */
1223         private function sortThrCommented(array $a, array $b)
1224         {
1225                 return strcmp($b['commented'], $a['commented']);
1226         }
1227 }