3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
23 use Friendica\Content\ContactSelector;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Profile;
36 use Friendica\Model\Tag;
37 use Friendica\Model\Verb;
38 use Friendica\Object\Post;
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 as ProxyUtils;
44 use Friendica\Util\Strings;
45 use Friendica\Util\Temporal;
46 use Friendica\Util\XML;
48 function item_extract_images($body) {
55 $img_start = strpos($orig_body, '[img');
56 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
57 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
58 while (($img_st_close !== false) && ($img_end !== false)) {
60 $img_st_close++; // make it point to AFTER the closing bracket
61 $img_end += $img_start;
63 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
64 // This is an embedded image
66 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
67 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
71 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
74 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
76 if ($orig_body === false) {
77 // in case the body ends on a closing image tag
81 $img_start = strpos($orig_body, '[img');
82 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
83 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
86 $new_body = $new_body . $orig_body;
88 return ['body' => $new_body, 'images' => $saved_image];
91 function item_redir_and_replace_images($body, $images, $cid) {
97 $pos = BBCode::getTagPosition($origbody, 'url', 0);
98 while ($pos !== false && $cnt < 1000) {
100 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
101 $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
102 . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
104 $newbody .= substr($origbody, 0, $pos['start']['open']);
105 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
106 $origbody = substr($origbody, $pos['end']['close']);
107 if ($origbody === false) {
111 $subject = preg_replace($search, $replace, $subject);
112 $newbody .= $subject;
115 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
116 $pos = BBCode::getTagPosition($origbody, 'url', 0);
118 $newbody .= $origbody;
121 foreach ($images as $image) {
123 * We're depending on the property of 'foreach' (specified on the PHP website) that
124 * it loops over the array starting from the first element and going sequentially
125 * to the last element.
127 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
134 * Render actions localized
137 * @throws ImagickException
138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
140 function localize_item(&$item)
142 $extracted = item_extract_images($item['body']);
143 if ($extracted['images']) {
144 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
147 /// @todo The following functionality needs to be cleaned up.
148 if (!empty($item['verb'])) {
149 $activity = DI::activity();
151 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
153 if (stristr($item['verb'], Activity::POKE)) {
154 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
158 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
162 $Aname = $item['author-name'];
163 $Alink = $item['author-link'];
165 $obj = XML::parseString($xmlhead . $item['object']);
167 $Bname = $obj->title;
171 foreach ($obj->link as $l) {
172 $atts = $l->attributes();
173 switch ($atts['rel']) {
174 case "alternate": $Blink = $atts['href'];
175 case "photo": $Bphoto = $atts['href'];
179 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
180 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
182 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
186 * we can't have a translation string with three positions but no distinguishable text
187 * So here is the translate string.
189 $txt = DI::l10n()->t('%1$s poked %2$s');
191 // now translate the verb
192 $poked_t = trim(sprintf($txt, '', ''));
193 $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
195 // then do the sprintf on the translation string
197 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
201 if ($activity->match($item['verb'], Activity::TAG)) {
202 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
203 'verb', 'object-type', 'resource-id', 'body', 'plink'];
204 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
205 if (!DBA::isResult($obj)) {
209 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
210 'network' => $item['author-network'], 'url' => $item['author-link']];
211 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
213 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
214 'network' => $obj['author-network'], 'url' => $obj['author-link']];
215 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
217 switch ($obj['verb']) {
219 switch ($obj['object-type']) {
220 case Activity\ObjectType::EVENT:
221 $post_type = DI::l10n()->t('event');
224 $post_type = DI::l10n()->t('status');
228 if ($obj['resource-id']) {
229 $post_type = DI::l10n()->t('photo');
230 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
231 $rr['plink'] = $m[1];
233 $post_type = DI::l10n()->t('status');
235 // Let's break everthing ... ;-)
238 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
240 $parsedobj = XML::parseString($xmlhead . $item['object']);
242 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
243 $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
248 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
249 foreach ($matches as $mtch) {
250 if (!strpos($mtch[1], 'zrl=')) {
251 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
256 // add zrl's to public images
257 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
258 if (preg_match($photo_pattern, $item['body'])) {
259 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
260 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
263 // add sparkle links to appropriate permalinks
264 $author = ['uid' => 0, 'id' => $item['author-id'],
265 'network' => $item['author-network'], 'url' => $item['author-link']];
267 // Only create a redirection to a magic link when logged in
268 if (!empty($item['plink']) && Session::isAuthenticated()) {
269 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
274 * Count the total of comments on this item and its desendants
275 * @TODO proper type-hint + doc-tag
279 function count_descendants($item) {
280 $total = count($item['children']);
283 foreach ($item['children'] as $child) {
284 if (!visible_activity($child)) {
287 $total += count_descendants($child);
294 function visible_activity($item) {
296 $activity = DI::activity();
298 if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
302 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
303 if ($activity->match($item['verb'], Activity::FOLLOW) &&
304 $item['object-type'] === Activity\ObjectType::NOTE &&
305 empty($item['self']) &&
306 $item['uid'] == local_user()) {
313 function conv_get_blocklist()
319 $str_blocked = DI::pConfig()->get(local_user(), 'system', 'blocked');
320 if (empty($str_blocked)) {
326 foreach (explode(',', $str_blocked) as $entry) {
327 // The 4th parameter guarantees that there always will be a public contact entry
328 $cid = Contact::getIdForURL(trim($entry), 0, false, ['url' => trim($entry)]);
338 * "Render" a conversation or list of items for HTML display.
339 * There are two major forms of display:
340 * - Sequential or unthreaded ("New Item View" or search results)
341 * - conversation view
342 * The $mode parameter decides between the various renderings and also
343 * figures out how to determine page owner and other contextual items
344 * that are based on unique features of the calling module.
346 * @param array $items
349 * @param bool $preview
350 * @param string $order
353 * @throws ImagickException
354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
356 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
358 $ssl_state = (local_user() ? true : false);
361 $live_update_div = '';
363 $blocklist = conv_get_blocklist();
365 $previewing = (($preview) ? ' preview ' : '');
367 if ($mode === 'network') {
368 $items = conversation_add_children($items, false, $order, $uid);
369 $profile_owner = local_user();
372 * The special div is needed for liveUpdate to kick in for this page.
373 * We only launch liveUpdate if you aren't filtering in some incompatible
374 * way and also you aren't writing a comment (discovered in javascript).
376 $live_update_div = '<div id="live-network"></div>' . "\r\n"
377 . "<script> var profile_uid = " . $_SESSION['uid']
378 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
380 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
381 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
382 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
383 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
384 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
385 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
386 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
387 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
388 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
389 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
390 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
392 . "'; </script>\r\n";
394 } elseif ($mode === 'profile') {
395 $items = conversation_add_children($items, false, $order, $uid);
396 $profile_owner = $a->profile['uid'];
400 if (!empty($_GET['tab'])) {
401 $tab = Strings::escapeTags(trim($_GET['tab']));
403 if ($tab === 'posts') {
405 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
406 * because browser prefetching might change it on us. We have to deliver it with the page.
409 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
410 . "<script> var profile_uid = " . $a->profile['uid']
411 . "; var netargs = '?f='; </script>\r\n";
414 } elseif ($mode === 'notes') {
415 $items = conversation_add_children($items, false, $order, local_user());
416 $profile_owner = local_user();
419 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
420 . "<script> var profile_uid = " . local_user()
421 . "; var netargs = '/?f='; </script>\r\n";
423 } elseif ($mode === 'display') {
424 $items = conversation_add_children($items, false, $order, $uid);
425 $profile_owner = $a->profile['uid'];
428 $live_update_div = '<div id="live-display"></div>' . "\r\n"
429 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
432 } elseif ($mode === 'community') {
433 $items = conversation_add_children($items, true, $order, $uid);
437 $live_update_div = '<div id="live-community"></div>' . "\r\n"
438 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
439 ."/?f='; </script>\r\n";
441 } elseif ($mode === 'contacts') {
442 $items = conversation_add_children($items, false, $order, $uid);
446 $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
447 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 9)
448 ."/?f='; </script>\r\n";
450 } elseif ($mode === 'search') {
451 $live_update_div = '<div id="live-search"></div>' . "\r\n";
454 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
457 $_SESSION['return_path'] = DI::args()->getQueryString();
460 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
461 Hook::callAll('conversation_start',$cb);
463 $items = $cb['items'];
474 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
475 unset($conv_responses['dislike']);
478 // array with html for each thread (parent+comments)
482 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
484 if (!empty($items)) {
485 if (in_array($mode, ['community', 'contacts'])) {
488 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
495 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
498 * "New Item View" on network page or search page results
499 * - just loop through the items and format them minimally for display
502 $tpl = 'search_item.tpl';
504 foreach ($items as $item) {
506 if (!visible_activity($item)) {
510 if (in_array($item['author-id'], $blocklist)) {
520 // prevent private email from leaking.
521 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
525 $profile_name = $item['author-name'];
526 if (!empty($item['author-link']) && empty($item['author-name'])) {
527 $profile_name = $item['author-link'];
530 $tags = Tag::populateFromItem($item);
532 $author = ['uid' => 0, 'id' => $item['author-id'],
533 'network' => $item['author-network'], 'url' => $item['author-link']];
534 $profile_link = Contact::magicLinkByContact($author);
536 if (strpos($profile_link, 'redir/') === 0) {
537 $sparkle = ' sparkle';
540 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
541 Hook::callAll('render_location',$locate);
543 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
545 localize_item($item);
546 if ($mode === 'network-new') {
553 'dropping' => $dropping,
554 'pagedrop' => $page_dropping,
555 'select' => DI::l10n()->t('Select'),
556 'delete' => DI::l10n()->t('Delete'),
560 $isstarred = "unstarred";
569 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
570 unset($likebuttons['dislike']);
573 $body = Item::prepareBody($item, true, $preview);
575 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
577 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
578 $title = ucfirst($item['content-warning']);
580 $title = $item['title'];
585 'id' => ($preview ? 'P0' : $item['id']),
586 'guid' => ($preview ? 'Q0' : $item['guid']),
587 'network' => $item['network'],
588 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
589 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
590 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
591 'profile_url' => $profile_link,
592 'item_photo_menu' => item_photo_menu($item),
593 'name' => $profile_name,
594 'sparkle' => $sparkle,
596 'thumb' => DI::baseUrl()->remove(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
599 'tags' => $tags['tags'],
600 'hashtags' => $tags['hashtags'],
601 'mentions' => $tags['mentions'],
602 'implicit_mentions' => $tags['implicit_mentions'],
603 'txt_cats' => DI::l10n()->t('Categories:'),
604 'txt_folders' => DI::l10n()->t('Filed under:'),
605 'has_cats' => ((count($categories)) ? 'true' : ''),
606 'has_folders' => ((count($folders)) ? 'true' : ''),
607 'categories' => $categories,
608 'folders' => $folders,
609 'text' => strip_tags($body),
610 'localtime' => DateTimeFormat::local($item['created'], 'r'),
611 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
612 'location' => $location,
614 'owner_name' => $owner_name,
615 'owner_url' => $owner_url,
616 'owner_photo' => DI::baseUrl()->remove(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
617 'plink' => Item::getPlink($item),
619 'isstarred' => $isstarred,
622 'vote' => $likebuttons,
626 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
627 'previewing' => $previewing,
628 'wait' => DI::l10n()->t('Please wait'),
632 $arr = ['item' => $item, 'output' => $tmp_item];
633 Hook::callAll('display_item', $arr);
635 $threads[$threadsid]['id'] = $item['id'];
636 $threads[$threadsid]['network'] = $item['network'];
637 $threads[$threadsid]['items'] = [$arr['output']];
642 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
644 $conv = new Thread($mode, $preview, $writable);
647 * get all the topmost parents
648 * this shouldn't be needed, as we should have only them in our array
649 * But for now, this array respects the old style, just in case
651 foreach ($items as $item) {
652 if (in_array($item['author-id'], $blocklist)) {
656 // Can we put this after the visibility check?
657 builtin_activity_puller($item, $conv_responses);
659 // Only add what is visible
660 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
664 if (!visible_activity($item)) {
668 /// @todo Check if this call is needed or not
669 $arr = ['item' => $item];
670 Hook::callAll('display_item', $arr);
672 $item['pagedrop'] = $page_dropping;
674 if ($item['gravity'] == GRAVITY_PARENT) {
675 $item_object = new Post($item);
676 $conv->addParent($item_object);
680 $threads = $conv->getTemplateData($conv_responses);
682 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
688 $o = Renderer::replaceMacros($page_template, [
689 '$baseurl' => DI::baseUrl()->get($ssl_state),
690 '$return_path' => DI::args()->getQueryString(),
691 '$live_update' => $live_update_div,
692 '$remove' => DI::l10n()->t('remove'),
695 '$threads' => $threads,
696 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
703 * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
705 * @param mixed $thread_items Database statement with thread posts
706 * @param boolean $pinned Is the item pinned?
708 * @return array items with parents and comments
710 function conversation_fetch_comments($thread_items, $pinned) {
717 while ($row = Item::fetch($thread_items)) {
718 if (($row['verb'] == Activity::ANNOUNCE) && !empty($row['contact-uid']) && ($row['received'] > $received) && ($row['thr-parent'] == $row['parent-uri'])) {
719 $actor = ['link' => $row['author-link'], 'avatar' => $row['author-avatar'], 'name' => $row['author-name']];
720 $received = $row['received'];
723 if ((($row['gravity'] == GRAVITY_PARENT) && !$row['origin'] && !in_array($row['network'], [Protocol::DIASPORA])) &&
724 (empty($row['contact-uid']) || !in_array($row['network'], Protocol::NATIVE_SUPPORT))) {
725 $parentlines[] = $lineno;
728 if ($row['gravity'] == GRAVITY_PARENT) {
729 $row['pinned'] = $pinned;
736 DBA::close($thread_items);
738 if (!empty($actor)) {
739 foreach ($parentlines as $line) {
740 $comments[$line]['owner-link'] = $actor['link'];
741 $comments[$line]['owner-avatar'] = $actor['avatar'];
742 $comments[$line]['owner-name'] = $actor['name'];
749 * Add comments to top level entries that had been fetched before
751 * The system will fetch the comments for the local user whenever possible.
752 * This behaviour is currently needed to allow commenting on Friendica posts.
754 * @param array $parents Parent items
756 * @param $block_authors
759 * @return array items with parents and comments
760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
762 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
763 if (count($parents) > 1) {
764 $max_comments = DI::config()->get('system', 'max_comments', 100);
766 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
769 $params = ['order' => ['uid', 'commented' => true]];
771 if ($max_comments > 0) {
772 $params['limit'] = $max_comments;
777 foreach ($parents AS $parent) {
778 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
779 $parent['uri'], $uid, Verb::getID(Activity::FOLLOW)];
780 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params);
783 foreach ($items as $index => $item) {
784 if ($item['uid'] == 0) {
785 $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
789 $items = conv_sort($items, $order);
795 * Fetch conversation items
797 * @param array $parent
798 * @param array $items
799 * @param array $condition
800 * @param boolean $block_authors
801 * @param array $params
804 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params) {
805 if ($block_authors) {
806 $condition[0] .= " AND NOT `author`.`hidden`";
809 $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['contact-uid', 'gravity']), $condition, $params);
811 $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false);
813 if (count($comments) != 0) {
814 $items = array_merge($items, $comments);
819 function item_photo_menu($item) {
830 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self']) {
831 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
834 $author = ['uid' => 0, 'id' => $item['author-id'],
835 'network' => $item['author-network'], 'url' => $item['author-link']];
836 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
837 $sparkle = (strpos($profile_link, 'redir/') === 0);
840 $pcid = Contact::getIdForURL($item['author-link'], 0, false);
843 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
844 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
845 if (DBA::isResult($contact)) {
846 $cid = $contact['id'];
847 $network = $contact['network'];
848 $rel = $contact['rel'];
852 $status_link = $profile_link . '/status';
853 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
854 $profile_link = $profile_link . '/profile';
858 $contact_url = 'contact/' . $pcid;
859 $posts_link = $contact_url . '/posts';
860 $block_link = $contact_url . '/block';
861 $ignore_link = $contact_url . '/ignore';
864 if ($cid && !$item['self']) {
865 $contact_url = 'contact/' . $cid;
866 $poke_link = $contact_url . '/poke';
867 $posts_link = $contact_url . '/posts';
869 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
870 $pm_url = 'message/new/' . $cid;
876 DI::l10n()->t('Follow Thread') => $sub_link,
877 DI::l10n()->t('View Status') => $status_link,
878 DI::l10n()->t('View Profile') => $profile_link,
879 DI::l10n()->t('View Photos') => $photos_link,
880 DI::l10n()->t('Network Posts') => $posts_link,
881 DI::l10n()->t('View Contact') => $contact_url,
882 DI::l10n()->t('Send PM') => $pm_url,
883 DI::l10n()->t('Block') => $block_link,
884 DI::l10n()->t('Ignore') => $ignore_link
887 if ($network == Protocol::DFRN) {
888 $menu[DI::l10n()->t("Poke")] = $poke_link;
891 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
892 in_array($item['network'], Protocol::FEDERATED)) {
893 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
896 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
899 $args = ['item' => $item, 'menu' => $menu];
901 Hook::callAll('item_photo_menu', $args);
903 $menu = $args['menu'];
906 foreach ($menu as $k => $v) {
907 if (strpos($v, 'javascript:') === 0) {
909 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
911 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
918 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
920 * Increments the count of each matching activity and adds a link to the author as needed.
923 * @param array &$conv_responses (already created with builtin activity structure)
925 * @throws ImagickException
926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
928 function builtin_activity_puller($item, &$conv_responses) {
929 foreach ($conv_responses as $mode => $v) {
934 $verb = Activity::LIKE;
937 $verb = Activity::DISLIKE;
940 $verb = Activity::ATTEND;
943 $verb = Activity::ATTENDNO;
946 $verb = Activity::ATTENDMAYBE;
949 $verb = Activity::ANNOUNCE;
955 if (!empty($item['verb']) && DI::activity()->match($item['verb'], $verb) && ($item['gravity'] != GRAVITY_PARENT)) {
956 $author = ['uid' => 0, 'id' => $item['author-id'],
957 'network' => $item['author-network'], 'url' => $item['author-link']];
958 $url = Contact::magicLinkByContact($author);
959 if (strpos($url, 'redir/') === 0) {
960 $sparkle = ' class="sparkle" ';
963 $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
965 if (empty($item['thr-parent'])) {
966 $item['thr-parent'] = $item['parent-uri'];
969 if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
970 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
971 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
974 // only list each unique author once
975 if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
979 if (!isset($conv_responses[$mode][$item['thr-parent']])) {
980 $conv_responses[$mode][$item['thr-parent']] = 1;
982 $conv_responses[$mode][$item['thr-parent']] ++;
985 if (public_contact() == $item['author-id']) {
986 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
989 $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
991 // there can only be one activity verb per item so if we found anything, we can stop looking
998 * Format the vote text for a profile item
1000 * @param int $cnt = number of people who vote the item
1001 * @param array $arr = array of pre-linked names of likers/dislikers
1002 * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1003 * @param int $id = item id
1004 * @return string formatted text
1005 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1007 function format_like($cnt, array $arr, $type, $id) {
1015 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1016 // list which show all likers
1019 $phrase = DI::l10n()->t('%s likes this.', $likers);
1022 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1025 $phrase = DI::l10n()->t('%s attends.', $likers);
1028 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1030 case 'attendmaybe' :
1031 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1034 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1040 $total = count($arr);
1041 if ($total < MAX_LIKERS) {
1042 $last = DI::l10n()->t('and') . ' ' . $arr[count($arr)-1];
1043 $arr2 = array_slice($arr, 0, -1);
1044 $likers = implode(', ', $arr2) . ' ' . $last;
1046 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1047 $likers = implode(', ', $arr);
1048 $likers .= DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1051 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1056 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
1057 $explikers = DI::l10n()->t('%s like this.', $likers);
1060 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1061 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1064 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
1065 $explikers = DI::l10n()->t('%s attend.', $likers);
1068 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1069 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1072 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1073 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1076 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $cnt);
1077 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1081 $expanded .= "\t" . '<p class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1084 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1085 '$phrase' => $phrase,
1094 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1098 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1100 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1101 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1102 '$newpost' => 'true',
1103 '$baseurl' => DI::baseUrl()->get(true),
1104 '$geotag' => $geotag,
1105 '$nickname' => $x['nickname'],
1106 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1107 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1108 '$term' => DI::l10n()->t('Tag term:'),
1109 '$fileas' => DI::l10n()->t('Save to Folder:'),
1110 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1111 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?")
1115 Hook::callAll('jot_tool', $jotplugins);
1117 // Private/public post links for the non-JS ACL form
1119 if (!empty($_REQUEST['public'])) {
1123 $query_str = DI::args()->getQueryString();
1124 if (strpos($query_str, 'public=1') !== false) {
1125 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1129 * I think $a->query_string may never have ? in it, but I could be wrong
1130 * It looks like it's from the index.php?q=[etc] rewrite that the web
1131 * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1133 if (strpos($query_str, '?') === false) {
1134 $public_post_link = '?public=1';
1136 $public_post_link = '&public=1';
1139 // $tpl = Renderer::replaceMacros($tpl,array('$jotplugins' => $jotplugins));
1140 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1142 $o .= Renderer::replaceMacros($tpl,[
1143 '$new_post' => DI::l10n()->t('New Post'),
1144 '$return_path' => $query_str,
1145 '$action' => 'item',
1146 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1147 '$loading' => DI::l10n()->t('Loading...'),
1148 '$upload' => DI::l10n()->t('Upload photo'),
1149 '$shortupload' => DI::l10n()->t('upload photo'),
1150 '$attach' => DI::l10n()->t('Attach file'),
1151 '$shortattach' => DI::l10n()->t('attach file'),
1152 '$edbold' => DI::l10n()->t('Bold'),
1153 '$editalic' => DI::l10n()->t('Italic'),
1154 '$eduline' => DI::l10n()->t('Underline'),
1155 '$edquote' => DI::l10n()->t('Quote'),
1156 '$edcode' => DI::l10n()->t('Code'),
1157 '$edimg' => DI::l10n()->t('Image'),
1158 '$edurl' => DI::l10n()->t('Link'),
1159 '$edattach' => DI::l10n()->t('Link or Media'),
1160 '$setloc' => DI::l10n()->t('Set your location'),
1161 '$shortsetloc' => DI::l10n()->t('set location'),
1162 '$noloc' => DI::l10n()->t('Clear browser location'),
1163 '$shortnoloc' => DI::l10n()->t('clear location'),
1164 '$title' => $x['title'] ?? '',
1165 '$placeholdertitle' => DI::l10n()->t('Set title'),
1166 '$category' => $x['category'] ?? '',
1167 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1168 '$wait' => DI::l10n()->t('Please wait'),
1169 '$permset' => DI::l10n()->t('Permission settings'),
1170 '$shortpermset' => DI::l10n()->t('permissions'),
1171 '$wall' => $notes_cid ? 0 : 1,
1172 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1173 '$content' => $x['content'] ?? '',
1174 '$post_id' => $x['post_id'] ?? '',
1175 '$baseurl' => DI::baseUrl()->get(true),
1176 '$defloc' => $x['default_location'],
1177 '$visitor' => $x['visitor'],
1178 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1179 '$public' => DI::l10n()->t('Public post'),
1180 '$lockstate' => $x['lockstate'],
1181 '$bang' => $x['bang'],
1182 '$profile_uid' => $x['profile_uid'],
1183 '$preview' => DI::l10n()->t('Preview'),
1184 '$jotplugins' => $jotplugins,
1185 '$notes_cid' => $notes_cid,
1186 '$sourceapp' => DI::l10n()->t($a->sourcename),
1187 '$cancel' => DI::l10n()->t('Cancel'),
1188 '$rand_num' => Crypto::randomDigits(12),
1190 // ACL permissions box
1191 '$acl' => $x['acl'],
1192 '$group_perms' => DI::l10n()->t('Post to Groups'),
1193 '$contact_perms' => DI::l10n()->t('Post to Contacts'),
1194 '$private' => DI::l10n()->t('Private post'),
1195 '$is_private' => $private_post,
1196 '$public_link' => $public_post_link,
1198 //jot nav tab (used in some themes)
1199 '$message' => DI::l10n()->t('Message'),
1200 '$browser' => DI::l10n()->t('Browser'),
1202 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1206 if ($popup == true) {
1207 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1214 * Plucks the children of the given parent from a given item list.
1216 * @param array $item_list
1217 * @param array $parent
1218 * @param bool $recursive
1221 function get_item_children(array &$item_list, array $parent, $recursive = true)
1224 foreach ($item_list as $i => $item) {
1225 if ($item['gravity'] != GRAVITY_PARENT) {
1227 // Fallback to parent-uri if thr-parent is not set
1228 $thr_parent = $item['thr-parent'];
1229 if ($thr_parent == '') {
1230 $thr_parent = $item['parent-uri'];
1233 if ($thr_parent == $parent['uri']) {
1234 $item['children'] = get_item_children($item_list, $item);
1235 $children[] = $item;
1236 unset($item_list[$i]);
1238 } elseif ($item['parent'] == $parent['id']) {
1239 $children[] = $item;
1240 unset($item_list[$i]);
1248 * Recursively sorts a tree-like item array
1250 * @param array $items
1253 function sort_item_children(array $items)
1256 usort($result, 'sort_thr_received_rev');
1257 foreach ($result as $k => $i) {
1258 if (isset($result[$k]['children'])) {
1259 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1266 * Recursively add all children items at the top level of a list
1268 * @param array $children List of items to append
1269 * @param array $item_list
1271 function add_children_to_list(array $children, array &$item_list)
1273 foreach ($children as $child) {
1274 $item_list[] = $child;
1275 if (isset($child['children'])) {
1276 add_children_to_list($child['children'], $item_list);
1282 * Selectively flattens a tree-like item structure to prevent threading stairs
1284 * This recursive function takes the item tree structure created by conv_sort() and
1285 * flatten the extraneous depth levels when people reply sequentially, removing the
1286 * stairs effect in threaded conversations limiting the available content width.
1288 * The basic principle is the following: if a post item has only one reply and is
1289 * the last reply of its parent, then the reply is moved to the parent.
1291 * This process is rendered somewhat more complicated because items can be either
1292 * replies or likes, and these don't factor at all in the reply count/last reply.
1294 * @param array $parent A tree-like array of items
1297 function smart_flatten_conversation(array $parent)
1299 if (!isset($parent['children']) || count($parent['children']) == 0) {
1303 // We use a for loop to ensure we process the newly-moved items
1304 for ($i = 0; $i < count($parent['children']); $i++) {
1305 $child = $parent['children'][$i];
1307 if (isset($child['children']) && count($child['children'])) {
1308 // This helps counting only the regular posts
1309 $count_post_closure = function($var) {
1310 return $var['verb'] === Activity::POST;
1313 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1315 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1317 // If there's only one child's children post and this is the last child post
1318 if ($child_post_count == 1 && $remaining_post_count == 1) {
1320 // Searches the post item in the children
1322 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1326 $moved_item = $child['children'][$j];
1327 unset($parent['children'][$i]['children'][$j]);
1328 $parent['children'][] = $moved_item;
1330 $parent['children'][$i] = smart_flatten_conversation($child);
1340 * Expands a flat list of items into corresponding tree-like conversation structures.
1342 * sort the top-level posts either on "received" or "commented", and finally
1343 * append all the items at the top level (???)
1345 * @param array $item_list A list of items belonging to one or more conversations
1346 * @param string $order Either on "received" or "commented"
1348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1350 function conv_sort(array $item_list, $order)
1354 if (!(is_array($item_list) && count($item_list))) {
1358 $blocklist = conv_get_blocklist();
1362 // Dedupes the item list on the uri to prevent infinite loops
1363 foreach ($item_list as $item) {
1364 if (in_array($item['author-id'], $blocklist)) {
1368 $item_array[$item['uri']] = $item;
1371 // Extract the top level items
1372 foreach ($item_array as $item) {
1373 if ($item['gravity'] == GRAVITY_PARENT) {
1378 if (stristr($order, 'pinned_received')) {
1379 usort($parents, 'sort_thr_pinned_received');
1380 } elseif (stristr($order, 'received')) {
1381 usort($parents, 'sort_thr_received');
1382 } elseif (stristr($order, 'commented')) {
1383 usort($parents, 'sort_thr_commented');
1387 * Plucks children from the item_array, second pass collects eventual orphan
1388 * items and add them as children of their top-level post.
1390 foreach ($parents as $i => $parent) {
1391 $parents[$i]['children'] =
1392 array_merge(get_item_children($item_array, $parent, true),
1393 get_item_children($item_array, $parent, false));
1396 foreach ($parents as $i => $parent) {
1397 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1400 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1401 foreach ($parents as $i => $parent) {
1402 $parents[$i] = smart_flatten_conversation($parent);
1406 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1407 /// However, this apparently ensures responses (likes, attendance) display (?!)
1408 foreach ($parents as $parent) {
1409 if (count($parent['children'])) {
1410 add_children_to_list($parent['children'], $parents);
1418 * usort() callback to sort item arrays by pinned and the received key
1424 function sort_thr_pinned_received(array $a, array $b)
1426 if ($b['pinned'] && !$a['pinned']) {
1428 } elseif (!$b['pinned'] && $a['pinned']) {
1432 return strcmp($b['received'], $a['received']);
1436 * usort() callback to sort item arrays by the received key
1442 function sort_thr_received(array $a, array $b)
1444 return strcmp($b['received'], $a['received']);
1448 * usort() callback to reverse sort item arrays by the received key
1454 function sort_thr_received_rev(array $a, array $b)
1456 return strcmp($a['received'], $b['received']);
1460 * usort() callback to sort item arrays by the commented key
1466 function sort_thr_commented(array $a, array $b)
1468 return strcmp($b['commented'], $a['commented']);
1471 function render_location_dummy(array $item) {
1472 if (!empty($item['location']) && !empty($item['location'])) {
1473 return $item['location'];
1476 if (!empty($item['coord']) && !empty($item['coord'])) {
1477 return $item['coord'];