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