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\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Profile;
18 use Friendica\Model\Item;
19 use Friendica\Object\Post;
20 use Friendica\Object\Thread;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Temporal;
23 use Friendica\Util\XML;
25 function item_extract_images($body) {
32 $img_start = strpos($orig_body, '[img');
33 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
34 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
35 while (($img_st_close !== false) && ($img_end !== false)) {
37 $img_st_close++; // make it point to AFTER the closing bracket
38 $img_end += $img_start;
40 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
41 // This is an embedded image
43 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
44 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
48 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
51 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
53 if ($orig_body === false) {
54 // in case the body ends on a closing image tag
58 $img_start = strpos($orig_body, '[img');
59 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
60 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
63 $new_body = $new_body . $orig_body;
65 return ['body' => $new_body, 'images' => $saved_image];
68 function item_redir_and_replace_images($body, $images, $cid) {
74 $pos = BBCode::getTagPosition($origbody, 'url', 0);
75 while ($pos !== false && $cnt < 1000) {
77 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
78 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
79 . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
81 $newbody .= substr($origbody, 0, $pos['start']['open']);
82 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
83 $origbody = substr($origbody, $pos['end']['close']);
84 if ($origbody === false) {
88 $subject = preg_replace($search, $replace, $subject);
92 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
93 $pos = BBCode::getTagPosition($origbody, 'url', 0);
95 $newbody .= $origbody;
98 foreach ($images as $image) {
100 * We're depending on the property of 'foreach' (specified on the PHP website) that
101 * it loops over the array starting from the first element and going sequentially
102 * to the last element.
104 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
111 * Render actions localized
113 function localize_item(&$item) {
115 $extracted = item_extract_images($item['body']);
116 if ($extracted['images']) {
117 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
120 /// @TODO Separted ???
121 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
122 if (activity_match($item['verb'], ACTIVITY_LIKE)
123 || activity_match($item['verb'], ACTIVITY_DISLIKE)
124 || activity_match($item['verb'], ACTIVITY_ATTEND)
125 || activity_match($item['verb'], ACTIVITY_ATTENDNO)
126 || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
128 /// @TODO may hurt performance
129 $r = q("SELECT * FROM `item`, `contact`
130 WHERE `item`.`contact-id`=`contact`.`id`
131 AND `item`.`uri`='%s'",
132 dbesc($item['parent-uri']));
133 if (!DBM::is_result($r)) {
138 $author = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
139 $objauthor = '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
141 switch ($obj['verb']) {
143 switch ($obj['object-type']) {
144 case ACTIVITY_OBJ_EVENT:
145 $post_type = L10n::t('event');
148 $post_type = L10n::t('status');
152 if ($obj['resource-id']) {
153 $post_type = L10n::t('photo');
155 preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
156 $rr['plink'] = $m[1];
158 $post_type = L10n::t('status');
162 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
164 if (activity_match($item['verb'], ACTIVITY_LIKE)) {
165 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
166 } elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
167 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
168 } elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
169 $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s');
170 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
171 $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s');
172 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
173 $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s');
176 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
179 if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
181 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
183 $Aname = $item['author-name'];
184 $Alink = $item['author-link'];
186 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
188 $obj = XML::parseString($xmlhead.$item['object']);
189 $links = XML::parseString($xmlhead."<links>".unxmlify($obj->link)."</links>");
191 $Bname = $obj->title;
192 $Blink = ""; $Bphoto = "";
193 foreach ($links->link as $l) {
194 $atts = $l->attributes();
195 switch ($atts['rel']) {
196 case "alternate": $Blink = $atts['href'];
197 case "photo": $Bphoto = $atts['href'];
201 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
202 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
204 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img]' . $Bphoto . '[/img][/url]';
207 $item['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$Bphoto;
210 if (stristr($item['verb'], ACTIVITY_POKE)) {
211 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
215 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) {
219 $Aname = $item['author-name'];
220 $Alink = $item['author-link'];
222 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
224 $obj = XML::parseString($xmlhead.$item['object']);
225 $links = XML::parseString($xmlhead."<links>".unxmlify($obj->link)."</links>");
227 $Bname = $obj->title;
230 foreach ($links->link as $l) {
231 $atts = $l->attributes();
232 switch ($atts['rel']) {
233 case "alternate": $Blink = $atts['href'];
234 case "photo": $Bphoto = $atts['href'];
238 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
239 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
241 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
245 * we can't have a translation string with three positions but no distinguishable text
246 * So here is the translate string.
248 $txt = L10n::t('%1$s poked %2$s');
250 // now translate the verb
251 $poked_t = trim(sprintf($txt, "", ""));
252 $txt = str_replace( $poked_t, L10n::t($verb), $txt);
254 // then do the sprintf on the translation string
256 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
260 if (activity_match($item['verb'], ACTIVITY_TAG)) {
261 /// @TODO may hurt performance "joining" two tables + asterisk
262 $r = q("SELECT * FROM `item`, `contact`
263 WHERE `item`.`contact-id`=`contact`.`id`
264 AND `item`.`uri`='%s'",
265 dbesc($item['parent-uri']));
267 if (!DBM::is_result($r)) {
273 $author = '[url=' . Contact::magicLinkById($item['author-id']) . ']' . $item['author-name'] . '[/url]';
274 $objauthor = '[url=' . Contact::magicLinkById($obj['author-id']) . ']' . $obj['author-name'] . '[/url]';
276 switch ($obj['verb']) {
278 switch ($obj['object-type']) {
279 case ACTIVITY_OBJ_EVENT:
280 $post_type = L10n::t('event');
283 $post_type = L10n::t('status');
287 if ($obj['resource-id']) {
288 $post_type = L10n::t('photo');
289 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
290 $rr['plink'] = $m[1];
292 $post_type = L10n::t('status');
294 // Let's break everthing ... ;-)
297 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
299 $parsedobj = XML::parseString($xmlhead.$item['object']);
301 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
302 $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag );
306 if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
307 if ($item['object-type'] == "") {
311 $Aname = $item['author-name'];
312 $Alink = $item['author-link'];
314 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
316 $obj = XML::parseString($xmlhead.$item['object']);
317 if (strlen($obj->id)) {
318 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
323 if (DBM::is_result($r) && $r[0]['plink']) {
325 $Bname = $target['author-name'];
326 $Blink = $target['author-link'];
327 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
328 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
329 $P = '[url=' . $target['plink'] . ']' . L10n::t('post/item') . '[/url]';
330 $item['body'] = L10n::t('%1$s marked %2$s\'s %3$s as favorite', $A, $B, $P)."\n";
335 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
336 foreach ($matches as $mtch) {
337 if (!strpos($mtch[1], 'zrl=')) {
338 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
343 // add zrl's to public images
344 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
345 if (preg_match($photo_pattern, $item['body'])) {
346 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
347 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
350 // add sparkle links to appropriate permalinks
351 $item['plink'] = Contact::magicLinkById($item['author-id'], $item['plink']);
355 * Count the total of comments on this item and its desendants
356 * @TODO proper type-hint + doc-tag
358 function count_descendants($item) {
359 $total = count($item['children']);
362 foreach ($item['children'] as $child) {
363 if (!visible_activity($child)) {
366 $total += count_descendants($child);
373 function visible_activity($item) {
376 * likes (etc.) can apply to other things besides posts. Check if they are post children,
377 * in which case we handle them specially
379 $hidden_activities = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
380 foreach ($hidden_activities as $act) {
381 if (activity_match($item['verb'], $act)) {
386 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
387 if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) {
395 * "Render" a conversation or list of items for HTML display.
396 * There are two major forms of display:
397 * - Sequential or unthreaded ("New Item View" or search results)
398 * - conversation view
399 * The $mode parameter decides between the various renderings and also
400 * figures out how to determine page owner and other contextual items
401 * that are based on unique features of the calling module.
404 function conversation(App $a, $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0) {
405 require_once 'mod/proxy.php';
407 $ssl_state = ((local_user()) ? true : false);
410 $live_update_div = '';
415 $str_blocked = PConfig::get(local_user(), 'system', 'blocked');
417 $arr_blocked = explode(',', $str_blocked);
418 for ($x = 0; $x < count($arr_blocked); $x ++) {
419 $arr_blocked[$x] = trim($arr_blocked[$x]);
425 $previewing = (($preview) ? ' preview ' : '');
427 if ($mode === 'network') {
428 $items = conversation_add_children($items, false, $order, $uid);
429 $profile_owner = local_user();
432 * The special div is needed for liveUpdate to kick in for this page.
433 * We only launch liveUpdate if you aren't filtering in some incompatible
434 * way and also you aren't writing a comment (discovered in javascript).
436 $live_update_div = '<div id="live-network"></div>' . "\r\n"
437 . "<script> var profile_uid = " . $_SESSION['uid']
438 . "; var netargs = '" . substr($a->cmd, 8)
440 . ((x($_GET, 'cid')) ? '&cid=' . $_GET['cid'] : '')
441 . ((x($_GET, 'search')) ? '&search=' . $_GET['search'] : '')
442 . ((x($_GET, 'star')) ? '&star=' . $_GET['star'] : '')
443 . ((x($_GET, 'order')) ? '&order=' . $_GET['order'] : '')
444 . ((x($_GET, 'bmark')) ? '&bmark=' . $_GET['bmark'] : '')
445 . ((x($_GET, 'liked')) ? '&liked=' . $_GET['liked'] : '')
446 . ((x($_GET, 'conv')) ? '&conv=' . $_GET['conv'] : '')
447 . ((x($_GET, 'nets')) ? '&nets=' . $_GET['nets'] : '')
448 . ((x($_GET, 'cmin')) ? '&cmin=' . $_GET['cmin'] : '')
449 . ((x($_GET, 'cmax')) ? '&cmax=' . $_GET['cmax'] : '')
450 . ((x($_GET, 'file')) ? '&file=' . $_GET['file'] : '')
452 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
454 } elseif ($mode === 'profile') {
455 $profile_owner = $a->profile['profile_uid'];
459 if (x($_GET, 'tab')) {
460 $tab = notags(trim($_GET['tab']));
462 if ($tab === 'posts') {
464 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
465 * because browser prefetching might change it on us. We have to deliver it with the page.
468 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
469 . "<script> var profile_uid = " . $a->profile['profile_uid']
470 . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
473 } elseif ($mode === 'notes') {
474 $profile_owner = local_user();
476 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
477 . "<script> var profile_uid = " . local_user()
478 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
480 } elseif ($mode === 'display') {
481 $profile_owner = $a->profile['uid'];
483 $live_update_div = '<div id="live-display"></div>' . "\r\n"
484 . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
485 . " var profile_page = 1; </script>";
487 } elseif ($mode === 'community') {
488 $items = conversation_add_children($items, true, $order, $uid);
491 $live_update_div = '<div id="live-community"></div>' . "\r\n"
492 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 10)
493 ."/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
495 } elseif ($mode === 'search') {
496 $live_update_div = '<div id="live-search"></div>' . "\r\n";
499 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
502 $_SESSION['return_url'] = $a->query_string;
505 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
506 Addon::callHooks('conversation_start',$cb);
508 $items = $cb['items'];
511 'like' => ['title' => L10n::t('Likes','title')], 'dislike' => ['title' => L10n::t('Dislikes','title')],
512 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
515 // array with html for each thread (parent+comments)
519 $page_template = get_markup_template("conversation.tpl");
521 if ($items && count($items)) {
522 if ($mode === 'community') {
525 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
532 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
535 * "New Item View" on network page or search page results
536 * - just loop through the items and format them minimally for display
539 $tpl = 'search_item.tpl';
541 foreach ($items as $item) {
543 if (!visible_activity($item)) {
549 foreach ($arr_blocked as $b) {
550 if ($b && link_compare($item['author-link'], $b)) {
567 // prevent private email from leaking.
568 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
572 if ($item['network'] == NETWORK_FEED) {
573 $item['author-avatar'] = $item['contact-avatar'];
574 $item['author-name'] = $item['contact-name'];
575 $item['owner-avatar'] = $item['contact-avatar'];
576 $item['owner-name'] = $item['contact-name'];
579 $profile_name = (strlen($item['author-name']) ? $item['author-name'] : $item['name']);
580 if ($item['author-link'] && !$item['author-name']) {
581 $profile_name = $item['author-link'];
584 $tags = \Friendica\Model\Term::populateTagsFromItem($item);
586 $profile_link = Contact::magicLinkbyId($item['author-id']);
588 if (strpos($profile_link, 'redir/') === 0) {
589 $sparkle = ' sparkle';
592 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
593 Addon::callHooks('render_location',$locate);
595 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
597 localize_item($item);
598 if ($mode === 'network-new') {
605 'dropping' => $dropping,
606 'pagedrop' => $page_dropping,
607 'select' => L10n::t('Select'),
608 'delete' => L10n::t('Delete'),
612 $isstarred = "unstarred";
615 $likebuttons = false;
617 $body = prepare_body($item, true, $preview);
619 list($categories, $folders) = get_cats_and_terms($item);
621 $profile_name_e = $profile_name;
623 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
624 $title_e = ucfirst($item['content-warning']);
626 $title_e = $item['title'];
630 $tags_e = $tags['tags'];
631 $hashtags_e = $tags['hashtags'];
632 $mentions_e = $tags['mentions'];
633 $location_e = $location;
634 $owner_name_e = $owner_name;
638 'id' => (($preview) ? 'P0' : $item['item_id']),
639 'guid' => (($preview) ? 'Q0' : $item['guid']),
640 'network' => $item['network'],
641 'network_name' => ContactSelector::networkToName($item['network'], $profile_link),
642 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
643 'profile_url' => $profile_link,
644 'item_photo_menu' => item_photo_menu($item),
645 'name' => $profile_name_e,
646 'sparkle' => $sparkle,
648 'thumb' => System::removedBaseUrl(proxy_url($item['author-avatar'], false, PROXY_SIZE_THUMB)),
652 'hashtags' => $hashtags_e,
653 'mentions' => $mentions_e,
654 'txt_cats' => L10n::t('Categories:'),
655 'txt_folders' => L10n::t('Filed under:'),
656 'has_cats' => ((count($categories)) ? 'true' : ''),
657 'has_folders' => ((count($folders)) ? 'true' : ''),
658 'categories' => $categories,
659 'folders' => $folders,
660 'text' => strip_tags($body_e),
661 'localtime' => DateTimeFormat::local($item['created'], 'r'),
662 'ago' => (($item['app']) ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
663 'location' => $location_e,
665 'owner_name' => $owner_name_e,
666 'owner_url' => $owner_url,
667 'owner_photo' => System::removedBaseUrl(proxy_url($item['owner-avatar'], false, PROXY_SIZE_THUMB)),
668 'plink' => get_plink($item),
670 'isstarred' => $isstarred,
673 'vote' => $likebuttons,
677 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> L10n::t('View in context')]),
678 'previewing' => $previewing,
679 'wait' => L10n::t('Please wait'),
683 $arr = ['item' => $item, 'output' => $tmp_item];
684 Addon::callHooks('display_item', $arr);
686 $threads[$threadsid]['id'] = $item['item_id'];
687 $threads[$threadsid]['network'] = $item['network'];
688 $threads[$threadsid]['items'] = [$arr['output']];
693 $page_template = get_markup_template("threaded_conversation.tpl");
695 $conv = new Thread($mode, $preview, $writable);
698 * get all the topmost parents
699 * this shouldn't be needed, as we should have only them in our array
700 * But for now, this array respects the old style, just in case
702 foreach ($items as $item) {
705 foreach ($arr_blocked as $b) {
706 if ($b && link_compare($item['author-link'], $b)) {
716 // Can we put this after the visibility check?
717 builtin_activity_puller($item, $conv_responses);
719 // Only add what is visible
720 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
724 if (!visible_activity($item)) {
728 Addon::callHooks('display_item', $arr);
730 $item['pagedrop'] = $page_dropping;
732 if ($item['id'] == $item['parent']) {
733 $item_object = new Post($item);
734 $conv->addParent($item_object);
738 $threads = $conv->getTemplateData($conv_responses);
740 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
746 $o = replace_macros($page_template, [
747 '$baseurl' => System::baseUrl($ssl_state),
748 '$return_path' => $a->query_string,
749 '$live_update' => $live_update_div,
750 '$remove' => L10n::t('remove'),
753 '$threads' => $threads,
754 '$dropping' => ($page_dropping && Feature::isEnabled(local_user(), 'multi_delete') ? L10n::t('Delete Selected Items') : False),
761 * @brief Add comments to top level entries that had been fetched before
763 * The system will fetch the comments for the local user whenever possible.
764 * This behaviour is currently needed to allow commenting on Friendica posts.
766 * @param array $parents Parent items
768 * @return array items with parents and comments
770 function conversation_add_children($parents, $block_authors, $order, $uid) {
771 $max_comments = Config::get('system', 'max_comments', 100);
773 $params = ['order' => ['uid', 'commented' => true]];
775 if ($max_comments > 0) {
776 $params['limit'] = $max_comments;
781 foreach ($parents AS $parent) {
782 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) ",
783 $parent['uri'], local_user()];
784 if ($block_authors) {
785 $condition[0] .= "AND NOT `author`.`hidden`";
787 $thread_items = Item::selectForUser(local_user(), [], $condition, $params);
789 $comments = dba::inArray($thread_items);
791 if (count($comments) != 0) {
792 $items = array_merge($items, $comments);
796 foreach ($items as $index => $item) {
797 if ($item['uid'] == 0) {
798 $items[$index]['writable'] = in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
802 $items = conv_sort($items, $order);
807 function item_photo_menu($item) {
816 if (local_user() && local_user() == $item['uid'] && $item['parent'] == $item['id'] && !$item['self']) {
817 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
820 $profile_link = Contact::magicLinkById($item['author-id']);
821 $sparkle = (strpos($profile_link, 'redir/') === 0);
826 $condition = ['uid' => local_user(), 'nurl' => normalise_link($item['author-link'])];
827 $contact = dba::selectFirst('contact', ['id', 'network', 'rel'], $condition);
828 if (DBM::is_result($contact)) {
829 $cid = $contact['id'];
830 $network = $contact['network'];
831 $rel = $contact['rel'];
835 $status_link = $profile_link . '?url=status';
836 $photos_link = $profile_link . '?url=photos';
837 $profile_link = $profile_link . '?url=profile';
840 if ($cid && !$item['self']) {
841 $poke_link = 'poke/?f=&c=' . $cid;
842 $contact_url = 'contacts/' . $cid;
843 $posts_link = 'contacts/' . $cid . '/posts';
845 if (in_array($network, [NETWORK_DFRN, NETWORK_DIASPORA])) {
846 $pm_url = 'message/new/' . $cid;
852 L10n::t('Follow Thread') => $sub_link,
853 L10n::t('View Status') => $status_link,
854 L10n::t('View Profile') => $profile_link,
855 L10n::t('View Photos') => $photos_link,
856 L10n::t('Network Posts') => $posts_link,
857 L10n::t('View Contact') => $contact_url,
858 L10n::t('Send PM') => $pm_url
861 if ($network == NETWORK_DFRN) {
862 $menu[L10n::t("Poke")] = $poke_link;
865 if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
866 in_array($item['network'], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA])) {
867 $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
870 $menu = [L10n::t('View Profile') => $item['author-link']];
873 $args = ['item' => $item, 'menu' => $menu];
875 Addon::callHooks('item_photo_menu', $args);
877 $menu = $args['menu'];
880 foreach ($menu as $k => $v) {
881 if (strpos($v, 'javascript:') === 0) {
883 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
885 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
892 * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
893 * Increments the count of each matching activity and adds a link to the author as needed.
896 * @param array &$conv_responses (already created with builtin activity structure)
899 function builtin_activity_puller($item, &$conv_responses) {
900 foreach ($conv_responses as $mode => $v) {
906 $verb = ACTIVITY_LIKE;
909 $verb = ACTIVITY_DISLIKE;
912 $verb = ACTIVITY_ATTEND;
915 $verb = ACTIVITY_ATTENDNO;
918 $verb = ACTIVITY_ATTENDMAYBE;
924 if (activity_match($item['verb'], $verb) && ($item['id'] != $item['parent'])) {
925 $url = Contact::MagicLinkbyId($item['author-id']);
926 if (strpos($url, 'redir/') === 0) {
927 $sparkle = ' class="sparkle" ';
930 $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
932 if (!x($item, 'thr-parent')) {
933 $item['thr-parent'] = $item['parent-uri'];
936 if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
937 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
938 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
941 // only list each unique author once
942 if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
946 if (!isset($conv_responses[$mode][$item['thr-parent']])) {
947 $conv_responses[$mode][$item['thr-parent']] = 1;
949 $conv_responses[$mode][$item['thr-parent']] ++;
952 if (public_contact() == $item['author-id']) {
953 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
956 $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
958 // there can only be one activity verb per item so if we found anything, we can stop looking
965 * Format the vote text for a profile item
966 * @param int $cnt = number of people who vote the item
967 * @param array $arr = array of pre-linked names of likers/dislikers
968 * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
969 * @param int $id = item id
970 * @return string formatted text
972 function format_like($cnt, array $arr, $type, $id) {
979 // Phrase if there is only one liker. In other cases it will be uses for the expanded
980 // list which show all likers
983 $phrase = L10n::t('%s likes this.', $likers);
986 $phrase = L10n::t('%s doesn\'t like this.', $likers);
989 $phrase = L10n::t('%s attends.', $likers);
992 $phrase = L10n::t('%s doesn\'t attend.', $likers);
995 $phrase = L10n::t('%s attends maybe.', $likers);
1001 $total = count($arr);
1002 if ($total >= MAX_LIKERS) {
1003 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1005 if ($total < MAX_LIKERS) {
1006 $last = L10n::t('and') . ' ' . $arr[count($arr)-1];
1007 $arr2 = array_slice($arr, 0, -1);
1008 $str = implode(', ', $arr2) . ' ' . $last;
1010 if ($total >= MAX_LIKERS) {
1011 $str = implode(', ', $arr);
1012 $str .= L10n::t('and %d other people', $total - MAX_LIKERS );
1017 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1021 $phrase = L10n::t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
1022 $explikers = L10n::t('%s like this.', $likers);
1025 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1026 $explikers = L10n::t('%s don\'t like this.', $likers);
1029 $phrase = L10n::t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
1030 $explikers = L10n::t('%s attend.', $likers);
1033 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1034 $explikers = L10n::t('%s don\'t attend.', $likers);
1037 $phrase = L10n::t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1038 $explikers = L10n::t('%s attend maybe.', $likers);
1042 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1046 $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), [
1047 '$phrase' => $phrase,
1056 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1060 $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), []) : '';
1062 $tpl = get_markup_template('jot-header.tpl');
1063 $a->page['htmlhead'] .= replace_macros($tpl, [
1064 '$newpost' => 'true',
1065 '$baseurl' => System::baseUrl(true),
1066 '$geotag' => $geotag,
1067 '$nickname' => $x['nickname'],
1068 '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
1069 '$linkurl' => L10n::t('Please enter a link URL:'),
1070 '$vidurl' => L10n::t("Please enter a video link/URL:"),
1071 '$audurl' => L10n::t("Please enter an audio link/URL:"),
1072 '$term' => L10n::t('Tag term:'),
1073 '$fileas' => L10n::t('Save to Folder:'),
1074 '$whereareu' => L10n::t('Where are you right now?'),
1075 '$delitems' => L10n::t("Delete item\x28s\x29?")
1078 $tpl = get_markup_template('jot-end.tpl');
1079 $a->page['end'] .= replace_macros($tpl, [
1080 '$newpost' => 'true',
1081 '$baseurl' => System::baseUrl(true),
1082 '$geotag' => $geotag,
1083 '$nickname' => $x['nickname'],
1084 '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
1085 '$linkurl' => L10n::t('Please enter a link URL:'),
1086 '$vidurl' => L10n::t("Please enter a video link/URL:"),
1087 '$audurl' => L10n::t("Please enter an audio link/URL:"),
1088 '$term' => L10n::t('Tag term:'),
1089 '$fileas' => L10n::t('Save to Folder:'),
1090 '$whereareu' => L10n::t('Where are you right now?')
1094 Addon::callHooks('jot_tool', $jotplugins);
1096 // Private/public post links for the non-JS ACL form
1098 if (x($_REQUEST, 'public')) {
1102 $query_str = $a->query_string;
1103 if (strpos($query_str, 'public=1') !== false) {
1104 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1108 * I think $a->query_string may never have ? in it, but I could be wrong
1109 * It looks like it's from the index.php?q=[etc] rewrite that the web
1110 * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1112 if (strpos($query_str, '?') === false) {
1113 $public_post_link = '?public=1';
1115 $public_post_link = '&public=1';
1118 // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1119 $tpl = get_markup_template("jot.tpl");
1121 $o .= replace_macros($tpl,[
1122 '$new_post' => L10n::t('New Post'),
1123 '$return_path' => $query_str,
1124 '$action' => 'item',
1125 '$share' => defaults($x, 'button', L10n::t('Share')),
1126 '$upload' => L10n::t('Upload photo'),
1127 '$shortupload' => L10n::t('upload photo'),
1128 '$attach' => L10n::t('Attach file'),
1129 '$shortattach' => L10n::t('attach file'),
1130 '$weblink' => L10n::t('Insert web link'),
1131 '$shortweblink' => L10n::t('web link'),
1132 '$video' => L10n::t('Insert video link'),
1133 '$shortvideo' => L10n::t('video link'),
1134 '$audio' => L10n::t('Insert audio link'),
1135 '$shortaudio' => L10n::t('audio link'),
1136 '$setloc' => L10n::t('Set your location'),
1137 '$shortsetloc' => L10n::t('set location'),
1138 '$noloc' => L10n::t('Clear browser location'),
1139 '$shortnoloc' => L10n::t('clear location'),
1140 '$title' => defaults($x, 'title', ''),
1141 '$placeholdertitle' => L10n::t('Set title'),
1142 '$category' => defaults($x, 'category', ''),
1143 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? L10n::t("Categories \x28comma-separated list\x29") : '',
1144 '$wait' => L10n::t('Please wait'),
1145 '$permset' => L10n::t('Permission settings'),
1146 '$shortpermset' => L10n::t('permissions'),
1147 '$ptyp' => $notes_cid ? 'note' : 'wall',
1148 '$content' => defaults($x, 'content', ''),
1149 '$post_id' => defaults($x, 'post_id', ''),
1150 '$baseurl' => System::baseUrl(true),
1151 '$defloc' => $x['default_location'],
1152 '$visitor' => $x['visitor'],
1153 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1154 '$public' => L10n::t('Public post'),
1155 '$lockstate' => $x['lockstate'],
1156 '$bang' => $x['bang'],
1157 '$profile_uid' => $x['profile_uid'],
1158 '$preview' => Feature::isEnabled($x['profile_uid'], 'preview') ? L10n::t('Preview') : '',
1159 '$jotplugins' => $jotplugins,
1160 '$notes_cid' => $notes_cid,
1161 '$sourceapp' => L10n::t($a->sourcename),
1162 '$cancel' => L10n::t('Cancel'),
1163 '$rand_num' => random_digits(12),
1165 // ACL permissions box
1166 '$acl' => $x['acl'],
1167 '$group_perms' => L10n::t('Post to Groups'),
1168 '$contact_perms' => L10n::t('Post to Contacts'),
1169 '$private' => L10n::t('Private post'),
1170 '$is_private' => $private_post,
1171 '$public_link' => $public_post_link,
1173 //jot nav tab (used in some themes)
1174 '$message' => L10n::t('Message'),
1175 '$browser' => L10n::t('Browser'),
1179 if ($popup == true) {
1180 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1187 * Plucks the children of the given parent from a given item list.
1189 * @brief Plucks all the children in the given item list of the given parent
1191 * @param array $item_list
1192 * @param array $parent
1193 * @param bool $recursive
1196 function get_item_children(array &$item_list, array $parent, $recursive = true)
1199 foreach ($item_list as $i => $item) {
1200 if ($item['id'] != $item['parent']) {
1202 // Fallback to parent-uri if thr-parent is not set
1203 $thr_parent = $item['thr-parent'];
1204 if ($thr_parent == '') {
1205 $thr_parent = $item['parent-uri'];
1208 if ($thr_parent == $parent['uri']) {
1209 $item['children'] = get_item_children($item_list, $item);
1210 $children[] = $item;
1211 unset($item_list[$i]);
1213 } elseif ($item['parent'] == $parent['id']) {
1214 $children[] = $item;
1215 unset($item_list[$i]);
1223 * @brief Recursively sorts a tree-like item array
1225 * @param array $items
1228 function sort_item_children(array $items)
1231 usort($result, 'sort_thr_created_rev');
1232 foreach ($result as $k => $i) {
1233 if (isset($result[$k]['children'])) {
1234 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1241 * @brief Recursively add all children items at the top level of a list
1243 * @param array $children List of items to append
1244 * @param array $item_list
1246 function add_children_to_list(array $children, array &$item_list)
1248 foreach ($children as $child) {
1249 $item_list[] = $child;
1250 if (isset($child['children'])) {
1251 add_children_to_list($child['children'], $item_list);
1257 * This recursive function takes the item tree structure created by conv_sort() and
1258 * flatten the extraneous depth levels when people reply sequentially, removing the
1259 * stairs effect in threaded conversations limiting the available content width.
1261 * The basic principle is the following: if a post item has only one reply and is
1262 * the last reply of its parent, then the reply is moved to the parent.
1264 * This process is rendered somewhat more complicated because items can be either
1265 * replies or likes, and these don't factor at all in the reply count/last reply.
1267 * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1269 * @param array $parent A tree-like array of items
1272 function smart_flatten_conversation(array $parent)
1274 if (!isset($parent['children']) || count($parent['children']) == 0) {
1278 // We use a for loop to ensure we process the newly-moved items
1279 for ($i = 0; $i < count($parent['children']); $i++) {
1280 $child = $parent['children'][$i];
1282 if (isset($child['children']) && count($child['children'])) {
1283 // This helps counting only the regular posts
1284 $count_post_closure = function($var) {
1285 return $var['verb'] === ACTIVITY_POST;
1288 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1290 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1292 // If there's only one child's children post and this is the last child post
1293 if ($child_post_count == 1 && $remaining_post_count == 1) {
1295 // Searches the post item in the children
1297 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1301 $moved_item = $child['children'][$j];
1302 unset($parent['children'][$i]['children'][$j]);
1303 $parent['children'][] = $moved_item;
1305 $parent['children'][$i] = smart_flatten_conversation($child);
1315 * Expands a flat list of items into corresponding tree-like conversation structures,
1316 * sort the top-level posts either on "created" or "commented", and finally
1317 * append all the items at the top level (???)
1319 * @brief Expands a flat item list into a conversation array for display
1321 * @param array $item_list A list of items belonging to one or more conversations
1322 * @param string $order Either on "created" or "commented"
1325 function conv_sort(array $item_list, $order)
1329 if (!(is_array($item_list) && count($item_list))) {
1335 // Dedupes the item list on the uri to prevent infinite loops
1336 foreach ($item_list as $item) {
1337 $item_array[$item['uri']] = $item;
1340 // Extract the top level items
1341 foreach ($item_array as $item) {
1342 if ($item['id'] == $item['parent']) {
1347 if (stristr($order, 'created')) {
1348 usort($parents, 'sort_thr_created');
1349 } elseif (stristr($order, 'commented')) {
1350 usort($parents, 'sort_thr_commented');
1354 * Plucks children from the item_array, second pass collects eventual orphan
1355 * items and add them as children of their top-level post.
1357 foreach ($parents as $i => $parent) {
1358 $parents[$i]['children'] =
1359 array_merge(get_item_children($item_array, $parent, true),
1360 get_item_children($item_array, $parent, false));
1363 foreach ($parents as $i => $parent) {
1364 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1367 if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1368 foreach ($parents as $i => $parent) {
1369 $parents[$i] = smart_flatten_conversation($parent);
1373 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1374 /// However, this apparently ensures responses (likes, attendance) display (?!)
1375 foreach ($parents as $parent) {
1376 if (count($parent['children'])) {
1377 add_children_to_list($parent['children'], $parents);
1385 * @brief usort() callback to sort item arrays by the created key
1391 function sort_thr_created(array $a, array $b)
1393 return strcmp($b['created'], $a['created']);
1397 * @brief usort() callback to reverse sort item arrays by the created key
1403 function sort_thr_created_rev(array $a, array $b)
1405 return strcmp($a['created'], $b['created']);
1409 * @brief usort() callback to sort item arrays by the commented key
1415 function sort_thr_commented(array $a, array $b)
1417 return strcmp($b['commented'], $a['commented']);
1420 function render_location_dummy(array $item) {
1421 if (x($item, 'location') && !empty($item['location'])) {
1422 return $item['location'];
1425 if (x($item, 'coord') && !empty($item['coord'])) {
1426 return $item['coord'];
1430 function get_responses(array $conv_responses, array $response_verbs, $ob, array $item) {
1432 foreach ($response_verbs as $v) {
1434 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
1435 $ret[$v]['list'] = defaults($conv_responses[$v], $item['uri'] . '-l', []);
1436 $ret[$v]['self'] = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1437 if (count($ret[$v]['list']) > MAX_LIKERS) {
1438 $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1439 array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1440 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . L10n::t('View all') . '</b></a>');
1442 $ret[$v]['list_part'] = '';
1444 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1445 $ret[$v]['title'] = $conv_responses[$v]['title'];
1449 foreach ($ret as $key) {
1450 if ($key['count'] == true) {
1454 $ret['count'] = $count;
1459 function get_response_button_text($v, $count)
1463 $return = L10n::tt('Like', 'Likes', $count);
1466 $return = L10n::tt('Dislike', 'Dislikes', $count);
1469 $return = L10n::tt('Attending', 'Attending', $count);
1472 $return = L10n::tt('Not Attending', 'Not Attending', $count);
1475 $return = L10n::tt('Undecided', 'Undecided', $count);