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