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