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