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