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