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