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