]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Remove unused cached avatar photo entries
[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                 $cid = Contact::getIdForURL(trim($entry), 0, false);
328                 if (!empty($cid)) {
329                         $blocklist[] = $cid;
330                 }
331         }
332
333         return $blocklist;
334 }
335
336 /**
337  * "Render" a conversation or list of items for HTML display.
338  * There are two major forms of display:
339  *      - Sequential or unthreaded ("New Item View" or search results)
340  *      - conversation view
341  * The $mode parameter decides between the various renderings and also
342  * figures out how to determine page owner and other contextual items
343  * that are based on unique features of the calling module.
344  * @param App    $a
345  * @param array  $items
346  * @param        $mode
347  * @param        $update
348  * @param bool   $preview
349  * @param string $order
350  * @param int    $uid
351  * @return string
352  * @throws ImagickException
353  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
354  */
355 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
356 {
357         $page = DI::page();
358
359         $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
360         $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
361         $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
362         $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
363
364         $ssl_state = (local_user() ? true : false);
365
366         $profile_owner = 0;
367         $live_update_div = '';
368
369         $blocklist = conv_get_blocklist();
370
371         $previewing = (($preview) ? ' preview ' : '');
372
373         if ($mode === 'network') {
374                 $items = conversation_add_children($items, false, $order, $uid);
375                 $profile_owner = local_user();
376                 if (!$update) {
377                         /*
378                          * The special div is needed for liveUpdate to kick in for this page.
379                          * We only launch liveUpdate if you aren't filtering in some incompatible
380                          * way and also you aren't writing a comment (discovered in javascript).
381                          */
382                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
383                                 . "<script> var profile_uid = " . $_SESSION['uid']
384                                 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
385                                 . '?f='
386                                 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
387                                 . (!empty($_GET['search'])    ? '&search='    . rawurlencode($_GET['search'])    : '')
388                                 . (!empty($_GET['star'])      ? '&star='      . rawurlencode($_GET['star'])      : '')
389                                 . (!empty($_GET['order'])     ? '&order='     . rawurlencode($_GET['order'])     : '')
390                                 . (!empty($_GET['bmark'])     ? '&bmark='     . rawurlencode($_GET['bmark'])     : '')
391                                 . (!empty($_GET['liked'])     ? '&liked='     . rawurlencode($_GET['liked'])     : '')
392                                 . (!empty($_GET['conv'])      ? '&conv='      . rawurlencode($_GET['conv'])      : '')
393                                 . (!empty($_GET['nets'])      ? '&nets='      . rawurlencode($_GET['nets'])      : '')
394                                 . (!empty($_GET['cmin'])      ? '&cmin='      . rawurlencode($_GET['cmin'])      : '')
395                                 . (!empty($_GET['cmax'])      ? '&cmax='      . rawurlencode($_GET['cmax'])      : '')
396                                 . (!empty($_GET['file'])      ? '&file='      . rawurlencode($_GET['file'])      : '')
397
398                                 . "'; </script>\r\n";
399                 }
400         } elseif ($mode === 'profile') {
401                 $items = conversation_add_children($items, false, $order, $uid);
402                 $profile_owner = $a->profile['uid'];
403
404                 if (!$update) {
405                         $tab = 'posts';
406                         if (!empty($_GET['tab'])) {
407                                 $tab = Strings::escapeTags(trim($_GET['tab']));
408                         }
409                         if ($tab === 'posts') {
410                                 /*
411                                  * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
412                                  * because browser prefetching might change it on us. We have to deliver it with the page.
413                                  */
414
415                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
416                                         . "<script> var profile_uid = " . $a->profile['uid']
417                                         . "; var netargs = '?f='; </script>\r\n";
418                         }
419                 }
420         } elseif ($mode === 'notes') {
421                 $items = conversation_add_children($items, false, $order, local_user());
422                 $profile_owner = local_user();
423
424                 if (!$update) {
425                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
426                                 . "<script> var profile_uid = " . local_user()
427                                 . "; var netargs = '/?f='; </script>\r\n";
428                 }
429         } elseif ($mode === 'display') {
430                 $items = conversation_add_children($items, false, $order, $uid);
431                 $profile_owner = $a->profile['uid'];
432
433                 if (!$update) {
434                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
435                                 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
436                                 . "</script>";
437                 }
438         } elseif ($mode === 'community') {
439                 $items = conversation_add_children($items, true, $order, $uid);
440                 $profile_owner = 0;
441
442                 if (!$update) {
443                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
444                                 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
445                                 . '?f='
446                                 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
447                                 . "'; </script>\r\n";
448                 }
449         } elseif ($mode === 'contacts') {
450                 $items = conversation_add_children($items, false, $order, $uid);
451                 $profile_owner = 0;
452
453                 if (!$update) {
454                         $live_update_div = '<div id="live-contact"></div>' . "\r\n"
455                                 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 8)
456                                 ."/?f='; </script>\r\n";
457                 }
458         } elseif ($mode === 'search') {
459                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
460         }
461
462         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
463
464         if (!$update) {
465                 $_SESSION['return_path'] = DI::args()->getQueryString();
466         }
467
468         $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
469         Hook::callAll('conversation_start', $cb);
470
471         $items = $cb['items'];
472
473         $conv_responses = [
474                 'like'        => [],
475                 'dislike'     => [],
476                 'attendyes'   => [],
477                 'attendno'    => [],
478                 'attendmaybe' => [],
479                 'announce'    => [],    
480         ];
481
482         if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
483                 unset($conv_responses['dislike']);
484         }
485
486         // array with html for each thread (parent+comments)
487         $threads = [];
488         $threadsid = -1;
489
490         $page_template = Renderer::getMarkupTemplate("conversation.tpl");
491
492         if (!empty($items)) {
493                 if (in_array($mode, ['community', 'contacts'])) {
494                         $writable = true;
495                 } else {
496                         $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
497                 }
498
499                 if (!local_user()) {
500                         $writable = false;
501                 }
502
503                 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
504
505                         /*
506                          * "New Item View" on network page or search page results
507                          * - just loop through the items and format them minimally for display
508                          */
509
510                         $tpl = 'search_item.tpl';
511
512                         foreach ($items as $item) {
513
514                                 if (!visible_activity($item)) {
515                                         continue;
516                                 }
517
518                                 if (in_array($item['author-id'], $blocklist)) {
519                                         continue;
520                                 }
521
522                                 $threadsid++;
523
524                                 // prevent private email from leaking.
525                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
526                                         continue;
527                                 }
528
529                                 $profile_name = $item['author-name'];
530                                 if (!empty($item['author-link']) && empty($item['author-name'])) {
531                                         $profile_name = $item['author-link'];
532                                 }
533
534                                 $tags = Tag::populateFromItem($item);
535
536                                 $author = ['uid' => 0, 'id' => $item['author-id'],
537                                         'network' => $item['author-network'], 'url' => $item['author-link']];
538                                 $profile_link = Contact::magicLinkByContact($author);
539
540                                 $sparkle = '';
541                                 if (strpos($profile_link, 'redir/') === 0) {
542                                         $sparkle = ' sparkle';
543                                 }
544
545                                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
546                                 Hook::callAll('render_location', $locate);
547                                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
548
549                                 localize_item($item);
550                                 if ($mode === 'filed') {
551                                         $dropping = true;
552                                 } else {
553                                         $dropping = false;
554                                 }
555
556                                 $drop = [
557                                         'dropping' => $dropping,
558                                         'pagedrop' => $page_dropping,
559                                         'select' => DI::l10n()->t('Select'),
560                                         'delete' => DI::l10n()->t('Delete'),
561                                 ];
562
563                                 $likebuttons = [
564                                         'like'     => null,
565                                         'dislike'  => null,
566                                         'share'    => null,
567                                         'announce' => null,
568                                 ];
569
570                                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
571                                         unset($likebuttons['dislike']);
572                                 }
573
574                                 $body_html = Item::prepareBody($item, true, $preview);
575
576                                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
577
578                                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
579                                         $title = ucfirst($item['content-warning']);
580                                 } else {
581                                         $title = $item['title'];
582                                 }
583
584                                 $tmp_item = [
585                                         'template' => $tpl,
586                                         'id' => ($preview ? 'P0' : $item['id']),
587                                         'guid' => ($preview ? 'Q0' : $item['guid']),
588                                         'commented' => $item['commented'],
589                                         'received' => $item['received'],
590                                         'created_date' => $item['created'],
591                                         'uriid' => $item['uri-id'],
592                                         'network' => $item['network'],
593                                         'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
594                                         'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
595                                         'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
596                                         'profile_url' => $profile_link,
597                                         'item_photo_menu_html' => item_photo_menu($item),
598                                         'name' => $profile_name,
599                                         'sparkle' => $sparkle,
600                                         'lock' => false,
601                                         'thumb' => DI::baseUrl()->remove($item['author-avatar']),
602                                         'title' => $title,
603                                         'body_html' => $body_html,
604                                         'tags' => $tags['tags'],
605                                         'hashtags' => $tags['hashtags'],
606                                         'mentions' => $tags['mentions'],
607                                         'implicit_mentions' => $tags['implicit_mentions'],
608                                         'txt_cats' => DI::l10n()->t('Categories:'),
609                                         'txt_folders' => DI::l10n()->t('Filed under:'),
610                                         'has_cats' => ((count($categories)) ? 'true' : ''),
611                                         'has_folders' => ((count($folders)) ? 'true' : ''),
612                                         'categories' => $categories,
613                                         'folders' => $folders,
614                                         'text' => strip_tags($body_html),
615                                         'localtime' => DateTimeFormat::local($item['created'], 'r'),
616                                         'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
617                                         'location_html' => $location_html,
618                                         'indent' => '',
619                                         'owner_name' => '',
620                                         'owner_url' => '',
621                                         'owner_photo' => DI::baseUrl()->remove($item['owner-avatar']),
622                                         'plink' => Item::getPlink($item),
623                                         'edpost' => false,
624                                         'isstarred' => 'unstarred',
625                                         'star' => false,
626                                         'drop' => $drop,
627                                         'vote' => $likebuttons,
628                                         'like_html' => '',
629                                         'dislike_html' => '',
630                                         'comment_html' => '',
631                                         'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
632                                         'previewing' => $previewing,
633                                         'wait' => DI::l10n()->t('Please wait'),
634                                         'thread_level' => 1,
635                                 ];
636
637                                 $arr = ['item' => $item, 'output' => $tmp_item];
638                                 Hook::callAll('display_item', $arr);
639
640                                 $threads[$threadsid]['id'] = $item['id'];
641                                 $threads[$threadsid]['network'] = $item['network'];
642                                 $threads[$threadsid]['items'] = [$arr['output']];
643
644                         }
645                 } else {
646                         // Normal View
647                         $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
648
649                         $conv = new Thread($mode, $preview, $writable);
650
651                         /*
652                          * get all the topmost parents
653                          * this shouldn't be needed, as we should have only them in our array
654                          * But for now, this array respects the old style, just in case
655                          */
656                         foreach ($items as $item) {
657                                 if (in_array($item['author-id'], $blocklist)) {
658                                         continue;
659                                 }
660
661                                 // Can we put this after the visibility check?
662                                 builtin_activity_puller($item, $conv_responses);
663
664                                 // Only add what is visible
665                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
666                                         continue;
667                                 }
668
669                                 if (!visible_activity($item)) {
670                                         continue;
671                                 }
672
673                                 /// @todo Check if this call is needed or not
674                                 $arr = ['item' => $item];
675                                 Hook::callAll('display_item', $arr);
676
677                                 $item['pagedrop'] = $page_dropping;
678
679                                 if ($item['gravity'] == GRAVITY_PARENT) {
680                                         $item_object = new Post($item);
681                                         $conv->addParent($item_object);
682                                 }
683                         }
684
685                         $threads = $conv->getTemplateData($conv_responses);
686                         if (!$threads) {
687                                 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
688                                 $threads = [];
689                         }
690                 }
691         }
692
693         $o = Renderer::replaceMacros($page_template, [
694                 '$baseurl' => DI::baseUrl()->get($ssl_state),
695                 '$return_path' => DI::args()->getQueryString(),
696                 '$live_update' => $live_update_div,
697                 '$remove' => DI::l10n()->t('remove'),
698                 '$mode' => $mode,
699                 '$update' => $update,
700                 '$user' => $a->user,
701                 '$threads' => $threads,
702                 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
703         ]);
704
705         return $o;
706 }
707
708 /**
709  * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
710  *
711  * @param mixed   $thread_items Database statement with thread posts
712  * @param boolean $pinned       Is the item pinned?
713  * @param array   $activity     Contact data of the resharer
714  *
715  * @return array items with parents and comments
716  */
717 function conversation_fetch_comments($thread_items, bool $pinned, array $activity) {
718         $comments = [];
719
720         while ($row = Item::fetch($thread_items)) {
721                 if (!empty($activity)) {
722                         if (($row['gravity'] == GRAVITY_PARENT)) {
723                                 $row['post-type'] = Item::PT_ANNOUNCEMENT;
724                                 $row = array_merge($row, $activity);
725                                 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
726                                 $row['causer-link'] = $contact['url'];
727                                 $row['causer-avatar'] = $contact['thumb'];
728                                 $row['causer-name'] = $contact['name'];
729                         } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
730                                 ($row['author-id'] == $activity['causer-id'])) {
731                                 continue;
732                         }
733                 }
734
735                 $name = $row['causer-contact-type'] == Contact::TYPE_RELAY ? $row['causer-link'] : $row['causer-name'];
736
737                 switch ($row['post-type']) {
738                         case Item::PT_TO:
739                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
740                                 break;
741                         case Item::PT_CC:
742                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
743                                 break;
744                         case Item::PT_BTO:
745                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
746                                 break;
747                         case Item::PT_BCC:
748                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
749                                 break;
750                         case Item::PT_FOLLOWER:
751                                 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
752                                 break;
753                         case Item::PT_TAG:
754                                 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
755                                 break;
756                         case Item::PT_ANNOUNCEMENT:
757                                 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
758                                         $row['owner-id'] = $row['causer-id'];
759                                         $row['owner-link'] = $row['causer-link'];
760                                         $row['owner-avatar'] = $row['causer-avatar'];
761                                         $row['owner-name'] = $row['causer-name'];
762                                 }
763
764                                 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
765                                         $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkbyId($row['causer-id'])) .'">' . htmlentities($name) . '</a>');
766                                 }
767                                 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Reshared') : DI::l10n()->t('Reshared by %s', $name))];
768                                 break;
769                         case Item::PT_COMMENT:
770                                 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
771                                 break;
772                         case Item::PT_STORED:
773                                 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
774                                 break;
775                         case Item::PT_GLOBAL:
776                                 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
777                                 break;
778                         case Item::PT_RELAY:
779                                 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Relayed') : DI::l10n()->t('Relayed by %s.', $name))];
780                                 break;
781                         case Item::PT_FETCHED:
782                                 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Fetched') : DI::l10n()->t('Fetched because of %s', $name))];
783                                 break;
784                         }
785
786                 if ($row['gravity'] == GRAVITY_PARENT) {
787                         $row['pinned'] = $pinned;
788                 }
789
790                 $comments[] = $row;
791         }
792
793         DBA::close($thread_items);
794
795         return $comments;
796 }
797
798 /**
799  * Add comments to top level entries that had been fetched before
800  *
801  * The system will fetch the comments for the local user whenever possible.
802  * This behaviour is currently needed to allow commenting on Friendica posts.
803  *
804  * @param array $parents Parent items
805  *
806  * @param       $block_authors
807  * @param       $order
808  * @param       $uid
809  * @return array items with parents and comments
810  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
811  */
812 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
813         if (count($parents) > 1) {
814                 $max_comments = DI::config()->get('system', 'max_comments', 100);
815         } else {
816                 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
817         }
818
819         $params = ['order' => ['gravity', 'uid', 'commented' => true]];
820
821         if ($max_comments > 0) {
822                 $params['limit'] = $max_comments;
823         }
824
825         $items = [];
826
827         foreach ($parents AS $parent) {
828                 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
829                         $condition = ["`item`.`parent-uri-id` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
830                                 $parent['thr-parent-id'], $uid, Verb::getID(Activity::FOLLOW)];
831                         if (!empty($parent['author-id'])) {
832                                 $activity = ['causer-id' => $parent['author-id']];
833                                 foreach (['commented', 'received', 'created'] as $orderfields) {
834                                         if (!empty($parent[$orderfields])) {
835                                                 $activity[$orderfields] = $parent[$orderfields];        
836                                         }       
837                                 }
838                         }
839                 } else {
840                         $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
841                                 $parent['uri'], $uid, Verb::getID(Activity::FOLLOW)];
842                         $activity = [];
843                 }
844                 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params, $activity);
845         }
846
847         foreach ($items as $index => $item) {
848                 if ($item['uid'] == 0) {
849                         $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
850                 }
851         }
852
853         $items = conv_sort($items, $order);
854
855         return $items;
856 }
857
858 /**
859  * Fetch conversation items
860  *
861  * @param array   $parent        Parent Item array
862  * @param array   $items         Item array
863  * @param array   $condition     SQL condition
864  * @param boolean $block_authors Don't show posts from contacts that are hidden (used on the community page)
865  * @param array   $params        SQL parameters
866  * @param array   $activity      Contact data of the resharer
867  * @return array
868  */
869 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params, array $activity) {
870         if ($block_authors) {
871                 $condition[0] .= " AND NOT `author`.`hidden`";
872         }
873
874         $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['contact-uid', 'gravity', 'post-type']), $condition, $params);
875
876         $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false, $activity);
877
878         if (count($comments) != 0) {
879                 $items = array_merge($items, $comments);
880         }
881         return $items;
882 }
883
884 function item_photo_menu($item) {
885         $sub_link = '';
886         $poke_link = '';
887         $contact_url = '';
888         $pm_url = '';
889         $status_link = '';
890         $photos_link = '';
891         $posts_link = '';
892         $block_link = '';
893         $ignore_link = '';
894
895         if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self']) {
896                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
897         }
898
899         $author = ['uid' => 0, 'id' => $item['author-id'],
900                 'network' => $item['author-network'], 'url' => $item['author-link']];
901         $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
902         $sparkle = (strpos($profile_link, 'redir/') === 0);
903
904         $cid = 0;
905         $pcid = Contact::getIdForURL($item['author-link'], 0, false);
906         $network = '';
907         $rel = 0;
908         $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
909         $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
910         if (DBA::isResult($contact)) {
911                 $cid = $contact['id'];
912                 $network = $contact['network'];
913                 $rel = $contact['rel'];
914         }
915
916         if ($sparkle) {
917                 $status_link = $profile_link . '/status';
918                 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
919                 $profile_link = $profile_link . '/profile';
920         }
921
922         if (!empty($pcid)) {
923                 $contact_url = 'contact/' . $pcid;
924                 $posts_link  = $contact_url . '/posts';
925                 $block_link  = $contact_url . '/block';
926                 $ignore_link = $contact_url . '/ignore';
927         }
928
929         if ($cid && !$item['self']) {
930                 $contact_url = 'contact/' . $cid;
931                 $poke_link   = $contact_url . '/poke';
932                 $posts_link  = $contact_url . '/posts';
933
934                 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
935                         $pm_url = 'message/new/' . $cid;
936                 }
937         }
938
939         if (local_user()) {
940                 $menu = [
941                         DI::l10n()->t('Follow Thread') => $sub_link,
942                         DI::l10n()->t('View Status') => $status_link,
943                         DI::l10n()->t('View Profile') => $profile_link,
944                         DI::l10n()->t('View Photos') => $photos_link,
945                         DI::l10n()->t('Network Posts') => $posts_link,
946                         DI::l10n()->t('View Contact') => $contact_url,
947                         DI::l10n()->t('Send PM') => $pm_url,
948                         DI::l10n()->t('Block') => $block_link,
949                         DI::l10n()->t('Ignore') => $ignore_link
950                 ];
951
952                 if (!empty($item['language'])) {
953                         $menu[DI::l10n()->t('Languages')] = 'javascript:alert(\'' . Item::getLanguageMessage($item) . '\');';
954                 }
955
956                 if ($network == Protocol::DFRN) {
957                         $menu[DI::l10n()->t("Poke")] = $poke_link;
958                 }
959
960                 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
961                         in_array($item['network'], Protocol::FEDERATED)) {
962                         $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
963                 }
964         } else {
965                 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
966         }
967
968         $args = ['item' => $item, 'menu' => $menu];
969
970         Hook::callAll('item_photo_menu', $args);
971
972         $menu = $args['menu'];
973
974         $o = '';
975         foreach ($menu as $k => $v) {
976                 if (strpos($v, 'javascript:') === 0) {
977                         $v = substr($v, 11);
978                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
979                 } elseif ($v!='') {
980                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
981                 }
982         }
983         return $o;
984 }
985
986 /**
987  * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
988  *
989  * Increments the count of each matching activity and adds a link to the author as needed.
990  *
991  * @param array  $activity
992  * @param array &$conv_responses (already created with builtin activity structure)
993  * @return void
994  * @throws ImagickException
995  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996  */
997 function builtin_activity_puller(array $activity, array &$conv_responses)
998 {
999         foreach ($conv_responses as $mode => $v) {
1000                 $sparkle = '';
1001
1002                 switch ($mode) {
1003                         case 'like':
1004                                 $verb = Activity::LIKE;
1005                                 break;
1006                         case 'dislike':
1007                                 $verb = Activity::DISLIKE;
1008                                 break;
1009                         case 'attendyes':
1010                                 $verb = Activity::ATTEND;
1011                                 break;
1012                         case 'attendno':
1013                                 $verb = Activity::ATTENDNO;
1014                                 break;
1015                         case 'attendmaybe':
1016                                 $verb = Activity::ATTENDMAYBE;
1017                                 break;
1018                         case 'announce':
1019                                 $verb = Activity::ANNOUNCE;
1020                                 break;
1021                         default:
1022                                 return;
1023                 }
1024
1025                 if (!empty($activity['verb']) && DI::activity()->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
1026                         $author = [
1027                                 'uid' => 0,
1028                                 'id' => $activity['author-id'],
1029                                 'network' => $activity['author-network'],
1030                                 'url' => $activity['author-link']
1031                         ];
1032                         $url = Contact::magicLinkByContact($author);
1033                         if (strpos($url, 'redir/') === 0) {
1034                                 $sparkle = ' class="sparkle" ';
1035                         }
1036
1037                         $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
1038
1039                         if (empty($activity['thr-parent'])) {
1040                                 $activity['thr-parent'] = $activity['parent-uri'];
1041                         }
1042
1043                         // Skip when the causer of the parent is the same than the author of the announce
1044                         if (($verb == Activity::ANNOUNCE) && Item::exists(['uri' => $activity['thr-parent'],
1045                                 'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => GRAVITY_PARENT])) {
1046                                 continue;
1047                         }
1048
1049                         if (!isset($conv_responses[$mode][$activity['thr-parent']])) {
1050                                 $conv_responses[$mode][$activity['thr-parent']] = [
1051                                         'links' => [],
1052                                         'self' => 0,
1053                                 ];
1054                         } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent']]['links'])) {
1055                                 // only list each unique author once
1056                                 continue;
1057                         }
1058
1059                         if (public_contact() == $activity['author-id']) {
1060                                 $conv_responses[$mode][$activity['thr-parent']]['self'] = 1;
1061                         }
1062
1063                         $conv_responses[$mode][$activity['thr-parent']]['links'][] = $link;
1064
1065                         // there can only be one activity verb per item so if we found anything, we can stop looking
1066                         return;
1067                 }
1068         }
1069 }
1070
1071 /**
1072  * Format the activity text for an item/photo/video
1073  *
1074  * @param array  $links = array of pre-linked names of actors
1075  * @param string $verb  = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1076  * @param int    $id    = item id
1077  * @return string formatted text
1078  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1079  */
1080 function format_activity(array $links, $verb, $id) {
1081         $o = '';
1082         $expanded = '';
1083         $phrase = '';
1084
1085         $total = count($links);
1086         if ($total == 1) {
1087                 $likers = $links[0];
1088
1089                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1090                 // list which show all likers
1091                 switch ($verb) {
1092                         case 'like' :
1093                                 $phrase = DI::l10n()->t('%s likes this.', $likers);
1094                                 break;
1095                         case 'dislike' :
1096                                 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1097                                 break;
1098                         case 'attendyes' :
1099                                 $phrase = DI::l10n()->t('%s attends.', $likers);
1100                                 break;
1101                         case 'attendno' :
1102                                 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1103                                 break;
1104                         case 'attendmaybe' :
1105                                 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1106                                 break;
1107                         case 'announce' :
1108                                 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1109                                 break;
1110                 }
1111         } elseif ($total > 1) {
1112                 if ($total < MAX_LIKERS) {
1113                         $likers = implode(', ', array_slice($links, 0, -1));
1114                         $likers .= ' ' . DI::l10n()->t('and') . ' ' . $links[count($links)-1];
1115                 } else  {
1116                         $likers = implode(', ', array_slice($links, 0, MAX_LIKERS - 1));
1117                         $likers .= ' ' . DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1118                 }
1119
1120                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
1121
1122                 $explikers = '';
1123                 switch ($verb) {
1124                         case 'like':
1125                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> like this', $spanatts, $total);
1126                                 $explikers = DI::l10n()->t('%s like this.', $likers);
1127                                 break;
1128                         case 'dislike':
1129                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
1130                                 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1131                                 break;
1132                         case 'attendyes':
1133                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend', $spanatts, $total);
1134                                 $explikers = DI::l10n()->t('%s attend.', $likers);
1135                                 break;
1136                         case 'attendno':
1137                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
1138                                 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1139                                 break;
1140                         case 'attendmaybe':
1141                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend maybe', $spanatts, $total);
1142                                 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1143                                 break;
1144                         case 'announce':
1145                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> reshared this', $spanatts, $total);
1146                                 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1147                                 break;
1148                 }
1149
1150                 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1151         }
1152
1153         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1154                 '$phrase' => $phrase,
1155                 '$type' => $verb,
1156                 '$id' => $id
1157         ]);
1158         $o .= $expanded;
1159
1160         return $o;
1161 }
1162
1163 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1164 {
1165         $o = '';
1166
1167         $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1168
1169         $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1170         DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1171                 '$newpost'   => 'true',
1172                 '$baseurl'   => DI::baseUrl()->get(true),
1173                 '$geotag'    => $geotag,
1174                 '$nickname'  => $x['nickname'],
1175                 '$ispublic'  => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1176                 '$linkurl'   => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1177                 '$term'      => DI::l10n()->t('Tag term:'),
1178                 '$fileas'    => DI::l10n()->t('Save to Folder:'),
1179                 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1180                 '$delitems'  => DI::l10n()->t("Delete item\x28s\x29?")
1181         ]);
1182
1183         $jotplugins = '';
1184         Hook::callAll('jot_tool', $jotplugins);
1185
1186         $tpl = Renderer::getMarkupTemplate("jot.tpl");
1187
1188         $o .= Renderer::replaceMacros($tpl, [
1189                 '$new_post' => DI::l10n()->t('New Post'),
1190                 '$return_path'  => DI::args()->getQueryString(),
1191                 '$action'       => 'item',
1192                 '$share'        => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1193                 '$loading'      => DI::l10n()->t('Loading...'),
1194                 '$upload'       => DI::l10n()->t('Upload photo'),
1195                 '$shortupload'  => DI::l10n()->t('upload photo'),
1196                 '$attach'       => DI::l10n()->t('Attach file'),
1197                 '$shortattach'  => DI::l10n()->t('attach file'),
1198                 '$edbold'       => DI::l10n()->t('Bold'),
1199                 '$editalic'     => DI::l10n()->t('Italic'),
1200                 '$eduline'      => DI::l10n()->t('Underline'),
1201                 '$edquote'      => DI::l10n()->t('Quote'),
1202                 '$edcode'       => DI::l10n()->t('Code'),
1203                 '$edimg'        => DI::l10n()->t('Image'),
1204                 '$edurl'        => DI::l10n()->t('Link'),
1205                 '$edattach'     => DI::l10n()->t('Link or Media'),
1206                 '$setloc'       => DI::l10n()->t('Set your location'),
1207                 '$shortsetloc'  => DI::l10n()->t('set location'),
1208                 '$noloc'        => DI::l10n()->t('Clear browser location'),
1209                 '$shortnoloc'   => DI::l10n()->t('clear location'),
1210                 '$title'        => $x['title'] ?? '',
1211                 '$placeholdertitle' => DI::l10n()->t('Set title'),
1212                 '$category'     => $x['category'] ?? '',
1213                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1214                 '$wait'         => DI::l10n()->t('Please wait'),
1215                 '$permset'      => DI::l10n()->t('Permission settings'),
1216                 '$shortpermset' => DI::l10n()->t('Permissions'),
1217                 '$wall'         => $notes_cid ? 0 : 1,
1218                 '$posttype'     => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1219                 '$content'      => $x['content'] ?? '',
1220                 '$post_id'      => $x['post_id'] ?? '',
1221                 '$baseurl'      => DI::baseUrl()->get(true),
1222                 '$defloc'       => $x['default_location'],
1223                 '$visitor'      => $x['visitor'],
1224                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1225                 '$public'       => DI::l10n()->t('Public post'),
1226                 '$lockstate'    => $x['lockstate'],
1227                 '$bang'         => $x['bang'],
1228                 '$profile_uid'  => $x['profile_uid'],
1229                 '$preview'      => DI::l10n()->t('Preview'),
1230                 '$jotplugins'   => $jotplugins,
1231                 '$notes_cid'    => $notes_cid,
1232                 '$sourceapp'    => DI::l10n()->t($a->sourcename),
1233                 '$cancel'       => DI::l10n()->t('Cancel'),
1234                 '$rand_num'     => Crypto::randomDigits(12),
1235
1236                 // ACL permissions box
1237                 '$acl'           => $x['acl'],
1238
1239                 //jot nav tab (used in some themes)
1240                 '$message' => DI::l10n()->t('Message'),
1241                 '$browser' => DI::l10n()->t('Browser'),
1242
1243                 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1244         ]);
1245
1246
1247         if ($popup == true) {
1248                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1249         }
1250
1251         return $o;
1252 }
1253
1254 /**
1255  * Plucks the children of the given parent from a given item list.
1256  *
1257  * @param array $item_list
1258  * @param array $parent
1259  * @param bool  $recursive
1260  * @return array
1261  */
1262 function get_item_children(array &$item_list, array $parent, $recursive = true)
1263 {
1264         $children = [];
1265         foreach ($item_list as $i => $item) {
1266                 if ($item['gravity'] != GRAVITY_PARENT) {
1267                         if ($recursive) {
1268                                 // Fallback to parent-uri if thr-parent is not set
1269                                 $thr_parent = $item['thr-parent'];
1270                                 if ($thr_parent == '') {
1271                                         $thr_parent = $item['parent-uri'];
1272                                 }
1273
1274                                 if ($thr_parent == $parent['uri']) {
1275                                         $item['children'] = get_item_children($item_list, $item);
1276                                         $children[] = $item;
1277                                         unset($item_list[$i]);
1278                                 }
1279                         } elseif ($item['parent'] == $parent['id']) {
1280                                 $children[] = $item;
1281                                 unset($item_list[$i]);
1282                         }
1283                 }
1284         }
1285         return $children;
1286 }
1287
1288 /**
1289  * Recursively sorts a tree-like item array
1290  *
1291  * @param array $items
1292  * @return array
1293  */
1294 function sort_item_children(array $items)
1295 {
1296         $result = $items;
1297         usort($result, 'sort_thr_received_rev');
1298         foreach ($result as $k => $i) {
1299                 if (isset($result[$k]['children'])) {
1300                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1301                 }
1302         }
1303         return $result;
1304 }
1305
1306 /**
1307  * Recursively add all children items at the top level of a list
1308  *
1309  * @param array $children List of items to append
1310  * @param array $item_list
1311  */
1312 function add_children_to_list(array $children, array &$item_list)
1313 {
1314         foreach ($children as $child) {
1315                 $item_list[] = $child;
1316                 if (isset($child['children'])) {
1317                         add_children_to_list($child['children'], $item_list);
1318                 }
1319         }
1320 }
1321
1322 /**
1323  * Selectively flattens a tree-like item structure to prevent threading stairs
1324  *
1325  * This recursive function takes the item tree structure created by conv_sort() and
1326  * flatten the extraneous depth levels when people reply sequentially, removing the
1327  * stairs effect in threaded conversations limiting the available content width.
1328  *
1329  * The basic principle is the following: if a post item has only one reply and is
1330  * the last reply of its parent, then the reply is moved to the parent.
1331  *
1332  * This process is rendered somewhat more complicated because items can be either
1333  * replies or likes, and these don't factor at all in the reply count/last reply.
1334  *
1335  * @param array $parent A tree-like array of items
1336  * @return array
1337  */
1338 function smart_flatten_conversation(array $parent)
1339 {
1340         if (!isset($parent['children']) || count($parent['children']) == 0) {
1341                 return $parent;
1342         }
1343
1344         // We use a for loop to ensure we process the newly-moved items
1345         for ($i = 0; $i < count($parent['children']); $i++) {
1346                 $child = $parent['children'][$i];
1347
1348                 if (isset($child['children']) && count($child['children'])) {
1349                         // This helps counting only the regular posts
1350                         $count_post_closure = function($var) {
1351                                 return $var['verb'] === Activity::POST;
1352                         };
1353
1354                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1355
1356                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1357
1358                         // If there's only one child's children post and this is the last child post
1359                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1360
1361                                 // Searches the post item in the children
1362                                 $j = 0;
1363                                 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1364                                         $j ++;
1365                                 }
1366
1367                                 $moved_item = $child['children'][$j];
1368                                 unset($parent['children'][$i]['children'][$j]);
1369                                 $parent['children'][] = $moved_item;
1370                         } else {
1371                                 $parent['children'][$i] = smart_flatten_conversation($child);
1372                         }
1373                 }
1374         }
1375
1376         return $parent;
1377 }
1378
1379
1380 /**
1381  * Expands a flat list of items into corresponding tree-like conversation structures.
1382  *
1383  * sort the top-level posts either on "received" or "commented", and finally
1384  * append all the items at the top level (???)
1385  *
1386  * @param array  $item_list A list of items belonging to one or more conversations
1387  * @param string $order     Either on "received" or "commented"
1388  * @return array
1389  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1390  */
1391 function conv_sort(array $item_list, $order)
1392 {
1393         $parents = [];
1394
1395         if (!(is_array($item_list) && count($item_list))) {
1396                 return $parents;
1397         }
1398
1399         $blocklist = conv_get_blocklist();
1400
1401         $item_array = [];
1402
1403         // Dedupes the item list on the uri to prevent infinite loops
1404         foreach ($item_list as $item) {
1405                 if (in_array($item['author-id'], $blocklist)) {
1406                         continue;
1407                 }
1408
1409                 $item_array[$item['uri']] = $item;
1410         }
1411
1412         // Extract the top level items
1413         foreach ($item_array as $item) {
1414                 if ($item['gravity'] == GRAVITY_PARENT) {
1415                         $parents[] = $item;
1416                 }
1417         }
1418
1419         if (stristr($order, 'pinned_received')) {
1420                 usort($parents, 'sort_thr_pinned_received');
1421         } elseif (stristr($order, 'received')) {
1422                 usort($parents, 'sort_thr_received');
1423         } elseif (stristr($order, 'commented')) {
1424                 usort($parents, 'sort_thr_commented');
1425         }
1426
1427         /*
1428          * Plucks children from the item_array, second pass collects eventual orphan
1429          * items and add them as children of their top-level post.
1430          */
1431         foreach ($parents as $i => $parent) {
1432                 $parents[$i]['children'] =
1433                         array_merge(get_item_children($item_array, $parent, true),
1434                                 get_item_children($item_array, $parent, false));
1435         }
1436
1437         foreach ($parents as $i => $parent) {
1438                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1439         }
1440
1441         if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1442                 foreach ($parents as $i => $parent) {
1443                         $parents[$i] = smart_flatten_conversation($parent);
1444                 }
1445         }
1446
1447         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1448         /// However, this apparently ensures responses (likes, attendance) display (?!)
1449         foreach ($parents as $parent) {
1450                 if (count($parent['children'])) {
1451                         add_children_to_list($parent['children'], $parents);
1452                 }
1453         }
1454
1455         return $parents;
1456 }
1457
1458 /**
1459  * usort() callback to sort item arrays by pinned and the received key
1460  *
1461  * @param array $a
1462  * @param array $b
1463  * @return int
1464  */
1465 function sort_thr_pinned_received(array $a, array $b)
1466 {
1467         if ($b['pinned'] && !$a['pinned']) {
1468                 return 1;
1469         } elseif (!$b['pinned'] && $a['pinned']) {
1470                 return -1;
1471         }
1472
1473         return strcmp($b['received'], $a['received']);
1474 }
1475
1476 /**
1477  * usort() callback to sort item arrays by the received key
1478  *
1479  * @param array $a
1480  * @param array $b
1481  * @return int
1482  */
1483 function sort_thr_received(array $a, array $b)
1484 {
1485         return strcmp($b['received'], $a['received']);
1486 }
1487
1488 /**
1489  * usort() callback to reverse sort item arrays by the received key
1490  *
1491  * @param array $a
1492  * @param array $b
1493  * @return int
1494  */
1495 function sort_thr_received_rev(array $a, array $b)
1496 {
1497         return strcmp($a['received'], $b['received']);
1498 }
1499
1500 /**
1501  * usort() callback to sort item arrays by the commented key
1502  *
1503  * @param array $a
1504  * @param array $b
1505  * @return int
1506  */
1507 function sort_thr_commented(array $a, array $b)
1508 {
1509         return strcmp($b['commented'], $a['commented']);
1510 }