3 * @file include/conversation.php
7 use Friendica\Content\ContactSelector;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Item;
19 use Friendica\Model\Profile;
20 use Friendica\Model\Term;
21 use Friendica\Object\Post;
22 use Friendica\Object\Thread;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Temporal;
25 use Friendica\Util\XML;
27 function item_extract_images($body) {
34 $img_start = strpos($orig_body, '[img');
35 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
36 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
37 while (($img_st_close !== false) && ($img_end !== false)) {
39 $img_st_close++; // make it point to AFTER the closing bracket
40 $img_end += $img_start;
42 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
43 // This is an embedded image
45 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
46 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
50 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
53 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
55 if ($orig_body === false) {
56 // in case the body ends on a closing image tag
60 $img_start = strpos($orig_body, '[img');
61 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
62 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
65 $new_body = $new_body . $orig_body;
67 return ['body' => $new_body, 'images' => $saved_image];
70 function item_redir_and_replace_images($body, $images, $cid) {
76 $pos = BBCode::getTagPosition($origbody, 'url', 0);
77 while ($pos !== false && $cnt < 1000) {
79 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
80 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
81 . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
83 $newbody .= substr($origbody, 0, $pos['start']['open']);
84 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
85 $origbody = substr($origbody, $pos['end']['close']);
86 if ($origbody === false) {
90 $subject = preg_replace($search, $replace, $subject);
94 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
95 $pos = BBCode::getTagPosition($origbody, 'url', 0);
97 $newbody .= $origbody;
100 foreach ($images as $image) {
102 * We're depending on the property of 'foreach' (specified on the PHP website) that
103 * it loops over the array starting from the first element and going sequentially
104 * to the last element.
106 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
113 * Render actions localized
115 function localize_item(&$item)
117 $extracted = item_extract_images($item['body']);
118 if ($extracted['images']) {
119 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
123 heluecht 2018-06-19: from my point of view this whole code part is useless.
124 It just renders the body message of technical posts (Like, dislike, ...).
125 But: The body isn't visible at all. So we do this stuff just because we can.
126 Even if these messages were visible, this would only mean that something went wrong.
127 During the further steps of the database restructuring I would like to address this issue.
130 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
131 if (activity_match($item['verb'], ACTIVITY_LIKE)
132 || activity_match($item['verb'], ACTIVITY_DISLIKE)
133 || activity_match($item['verb'], ACTIVITY_ATTEND)
134 || activity_match($item['verb'], ACTIVITY_ATTENDNO)
135 || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
137 $fields = ['author-link', 'author-name', 'verb', 'object-type', 'resource-id', 'body', 'plink'];
138 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
139 if (!DBM::is_result($obj)) {
143 $author = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
144 $objauthor = '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
146 switch ($obj['verb']) {
148 switch ($obj['object-type']) {
149 case ACTIVITY_OBJ_EVENT:
150 $post_type = L10n::t('event');
153 $post_type = L10n::t('status');
157 if ($obj['resource-id']) {
158 $post_type = L10n::t('photo');
160 preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
161 $rr['plink'] = $m[1];
163 $post_type = L10n::t('status');
167 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
169 if (activity_match($item['verb'], ACTIVITY_LIKE)) {
170 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
171 } elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
172 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
173 } elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
174 $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s');
175 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
176 $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s');
177 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
178 $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s');
181 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
184 if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
186 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
188 $Aname = $item['author-name'];
189 $Alink = $item['author-link'];
191 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
193 $obj = XML::parseString($xmlhead.$item['object']);
194 $links = XML::parseString($xmlhead."<links>".unxmlify($obj->link)."</links>");
196 $Bname = $obj->title;
199 foreach ($links->link as $l) {
200 $atts = $l->attributes();
201 switch ($atts['rel']) {
202 case "alternate": $Blink = $atts['href'];
203 case "photo": $Bphoto = $atts['href'];
207 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
208 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
210 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img]' . $Bphoto . '[/img][/url]';
213 $item['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$Bphoto;
216 if (stristr($item['verb'], ACTIVITY_POKE)) {
217 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
221 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) {
225 $Aname = $item['author-name'];
226 $Alink = $item['author-link'];
228 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
230 $obj = XML::parseString($xmlhead.$item['object']);
231 $links = XML::parseString($xmlhead."<links>".unxmlify($obj->link)."</links>");
233 $Bname = $obj->title;
236 foreach ($links->link as $l) {
237 $atts = $l->attributes();
238 switch ($atts['rel']) {
239 case "alternate": $Blink = $atts['href'];
240 case "photo": $Bphoto = $atts['href'];
244 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
245 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
247 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
251 * we can't have a translation string with three positions but no distinguishable text
252 * So here is the translate string.
254 $txt = L10n::t('%1$s poked %2$s');
256 // now translate the verb
257 $poked_t = trim(sprintf($txt, "", ""));
258 $txt = str_replace($poked_t, L10n::t($verb), $txt);
260 // then do the sprintf on the translation string
262 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
266 if (activity_match($item['verb'], ACTIVITY_TAG)) {
267 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
268 'verb', 'object-type', 'resource-id', 'body', 'plink'];
269 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
270 if (!DBM::is_result($obj)) {
274 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
275 'network' => $item['author-network'], 'url' => $item['author-link']];
276 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
278 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
279 'network' => $obj['author-network'], 'url' => $obj['author-link']];
280 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
282 switch ($obj['verb']) {
284 switch ($obj['object-type']) {
285 case ACTIVITY_OBJ_EVENT:
286 $post_type = L10n::t('event');
289 $post_type = L10n::t('status');
293 if ($obj['resource-id']) {
294 $post_type = L10n::t('photo');
295 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
296 $rr['plink'] = $m[1];
298 $post_type = L10n::t('status');
300 // Let's break everthing ... ;-)
303 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
305 $parsedobj = XML::parseString($xmlhead.$item['object']);
307 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
308 $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
311 if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
312 if ($item['object-type'] == "") {
316 $Aname = $item['author-name'];
317 $Alink = $item['author-link'];
319 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
321 $obj = XML::parseString($xmlhead.$item['object']);
322 if (strlen($obj->id)) {
323 $fields = ['author-link', 'author-name', 'plink'];
324 $target = Item::selectFirst($fields, ['uri' => $obj->id, 'uid' => $item['uid']]);
325 if (DBM::is_result($target) && $target['plink']) {
326 $Bname = $target['author-name'];
327 $Blink = $target['author-link'];
328 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
329 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
330 $P = '[url=' . $target['plink'] . ']' . L10n::t('post/item') . '[/url]';
331 $item['body'] = L10n::t('%1$s marked %2$s\'s %3$s as favorite', $A, $B, $P)."\n";
336 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
337 foreach ($matches as $mtch) {
338 if (!strpos($mtch[1], 'zrl=')) {
339 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
344 // add zrl's to public images
345 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
346 if (preg_match($photo_pattern, $item['body'])) {
347 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
348 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
351 // add sparkle links to appropriate permalinks
352 $author = ['uid' => 0, 'id' => $item['author-id'],
353 'network' => $item['author-network'], 'url' => $item['author-link']];
355 if (!empty($item['plink'])) {
356 $item['plink'] = Contact::magicLinkbyContact($author, $item['plink']);
361 * Count the total of comments on this item and its desendants
362 * @TODO proper type-hint + doc-tag
364 function count_descendants($item) {
365 $total = count($item['children']);
368 foreach ($item['children'] as $child) {
369 if (!visible_activity($child)) {
372 $total += count_descendants($child);
379 function visible_activity($item) {
382 * likes (etc.) can apply to other things besides posts. Check if they are post children,
383 * in which case we handle them specially
385 $hidden_activities = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
386 foreach ($hidden_activities as $act) {
387 if (activity_match($item['verb'], $act)) {
392 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
393 if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) {
401 * "Render" a conversation or list of items for HTML display.
402 * There are two major forms of display:
403 * - Sequential or unthreaded ("New Item View" or search results)
404 * - conversation view
405 * The $mode parameter decides between the various renderings and also
406 * figures out how to determine page owner and other contextual items
407 * that are based on unique features of the calling module.
410 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0) {
411 require_once 'mod/proxy.php';
413 $ssl_state = ((local_user()) ? true : false);
416 $live_update_div = '';
421 $str_blocked = PConfig::get(local_user(), 'system', 'blocked');
423 $arr_blocked = explode(',', $str_blocked);
424 for ($x = 0; $x < count($arr_blocked); $x ++) {
425 $arr_blocked[$x] = trim($arr_blocked[$x]);
431 $previewing = (($preview) ? ' preview ' : '');
433 if ($mode === 'network') {
434 $items = conversation_add_children($items, false, $order, $uid);
435 $profile_owner = local_user();
438 * The special div is needed for liveUpdate to kick in for this page.
439 * We only launch liveUpdate if you aren't filtering in some incompatible
440 * way and also you aren't writing a comment (discovered in javascript).
442 $live_update_div = '<div id="live-network"></div>' . "\r\n"
443 . "<script> var profile_uid = " . $_SESSION['uid']
444 . "; var netargs = '" . substr($a->cmd, 8)
446 . ((x($_GET, 'cid')) ? '&cid=' . $_GET['cid'] : '')
447 . ((x($_GET, 'search')) ? '&search=' . $_GET['search'] : '')
448 . ((x($_GET, 'star')) ? '&star=' . $_GET['star'] : '')
449 . ((x($_GET, 'order')) ? '&order=' . $_GET['order'] : '')
450 . ((x($_GET, 'bmark')) ? '&bmark=' . $_GET['bmark'] : '')
451 . ((x($_GET, 'liked')) ? '&liked=' . $_GET['liked'] : '')
452 . ((x($_GET, 'conv')) ? '&conv=' . $_GET['conv'] : '')
453 . ((x($_GET, 'nets')) ? '&nets=' . $_GET['nets'] : '')
454 . ((x($_GET, 'cmin')) ? '&cmin=' . $_GET['cmin'] : '')
455 . ((x($_GET, 'cmax')) ? '&cmax=' . $_GET['cmax'] : '')
456 . ((x($_GET, 'file')) ? '&file=' . $_GET['file'] : '')
458 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
460 } elseif ($mode === 'profile') {
461 $profile_owner = $a->profile['profile_uid'];
465 if (x($_GET, 'tab')) {
466 $tab = notags(trim($_GET['tab']));
468 if ($tab === 'posts') {
470 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
471 * because browser prefetching might change it on us. We have to deliver it with the page.
474 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
475 . "<script> var profile_uid = " . $a->profile['profile_uid']
476 . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
479 } elseif ($mode === 'notes') {
480 $profile_owner = local_user();
482 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
483 . "<script> var profile_uid = " . local_user()
484 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
486 } elseif ($mode === 'display') {
487 $profile_owner = $a->profile['uid'];
489 $live_update_div = '<div id="live-display"></div>' . "\r\n"
490 . "<script> var profile_uid = " . defaults($_SESSION, 'uid', 0) . ";"
491 . " var profile_page = 1; </script>";
493 } elseif ($mode === 'community') {
494 $items = conversation_add_children($items, true, $order, $uid);
497 $live_update_div = '<div id="live-community"></div>' . "\r\n"
498 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 10)
499 ."/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
501 } elseif ($mode === 'search') {
502 $live_update_div = '<div id="live-search"></div>' . "\r\n";
505 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
508 $_SESSION['return_url'] = $a->query_string;
511 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
512 Addon::callHooks('conversation_start',$cb);
514 $items = $cb['items'];
517 'like' => ['title' => L10n::t('Likes','title')], 'dislike' => ['title' => L10n::t('Dislikes','title')],
518 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
521 // array with html for each thread (parent+comments)
525 $page_template = get_markup_template("conversation.tpl");
527 if ($items && count($items)) {
528 if ($mode === 'community') {
531 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
538 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
541 * "New Item View" on network page or search page results
542 * - just loop through the items and format them minimally for display
545 $tpl = 'search_item.tpl';
547 foreach ($items as $item) {
549 if (!visible_activity($item)) {
555 foreach ($arr_blocked as $b) {
556 if ($b && link_compare($item['author-link'], $b)) {
573 // prevent private email from leaking.
574 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
578 $profile_name = $item['author-name'];
579 if (!empty($item['author-link']) && empty($item['author-name'])) {
580 $profile_name = $item['author-link'];
583 $tags = Term::populateTagsFromItem($item);
585 $author = ['uid' => 0, 'id' => $item['author-id'],
586 'network' => $item['author-network'], 'url' => $item['author-link']];
587 $profile_link = Contact::magicLinkbyContact($author);
589 if (strpos($profile_link, 'redir/') === 0) {
590 $sparkle = ' sparkle';
593 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
594 Addon::callHooks('render_location',$locate);
596 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
598 localize_item($item);
599 if ($mode === 'network-new') {
606 'dropping' => $dropping,
607 'pagedrop' => $page_dropping,
608 'select' => L10n::t('Select'),
609 'delete' => L10n::t('Delete'),
613 $isstarred = "unstarred";
616 $likebuttons = false;
618 $body = prepare_body($item, true, $preview);
620 list($categories, $folders) = get_cats_and_terms($item);
622 $profile_name_e = $profile_name;
624 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
625 $title_e = ucfirst($item['content-warning']);
627 $title_e = $item['title'];
631 $tags_e = $tags['tags'];
632 $hashtags_e = $tags['hashtags'];
633 $mentions_e = $tags['mentions'];
634 $location_e = $location;
635 $owner_name_e = $owner_name;
639 'id' => ($preview ? 'P0' : $item['id']),
640 'guid' => ($preview ? 'Q0' : $item['guid']),
641 'network' => $item['network'],
642 'network_name' => ContactSelector::networkToName($item['network'], $profile_link),
643 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
644 'profile_url' => $profile_link,
645 'item_photo_menu' => item_photo_menu($item),
646 'name' => $profile_name_e,
647 'sparkle' => $sparkle,
649 'thumb' => System::removedBaseUrl(proxy_url($item['author-avatar'], false, PROXY_SIZE_THUMB)),
653 'hashtags' => $hashtags_e,
654 'mentions' => $mentions_e,
655 'txt_cats' => L10n::t('Categories:'),
656 'txt_folders' => L10n::t('Filed under:'),
657 'has_cats' => ((count($categories)) ? 'true' : ''),
658 'has_folders' => ((count($folders)) ? 'true' : ''),
659 'categories' => $categories,
660 'folders' => $folders,
661 'text' => strip_tags($body_e),
662 'localtime' => DateTimeFormat::local($item['created'], 'r'),
663 'ago' => (($item['app']) ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
664 'location' => $location_e,
666 'owner_name' => $owner_name_e,
667 'owner_url' => $owner_url,
668 'owner_photo' => System::removedBaseUrl(proxy_url($item['owner-avatar'], false, PROXY_SIZE_THUMB)),
669 'plink' => get_plink($item),
671 'isstarred' => $isstarred,
674 'vote' => $likebuttons,
678 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> L10n::t('View in context')]),
679 'previewing' => $previewing,
680 'wait' => L10n::t('Please wait'),
684 $arr = ['item' => $item, 'output' => $tmp_item];
685 Addon::callHooks('display_item', $arr);
687 $threads[$threadsid]['id'] = $item['id'];
688 $threads[$threadsid]['network'] = $item['network'];
689 $threads[$threadsid]['items'] = [$arr['output']];
694 $page_template = get_markup_template("threaded_conversation.tpl");
696 $conv = new Thread($mode, $preview, $writable);
699 * get all the topmost parents
700 * this shouldn't be needed, as we should have only them in our array
701 * But for now, this array respects the old style, just in case
703 foreach ($items as $item) {
706 foreach ($arr_blocked as $b) {
707 if ($b && link_compare($item['author-link'], $b)) {
717 // Can we put this after the visibility check?
718 builtin_activity_puller($item, $conv_responses);
720 // Only add what is visible
721 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
725 if (!visible_activity($item)) {
729 /// @todo Check if this call is needed or not
730 $arr = ['item' => $item];
731 Addon::callHooks('display_item', $arr);
733 $item['pagedrop'] = $page_dropping;
735 if ($item['id'] == $item['parent']) {
736 $item_object = new Post($item);
737 $conv->addParent($item_object);
741 $threads = $conv->getTemplateData($conv_responses);
743 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
749 $o = replace_macros($page_template, [
750 '$baseurl' => System::baseUrl($ssl_state),
751 '$return_path' => $a->query_string,
752 '$live_update' => $live_update_div,
753 '$remove' => L10n::t('remove'),
756 '$threads' => $threads,
757 '$dropping' => ($page_dropping && Feature::isEnabled(local_user(), 'multi_delete') ? L10n::t('Delete Selected Items') : False),
764 * @brief Add comments to top level entries that had been fetched before
766 * The system will fetch the comments for the local user whenever possible.
767 * This behaviour is currently needed to allow commenting on Friendica posts.
769 * @param array $parents Parent items
771 * @return array items with parents and comments
773 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
774 $max_comments = Config::get('system', 'max_comments', 100);
776 $params = ['order' => ['uid', 'commented' => true]];
778 if ($max_comments > 0) {
779 $params['limit'] = $max_comments;
784 foreach ($parents AS $parent) {
785 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) ",
786 $parent['uri'], local_user()];
787 if ($block_authors) {
788 $condition[0] .= "AND NOT `author`.`hidden`";
790 $thread_items = Item::selectForUser(local_user(), [], $condition, $params);
792 $comments = Item::inArray($thread_items);
794 if (count($comments) != 0) {
795 $items = array_merge($items, $comments);
799 foreach ($items as $index => $item) {
800 if ($item['uid'] == 0) {
801 $items[$index]['writable'] = in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
805 $items = conv_sort($items, $order);
810 function item_photo_menu($item) {
819 if (local_user() && local_user() == $item['uid'] && $item['parent'] == $item['id'] && !$item['self']) {
820 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
823 $author = ['uid' => 0, 'id' => $item['author-id'],
824 'network' => $item['author-network'], 'url' => $item['author-link']];
825 $profile_link = Contact::magicLinkbyContact($author);
826 $sparkle = (strpos($profile_link, 'redir/') === 0);
831 $condition = ['uid' => local_user(), 'nurl' => normalise_link($item['author-link'])];
832 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
833 if (DBM::is_result($contact)) {
834 $cid = $contact['id'];
835 $network = $contact['network'];
836 $rel = $contact['rel'];
840 $status_link = $profile_link . '?url=status';
841 $photos_link = $profile_link . '?url=photos';
842 $profile_link = $profile_link . '?url=profile';
845 if ($cid && !$item['self']) {
846 $poke_link = 'poke/?f=&c=' . $cid;
847 $contact_url = 'contacts/' . $cid;
848 $posts_link = 'contacts/' . $cid . '/posts';
850 if (in_array($network, [NETWORK_DFRN, NETWORK_DIASPORA])) {
851 $pm_url = 'message/new/' . $cid;
857 L10n::t('Follow Thread') => $sub_link,
858 L10n::t('View Status') => $status_link,
859 L10n::t('View Profile') => $profile_link,
860 L10n::t('View Photos') => $photos_link,
861 L10n::t('Network Posts') => $posts_link,
862 L10n::t('View Contact') => $contact_url,
863 L10n::t('Send PM') => $pm_url
866 if ($network == NETWORK_DFRN) {
867 $menu[L10n::t("Poke")] = $poke_link;
870 if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
871 in_array($item['network'], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA])) {
872 $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
875 $menu = [L10n::t('View Profile') => $item['author-link']];
878 $args = ['item' => $item, 'menu' => $menu];
880 Addon::callHooks('item_photo_menu', $args);
882 $menu = $args['menu'];
885 foreach ($menu as $k => $v) {
886 if (strpos($v, 'javascript:') === 0) {
888 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
890 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
897 * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
898 * Increments the count of each matching activity and adds a link to the author as needed.
901 * @param array &$conv_responses (already created with builtin activity structure)
904 function builtin_activity_puller($item, &$conv_responses) {
905 foreach ($conv_responses as $mode => $v) {
911 $verb = ACTIVITY_LIKE;
914 $verb = ACTIVITY_DISLIKE;
917 $verb = ACTIVITY_ATTEND;
920 $verb = ACTIVITY_ATTENDNO;
923 $verb = ACTIVITY_ATTENDMAYBE;
929 if (activity_match($item['verb'], $verb) && ($item['id'] != $item['parent'])) {
930 $author = ['uid' => 0, 'id' => $item['author-id'],
931 'network' => $item['author-network'], 'url' => $item['author-link']];
932 $url = Contact::magicLinkbyContact($author);
933 if (strpos($url, 'redir/') === 0) {
934 $sparkle = ' class="sparkle" ';
937 $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
939 if (!x($item, 'thr-parent')) {
940 $item['thr-parent'] = $item['parent-uri'];
943 if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
944 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
945 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
948 // only list each unique author once
949 if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
953 if (!isset($conv_responses[$mode][$item['thr-parent']])) {
954 $conv_responses[$mode][$item['thr-parent']] = 1;
956 $conv_responses[$mode][$item['thr-parent']] ++;
959 if (public_contact() == $item['author-id']) {
960 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
963 $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
965 // there can only be one activity verb per item so if we found anything, we can stop looking
972 * Format the vote text for a profile item
973 * @param int $cnt = number of people who vote the item
974 * @param array $arr = array of pre-linked names of likers/dislikers
975 * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
976 * @param int $id = item id
977 * @return string formatted text
979 function format_like($cnt, array $arr, $type, $id) {
986 // Phrase if there is only one liker. In other cases it will be uses for the expanded
987 // list which show all likers
990 $phrase = L10n::t('%s likes this.', $likers);
993 $phrase = L10n::t('%s doesn\'t like this.', $likers);
996 $phrase = L10n::t('%s attends.', $likers);
999 $phrase = L10n::t('%s doesn\'t attend.', $likers);
1001 case 'attendmaybe' :
1002 $phrase = L10n::t('%s attends maybe.', $likers);
1008 $total = count($arr);
1009 if ($total >= MAX_LIKERS) {
1010 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1012 if ($total < MAX_LIKERS) {
1013 $last = L10n::t('and') . ' ' . $arr[count($arr)-1];
1014 $arr2 = array_slice($arr, 0, -1);
1015 $str = implode(', ', $arr2) . ' ' . $last;
1017 if ($total >= MAX_LIKERS) {
1018 $str = implode(', ', $arr);
1019 $str .= L10n::t('and %d other people', $total - MAX_LIKERS);
1024 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1028 $phrase = L10n::t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
1029 $explikers = L10n::t('%s like this.', $likers);
1032 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1033 $explikers = L10n::t('%s don\'t like this.', $likers);
1036 $phrase = L10n::t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
1037 $explikers = L10n::t('%s attend.', $likers);
1040 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1041 $explikers = L10n::t('%s don\'t attend.', $likers);
1044 $phrase = L10n::t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1045 $explikers = L10n::t('%s attend maybe.', $likers);
1049 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1053 $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), [
1054 '$phrase' => $phrase,
1063 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1067 $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), []) : '';
1069 $tpl = get_markup_template('jot-header.tpl');
1070 $a->page['htmlhead'] .= replace_macros($tpl, [
1071 '$newpost' => 'true',
1072 '$baseurl' => System::baseUrl(true),
1073 '$geotag' => $geotag,
1074 '$nickname' => $x['nickname'],
1075 '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
1076 '$linkurl' => L10n::t('Please enter a link URL:'),
1077 '$vidurl' => L10n::t("Please enter a video link/URL:"),
1078 '$audurl' => L10n::t("Please enter an audio link/URL:"),
1079 '$term' => L10n::t('Tag term:'),
1080 '$fileas' => L10n::t('Save to Folder:'),
1081 '$whereareu' => L10n::t('Where are you right now?'),
1082 '$delitems' => L10n::t("Delete item\x28s\x29?")
1085 $tpl = get_markup_template('jot-end.tpl');
1086 $a->page['end'] .= replace_macros($tpl, [
1087 '$newpost' => 'true',
1088 '$baseurl' => System::baseUrl(true),
1089 '$geotag' => $geotag,
1090 '$nickname' => $x['nickname'],
1091 '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
1092 '$linkurl' => L10n::t('Please enter a link URL:'),
1093 '$vidurl' => L10n::t("Please enter a video link/URL:"),
1094 '$audurl' => L10n::t("Please enter an audio link/URL:"),
1095 '$term' => L10n::t('Tag term:'),
1096 '$fileas' => L10n::t('Save to Folder:'),
1097 '$whereareu' => L10n::t('Where are you right now?')
1101 Addon::callHooks('jot_tool', $jotplugins);
1103 // Private/public post links for the non-JS ACL form
1105 if (x($_REQUEST, 'public')) {
1109 $query_str = $a->query_string;
1110 if (strpos($query_str, 'public=1') !== false) {
1111 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1115 * I think $a->query_string may never have ? in it, but I could be wrong
1116 * It looks like it's from the index.php?q=[etc] rewrite that the web
1117 * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1119 if (strpos($query_str, '?') === false) {
1120 $public_post_link = '?public=1';
1122 $public_post_link = '&public=1';
1125 // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1126 $tpl = get_markup_template("jot.tpl");
1128 $o .= replace_macros($tpl,[
1129 '$new_post' => L10n::t('New Post'),
1130 '$return_path' => $query_str,
1131 '$action' => 'item',
1132 '$share' => defaults($x, 'button', L10n::t('Share')),
1133 '$upload' => L10n::t('Upload photo'),
1134 '$shortupload' => L10n::t('upload photo'),
1135 '$attach' => L10n::t('Attach file'),
1136 '$shortattach' => L10n::t('attach file'),
1137 '$weblink' => L10n::t('Insert web link'),
1138 '$shortweblink' => L10n::t('web link'),
1139 '$video' => L10n::t('Insert video link'),
1140 '$shortvideo' => L10n::t('video link'),
1141 '$audio' => L10n::t('Insert audio link'),
1142 '$shortaudio' => L10n::t('audio link'),
1143 '$setloc' => L10n::t('Set your location'),
1144 '$shortsetloc' => L10n::t('set location'),
1145 '$noloc' => L10n::t('Clear browser location'),
1146 '$shortnoloc' => L10n::t('clear location'),
1147 '$title' => defaults($x, 'title', ''),
1148 '$placeholdertitle' => L10n::t('Set title'),
1149 '$category' => defaults($x, 'category', ''),
1150 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? L10n::t("Categories \x28comma-separated list\x29") : '',
1151 '$wait' => L10n::t('Please wait'),
1152 '$permset' => L10n::t('Permission settings'),
1153 '$shortpermset' => L10n::t('permissions'),
1154 '$wall' => $notes_cid ? 0 : 1,
1155 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1156 '$content' => defaults($x, 'content', ''),
1157 '$post_id' => defaults($x, 'post_id', ''),
1158 '$baseurl' => System::baseUrl(true),
1159 '$defloc' => $x['default_location'],
1160 '$visitor' => $x['visitor'],
1161 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1162 '$public' => L10n::t('Public post'),
1163 '$lockstate' => $x['lockstate'],
1164 '$bang' => $x['bang'],
1165 '$profile_uid' => $x['profile_uid'],
1166 '$preview' => Feature::isEnabled($x['profile_uid'], 'preview') ? L10n::t('Preview') : '',
1167 '$jotplugins' => $jotplugins,
1168 '$notes_cid' => $notes_cid,
1169 '$sourceapp' => L10n::t($a->sourcename),
1170 '$cancel' => L10n::t('Cancel'),
1171 '$rand_num' => random_digits(12),
1173 // ACL permissions box
1174 '$acl' => $x['acl'],
1175 '$group_perms' => L10n::t('Post to Groups'),
1176 '$contact_perms' => L10n::t('Post to Contacts'),
1177 '$private' => L10n::t('Private post'),
1178 '$is_private' => $private_post,
1179 '$public_link' => $public_post_link,
1181 //jot nav tab (used in some themes)
1182 '$message' => L10n::t('Message'),
1183 '$browser' => L10n::t('Browser'),
1187 if ($popup == true) {
1188 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1195 * Plucks the children of the given parent from a given item list.
1197 * @brief Plucks all the children in the given item list of the given parent
1199 * @param array $item_list
1200 * @param array $parent
1201 * @param bool $recursive
1204 function get_item_children(array &$item_list, array $parent, $recursive = true)
1207 foreach ($item_list as $i => $item) {
1208 if ($item['id'] != $item['parent']) {
1210 // Fallback to parent-uri if thr-parent is not set
1211 $thr_parent = $item['thr-parent'];
1212 if ($thr_parent == '') {
1213 $thr_parent = $item['parent-uri'];
1216 if ($thr_parent == $parent['uri']) {
1217 $item['children'] = get_item_children($item_list, $item);
1218 $children[] = $item;
1219 unset($item_list[$i]);
1221 } elseif ($item['parent'] == $parent['id']) {
1222 $children[] = $item;
1223 unset($item_list[$i]);
1231 * @brief Recursively sorts a tree-like item array
1233 * @param array $items
1236 function sort_item_children(array $items)
1239 usort($result, 'sort_thr_created_rev');
1240 foreach ($result as $k => $i) {
1241 if (isset($result[$k]['children'])) {
1242 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1249 * @brief Recursively add all children items at the top level of a list
1251 * @param array $children List of items to append
1252 * @param array $item_list
1254 function add_children_to_list(array $children, array &$item_list)
1256 foreach ($children as $child) {
1257 $item_list[] = $child;
1258 if (isset($child['children'])) {
1259 add_children_to_list($child['children'], $item_list);
1265 * This recursive function takes the item tree structure created by conv_sort() and
1266 * flatten the extraneous depth levels when people reply sequentially, removing the
1267 * stairs effect in threaded conversations limiting the available content width.
1269 * The basic principle is the following: if a post item has only one reply and is
1270 * the last reply of its parent, then the reply is moved to the parent.
1272 * This process is rendered somewhat more complicated because items can be either
1273 * replies or likes, and these don't factor at all in the reply count/last reply.
1275 * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1277 * @param array $parent A tree-like array of items
1280 function smart_flatten_conversation(array $parent)
1282 if (!isset($parent['children']) || count($parent['children']) == 0) {
1286 // We use a for loop to ensure we process the newly-moved items
1287 for ($i = 0; $i < count($parent['children']); $i++) {
1288 $child = $parent['children'][$i];
1290 if (isset($child['children']) && count($child['children'])) {
1291 // This helps counting only the regular posts
1292 $count_post_closure = function($var) {
1293 return $var['verb'] === ACTIVITY_POST;
1296 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1298 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1300 // If there's only one child's children post and this is the last child post
1301 if ($child_post_count == 1 && $remaining_post_count == 1) {
1303 // Searches the post item in the children
1305 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1309 $moved_item = $child['children'][$j];
1310 unset($parent['children'][$i]['children'][$j]);
1311 $parent['children'][] = $moved_item;
1313 $parent['children'][$i] = smart_flatten_conversation($child);
1323 * Expands a flat list of items into corresponding tree-like conversation structures,
1324 * sort the top-level posts either on "created" or "commented", and finally
1325 * append all the items at the top level (???)
1327 * @brief Expands a flat item list into a conversation array for display
1329 * @param array $item_list A list of items belonging to one or more conversations
1330 * @param string $order Either on "created" or "commented"
1333 function conv_sort(array $item_list, $order)
1337 if (!(is_array($item_list) && count($item_list))) {
1343 // Dedupes the item list on the uri to prevent infinite loops
1344 foreach ($item_list as $item) {
1345 $item_array[$item['uri']] = $item;
1348 // Extract the top level items
1349 foreach ($item_array as $item) {
1350 if ($item['id'] == $item['parent']) {
1355 if (stristr($order, 'created')) {
1356 usort($parents, 'sort_thr_created');
1357 } elseif (stristr($order, 'commented')) {
1358 usort($parents, 'sort_thr_commented');
1362 * Plucks children from the item_array, second pass collects eventual orphan
1363 * items and add them as children of their top-level post.
1365 foreach ($parents as $i => $parent) {
1366 $parents[$i]['children'] =
1367 array_merge(get_item_children($item_array, $parent, true),
1368 get_item_children($item_array, $parent, false));
1371 foreach ($parents as $i => $parent) {
1372 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1375 if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1376 foreach ($parents as $i => $parent) {
1377 $parents[$i] = smart_flatten_conversation($parent);
1381 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1382 /// However, this apparently ensures responses (likes, attendance) display (?!)
1383 foreach ($parents as $parent) {
1384 if (count($parent['children'])) {
1385 add_children_to_list($parent['children'], $parents);
1393 * @brief usort() callback to sort item arrays by the created key
1399 function sort_thr_created(array $a, array $b)
1401 return strcmp($b['created'], $a['created']);
1405 * @brief usort() callback to reverse sort item arrays by the created key
1411 function sort_thr_created_rev(array $a, array $b)
1413 return strcmp($a['created'], $b['created']);
1417 * @brief usort() callback to sort item arrays by the commented key
1423 function sort_thr_commented(array $a, array $b)
1425 return strcmp($b['commented'], $a['commented']);
1428 function render_location_dummy(array $item) {
1429 if (x($item, 'location') && !empty($item['location'])) {
1430 return $item['location'];
1433 if (x($item, 'coord') && !empty($item['coord'])) {
1434 return $item['coord'];
1438 function get_responses(array $conv_responses, array $response_verbs, $ob, array $item) {
1440 foreach ($response_verbs as $v) {
1442 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
1443 $ret[$v]['list'] = defaults($conv_responses[$v], $item['uri'] . '-l', []);
1444 $ret[$v]['self'] = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1445 if (count($ret[$v]['list']) > MAX_LIKERS) {
1446 $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1447 array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1448 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . L10n::t('View all') . '</b></a>');
1450 $ret[$v]['list_part'] = '';
1452 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1453 $ret[$v]['title'] = $conv_responses[$v]['title'];
1457 foreach ($ret as $key) {
1458 if ($key['count'] == true) {
1462 $ret['count'] = $count;
1467 function get_response_button_text($v, $count)
1471 $return = L10n::tt('Like', 'Likes', $count);
1474 $return = L10n::tt('Dislike', 'Dislikes', $count);
1477 $return = L10n::tt('Attending', 'Attending', $count);
1480 $return = L10n::tt('Not Attending', 'Not Attending', $count);
1483 $return = L10n::tt('Undecided', 'Undecided', $count);