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