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