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