Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1603 lines
49 KiB

2 years ago
2 years ago
9 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
10 years ago
10 years ago
3 years ago
  1. <?php
  2. /**
  3. * @file include/conversation.php
  4. */
  5. use Friendica\App;
  6. use Friendica\Content\ContactSelector;
  7. use Friendica\Content\Feature;
  8. use Friendica\Content\Pager;
  9. use Friendica\Content\Text\BBCode;
  10. use Friendica\Core\Config;
  11. use Friendica\Core\Hook;
  12. use Friendica\Core\L10n;
  13. use Friendica\Core\Logger;
  14. use Friendica\Core\Protocol;
  15. use Friendica\Core\Renderer;
  16. use Friendica\Core\Session;
  17. use Friendica\Database\DBA;
  18. use Friendica\DI;
  19. use Friendica\Model\Contact;
  20. use Friendica\Model\Item;
  21. use Friendica\Model\Profile;
  22. use Friendica\Model\Term;
  23. use Friendica\Object\Post;
  24. use Friendica\Object\Thread;
  25. use Friendica\Protocol\Activity;
  26. use Friendica\Util\Crypto;
  27. use Friendica\Util\DateTimeFormat;
  28. use Friendica\Util\Proxy as ProxyUtils;
  29. use Friendica\Util\Strings;
  30. use Friendica\Util\Temporal;
  31. use Friendica\Util\XML;
  32. function item_extract_images($body) {
  33. $saved_image = [];
  34. $orig_body = $body;
  35. $new_body = '';
  36. $cnt = 0;
  37. $img_start = strpos($orig_body, '[img');
  38. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  39. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  40. while (($img_st_close !== false) && ($img_end !== false)) {
  41. $img_st_close++; // make it point to AFTER the closing bracket
  42. $img_end += $img_start;
  43. if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
  44. // 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 . '#!]';
  47. $cnt++;
  48. } else {
  49. $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
  50. }
  51. $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
  52. if ($orig_body === false) {
  53. // in case the body ends on a closing image tag
  54. $orig_body = '';
  55. }
  56. $img_start = strpos($orig_body, '[img');
  57. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  58. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  59. }
  60. $new_body = $new_body . $orig_body;
  61. return ['body' => $new_body, 'images' => $saved_image];
  62. }
  63. function item_redir_and_replace_images($body, $images, $cid) {
  64. $origbody = $body;
  65. $newbody = '';
  66. $cnt = 1;
  67. $pos = BBCode::getTagPosition($origbody, 'url', 0);
  68. while ($pos !== false && $cnt < 1000) {
  69. $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
  70. $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
  71. . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
  72. $newbody .= substr($origbody, 0, $pos['start']['open']);
  73. $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
  74. $origbody = substr($origbody, $pos['end']['close']);
  75. if ($origbody === false) {
  76. $origbody = '';
  77. }
  78. $subject = preg_replace($search, $replace, $subject);
  79. $newbody .= $subject;
  80. $cnt++;
  81. // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
  82. $pos = BBCode::getTagPosition($origbody, 'url', 0);
  83. }
  84. $newbody .= $origbody;
  85. $cnt = 0;
  86. foreach ($images as $image) {
  87. /*
  88. * We're depending on the property of 'foreach' (specified on the PHP website) that
  89. * it loops over the array starting from the first element and going sequentially
  90. * to the last element.
  91. */
  92. $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
  93. $cnt++;
  94. }
  95. return $newbody;
  96. }
  97. /**
  98. * Render actions localized
  99. *
  100. * @param $item
  101. * @throws ImagickException
  102. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  103. */
  104. function localize_item(&$item)
  105. {
  106. $extracted = item_extract_images($item['body']);
  107. if ($extracted['images']) {
  108. $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
  109. }
  110. /*
  111. heluecht 2018-06-19: from my point of view this whole code part is useless.
  112. It just renders the body message of technical posts (Like, dislike, ...).
  113. But: The body isn't visible at all. So we do this stuff just because we can.
  114. Even if these messages were visible, this would only mean that something went wrong.
  115. During the further steps of the database restructuring I would like to address this issue.
  116. */
  117. $activity = DI::activity();
  118. $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
  119. if ($activity->match($item['verb'], Activity::LIKE)
  120. || $activity->match($item['verb'], Activity::DISLIKE)
  121. || $activity->match($item['verb'], Activity::ATTEND)
  122. || $activity->match($item['verb'], Activity::ATTENDNO)
  123. || $activity->match($item['verb'], Activity::ATTENDMAYBE)) {
  124. $fields = ['author-link', 'author-name', 'verb', 'object-type', 'resource-id', 'body', 'plink'];
  125. $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
  126. if (!DBA::isResult($obj)) {
  127. return;
  128. }
  129. $author = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
  130. $objauthor = '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
  131. switch ($obj['verb']) {
  132. case Activity::POST:
  133. switch ($obj['object-type']) {
  134. case Activity\ObjectType::EVENT:
  135. $post_type = L10n::t('event');
  136. break;
  137. default:
  138. $post_type = L10n::t('status');
  139. }
  140. break;
  141. default:
  142. if ($obj['resource-id']) {
  143. $post_type = L10n::t('photo');
  144. $m = [];
  145. preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
  146. $rr['plink'] = $m[1];
  147. } else {
  148. $post_type = L10n::t('status');
  149. }
  150. }
  151. $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
  152. $bodyverb = '';
  153. if ($activity->match($item['verb'], Activity::LIKE)) {
  154. $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
  155. } elseif ($activity->match($item['verb'], Activity::DISLIKE)) {
  156. $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
  157. } elseif ($activity->match($item['verb'], Activity::ATTEND)) {
  158. $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s');
  159. } elseif ($activity->match($item['verb'], Activity::ATTENDNO)) {
  160. $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s');
  161. } elseif ($activity->match($item['verb'], Activity::ATTENDMAYBE)) {
  162. $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s');
  163. }
  164. $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
  165. }
  166. if ($activity->match($item['verb'], Activity::FRIEND)) {
  167. if ($item['object-type']=="" || $item['object-type']!== Activity\ObjectType::PERSON) return;
  168. $Aname = $item['author-name'];
  169. $Alink = $item['author-link'];
  170. $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
  171. $obj = XML::parseString($xmlhead.$item['object']);
  172. $links = XML::parseString($xmlhead."<links>".XML::unescape($obj->link)."</links>");
  173. $Bname = $obj->title;
  174. $Blink = "";
  175. $Bphoto = "";
  176. foreach ($links->link as $l) {
  177. $atts = $l->attributes();
  178. switch ($atts['rel']) {
  179. case "alternate": $Blink = $atts['href']; break;
  180. case "photo": $Bphoto = $atts['href']; break;
  181. }
  182. }
  183. $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
  184. $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
  185. if ($Bphoto != "") {
  186. $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img]' . $Bphoto . '[/img][/url]';
  187. }
  188. $item['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$Bphoto;
  189. }
  190. if (stristr($item['verb'], Activity::POKE)) {
  191. $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
  192. if (!$verb) {
  193. return;
  194. }
  195. if ($item['object-type']=="" || $item['object-type']!== Activity\ObjectType::PERSON) {
  196. return;
  197. }
  198. $Aname = $item['author-name'];
  199. $Alink = $item['author-link'];
  200. $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
  201. $obj = XML::parseString($xmlhead.$item['object']);
  202. $Bname = $obj->title;
  203. $Blink = $obj->id;
  204. $Bphoto = "";
  205. foreach ($obj->link as $l) {
  206. $atts = $l->attributes();
  207. switch ($atts['rel']) {
  208. case "alternate": $Blink = $atts['href'];
  209. case "photo": $Bphoto = $atts['href'];
  210. }
  211. }
  212. $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
  213. $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
  214. if ($Bphoto != "") {
  215. $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
  216. }
  217. /*
  218. * we can't have a translation string with three positions but no distinguishable text
  219. * So here is the translate string.
  220. */
  221. $txt = L10n::t('%1$s poked %2$s');
  222. // now translate the verb
  223. $poked_t = trim(sprintf($txt, "", ""));
  224. $txt = str_replace($poked_t, L10n::t($verb), $txt);
  225. // then do the sprintf on the translation string
  226. $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
  227. }
  228. if ($activity->match($item['verb'], Activity::TAG)) {
  229. $fields = ['author-id', 'author-link', 'author-name', 'author-network',
  230. 'verb', 'object-type', 'resource-id', 'body', 'plink'];
  231. $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
  232. if (!DBA::isResult($obj)) {
  233. return;
  234. }
  235. $author_arr = ['uid' => 0, 'id' => $item['author-id'],
  236. 'network' => $item['author-network'], 'url' => $item['author-link']];
  237. $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
  238. $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
  239. 'network' => $obj['author-network'], 'url' => $obj['author-link']];
  240. $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
  241. switch ($obj['verb']) {
  242. case Activity::POST:
  243. switch ($obj['object-type']) {
  244. case Activity\ObjectType::EVENT:
  245. $post_type = L10n::t('event');
  246. break;
  247. default:
  248. $post_type = L10n::t('status');
  249. }
  250. break;
  251. default:
  252. if ($obj['resource-id']) {
  253. $post_type = L10n::t('photo');
  254. $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
  255. $rr['plink'] = $m[1];
  256. } else {
  257. $post_type = L10n::t('status');
  258. }
  259. // Let's break everthing ... ;-)
  260. break;
  261. }
  262. $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
  263. $parsedobj = XML::parseString($xmlhead.$item['object']);
  264. $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
  265. $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
  266. }
  267. if ($activity->match($item['verb'], Activity::FAVORITE)) {
  268. if ($item['object-type'] == "") {
  269. return;
  270. }
  271. $Aname = $item['author-name'];
  272. $Alink = $item['author-link'];
  273. $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
  274. $obj = XML::parseString($xmlhead.$item['object']);
  275. if (strlen($obj->id)) {
  276. $fields = ['author-link', 'author-name', 'plink'];
  277. $target = Item::selectFirst($fields, ['uri' => $obj->id, 'uid' => $item['uid']]);
  278. if (DBA::isResult($target) && $target['plink']) {
  279. $Bname = $target['author-name'];
  280. $Blink = $target['author-link'];
  281. $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
  282. $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
  283. $P = '[url=' . $target['plink'] . ']' . L10n::t('post/item') . '[/url]';
  284. $item['body'] = L10n::t('%1$s marked %2$s\'s %3$s as favorite', $A, $B, $P)."\n";
  285. }
  286. }
  287. }
  288. $matches = null;
  289. if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
  290. foreach ($matches as $mtch) {
  291. if (!strpos($mtch[1], 'zrl=')) {
  292. $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
  293. }
  294. }
  295. }
  296. // add zrl's to public images
  297. $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
  298. if (preg_match($photo_pattern, $item['body'])) {
  299. $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
  300. $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
  301. }
  302. // add sparkle links to appropriate permalinks
  303. $author = ['uid' => 0, 'id' => $item['author-id'],
  304. 'network' => $item['author-network'], 'url' => $item['author-link']];
  305. // Only create a redirection to a magic link when logged in
  306. if (!empty($item['plink']) && Session::isAuthenticated()) {
  307. $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
  308. }
  309. }
  310. /**
  311. * Count the total of comments on this item and its desendants
  312. * @TODO proper type-hint + doc-tag
  313. * @param $item
  314. * @return int
  315. */
  316. function count_descendants($item) {
  317. $total = count($item['children']);
  318. if ($total > 0) {
  319. foreach ($item['children'] as $child) {
  320. if (!visible_activity($child)) {
  321. $total --;
  322. }
  323. $total += count_descendants($child);
  324. }
  325. }
  326. return $total;
  327. }
  328. function visible_activity($item) {
  329. $activity = DI::activity();
  330. if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
  331. return false;
  332. }
  333. // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
  334. if ($activity->match($item['verb'], Activity::FOLLOW) &&
  335. $item['object-type'] === Activity\ObjectType::NOTE &&
  336. empty($item['self']) &&
  337. $item['uid'] == local_user()) {
  338. return false;
  339. }
  340. return true;
  341. }
  342. function conv_get_blocklist()
  343. {
  344. if (!local_user()) {
  345. return [];
  346. }
  347. $str_blocked = DI::pConfig()->get(local_user(), 'system', 'blocked');
  348. if (empty($str_blocked)) {
  349. return [];
  350. }
  351. $blocklist = [];
  352. foreach (explode(',', $str_blocked) as $entry) {
  353. // The 4th parameter guarantees that there always will be a public contact entry
  354. $cid = Contact::getIdForURL(trim($entry), 0, true, ['url' => trim($entry)]);
  355. if (!empty($cid)) {
  356. $blocklist[] = $cid;
  357. }
  358. }
  359. return $blocklist;
  360. }
  361. /**
  362. * "Render" a conversation or list of items for HTML display.
  363. * There are two major forms of display:
  364. * - Sequential or unthreaded ("New Item View" or search results)
  365. * - conversation view
  366. * The $mode parameter decides between the various renderings and also
  367. * figures out how to determine page owner and other contextual items
  368. * that are based on unique features of the calling module.
  369. * @param App $a
  370. * @param array $items
  371. * @param Pager $pager
  372. * @param $mode
  373. * @param $update
  374. * @param bool $preview
  375. * @param string $order
  376. * @param int $uid
  377. * @return string
  378. * @throws ImagickException
  379. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  380. */
  381. function conversation(App $a, array $items, Pager $pager, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
  382. {
  383. $ssl_state = (local_user() ? true : false);
  384. $profile_owner = 0;
  385. $live_update_div = '';
  386. $blocklist = conv_get_blocklist();
  387. $previewing = (($preview) ? ' preview ' : '');
  388. if ($mode === 'network') {
  389. $items = conversation_add_children($items, false, $order, $uid);
  390. $profile_owner = local_user();
  391. if (!$update) {
  392. /*
  393. * The special div is needed for liveUpdate to kick in for this page.
  394. * We only launch liveUpdate if you aren't filtering in some incompatible
  395. * way and also you aren't writing a comment (discovered in javascript).
  396. */
  397. $live_update_div = '<div id="live-network"></div>' . "\r\n"
  398. . "<script> var profile_uid = " . $_SESSION['uid']
  399. . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
  400. . '?f='
  401. . (!empty($_GET['cid']) ? '&cid=' . rawurlencode($_GET['cid']) : '')
  402. . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
  403. . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
  404. . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
  405. . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
  406. . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
  407. . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
  408. . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
  409. . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
  410. . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
  411. . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
  412. . "'; var profile_page = " . $pager->getPage() . "; </script>\r\n";
  413. }
  414. } elseif ($mode === 'profile') {
  415. $items = conversation_add_children($items, false, $order, $uid);
  416. $profile_owner = $a->profile['profile_uid'];
  417. if (!$update) {
  418. $tab = 'posts';
  419. if (!empty($_GET['tab'])) {
  420. $tab = Strings::escapeTags(trim($_GET['tab']));
  421. }
  422. if ($tab === 'posts') {
  423. /*
  424. * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
  425. * because browser prefetching might change it on us. We have to deliver it with the page.
  426. */
  427. $live_update_div = '<div id="live-profile"></div>' . "\r\n"
  428. . "<script> var profile_uid = " . $a->profile['profile_uid']
  429. . "; var netargs = '?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
  430. }
  431. }
  432. } elseif ($mode === 'notes') {
  433. $items = conversation_add_children($items, false, $order, local_user());
  434. $profile_owner = local_user();
  435. if (!$update) {
  436. $live_update_div = '<div id="live-notes"></div>' . "\r\n"
  437. . "<script> var profile_uid = " . local_user()
  438. . "; var netargs = '/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
  439. }
  440. } elseif ($mode === 'display') {
  441. $items = conversation_add_children($items, false, $order, $uid);
  442. $profile_owner = $a->profile['uid'];
  443. if (!$update) {
  444. $live_update_div = '<div id="live-display"></div>' . "\r\n"
  445. . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
  446. . " var profile_page = 1; </script>";
  447. }
  448. } elseif ($mode === 'community') {
  449. $items = conversation_add_children($items, true, $order, $uid);
  450. $profile_owner = 0;
  451. if (!$update) {
  452. $live_update_div = '<div id="live-community"></div>' . "\r\n"
  453. . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
  454. ."/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
  455. }
  456. } elseif ($mode === 'contacts') {
  457. $items = conversation_add_children($items, false, $order, $uid);
  458. $profile_owner = 0;
  459. if (!$update) {
  460. $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
  461. . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 9)
  462. ."/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
  463. }
  464. } elseif ($mode === 'search') {
  465. $live_update_div = '<div id="live-search"></div>' . "\r\n";
  466. }
  467. $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
  468. if (!$update) {
  469. $_SESSION['return_path'] = DI::args()->getQueryString();
  470. }
  471. $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
  472. Hook::callAll('conversation_start',$cb);
  473. $items = $cb['items'];
  474. $conv_responses = [
  475. 'like' => ['title' => L10n::t('Likes','title')],
  476. 'dislike' => ['title' => L10n::t('Dislikes','title')],
  477. 'attendyes' => ['title' => L10n::t('Attending','title')],
  478. 'attendno' => ['title' => L10n::t('Not attending','title')],
  479. 'attendmaybe' => ['title' => L10n::t('Might attend','title')],
  480. 'announce' => ['title' => L10n::t('Reshares','title')]
  481. ];
  482. // array with html for each thread (parent+comments)
  483. $threads = [];
  484. $threadsid = -1;
  485. $page_template = Renderer::getMarkupTemplate("conversation.tpl");
  486. if (!empty($items)) {
  487. if (in_array($mode, ['community', 'contacts'])) {
  488. $writable = true;
  489. } else {
  490. $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
  491. }
  492. if (!local_user()) {
  493. $writable = false;
  494. }
  495. if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
  496. /*
  497. * "New Item View" on network page or search page results
  498. * - just loop through the items and format them minimally for display
  499. */
  500. $tpl = 'search_item.tpl';
  501. foreach ($items as $item) {
  502. if (!visible_activity($item)) {
  503. continue;
  504. }
  505. if (in_array($item['author-id'], $blocklist)) {
  506. continue;
  507. }
  508. $threadsid++;
  509. $owner_url = '';
  510. $owner_name = '';
  511. $sparkle = '';
  512. // prevent private email from leaking.
  513. if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
  514. continue;
  515. }
  516. $profile_name = $item['author-name'];
  517. if (!empty($item['author-link']) && empty($item['author-name'])) {
  518. $profile_name = $item['author-link'];
  519. }
  520. $tags = Term::populateTagsFromItem($item);
  521. $author = ['uid' => 0, 'id' => $item['author-id'],
  522. 'network' => $item['author-network'], 'url' => $item['author-link']];
  523. $profile_link = Contact::magicLinkByContact($author);
  524. if (strpos($profile_link, 'redir/') === 0) {
  525. $sparkle = ' sparkle';
  526. }
  527. $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
  528. Hook::callAll('render_location',$locate);
  529. $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
  530. localize_item($item);
  531. if ($mode === 'network-new') {
  532. $dropping = true;
  533. } else {
  534. $dropping = false;
  535. }
  536. $drop = [
  537. 'dropping' => $dropping,
  538. 'pagedrop' => $page_dropping,
  539. 'select' => L10n::t('Select'),
  540. 'delete' => L10n::t('Delete'),
  541. ];
  542. $star = false;
  543. $isstarred = "unstarred";
  544. $lock = false;
  545. $likebuttons = false;
  546. $body = Item::prepareBody($item, true, $preview);
  547. list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
  548. if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
  549. $title = ucfirst($item['content-warning']);
  550. } else {
  551. $title = $item['title'];
  552. }
  553. $tmp_item = [
  554. 'template' => $tpl,
  555. 'id' => ($preview ? 'P0' : $item['id']),
  556. 'guid' => ($preview ? 'Q0' : $item['guid']),
  557. 'network' => $item['network'],
  558. 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
  559. 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
  560. 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
  561. 'profile_url' => $profile_link,
  562. 'item_photo_menu' => item_photo_menu($item),
  563. 'name' => $profile_name,
  564. 'sparkle' => $sparkle,
  565. 'lock' => $lock,
  566. 'thumb' => DI::baseUrl()->remove(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
  567. 'title' => $title,
  568. 'body' => $body,
  569. 'tags' => $tags['tags'],
  570. 'hashtags' => $tags['hashtags'],
  571. 'mentions' => $tags['mentions'],
  572. 'implicit_mentions' => $tags['implicit_mentions'],
  573. 'txt_cats' => L10n::t('Categories:'),
  574. 'txt_folders' => L10n::t('Filed under:'),
  575. 'has_cats' => ((count($categories)) ? 'true' : ''),
  576. 'has_folders' => ((count($folders)) ? 'true' : ''),
  577. 'categories' => $categories,
  578. 'folders' => $folders,
  579. 'text' => strip_tags($body),
  580. 'localtime' => DateTimeFormat::local($item['created'], 'r'),
  581. 'ago' => (($item['app']) ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
  582. 'location' => $location,
  583. 'indent' => '',
  584. 'owner_name' => $owner_name,
  585. 'owner_url' => $owner_url,
  586. 'owner_photo' => DI::baseUrl()->remove(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
  587. 'plink' => Item::getPlink($item),
  588. 'edpost' => false,
  589. 'isstarred' => $isstarred,
  590. 'star' => $star,
  591. 'drop' => $drop,
  592. 'vote' => $likebuttons,
  593. 'like' => '',
  594. 'dislike' => '',
  595. 'comment' => '',
  596. 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> L10n::t('View in context')]),
  597. 'previewing' => $previewing,
  598. 'wait' => L10n::t('Please wait'),
  599. 'thread_level' => 1,
  600. ];
  601. $arr = ['item' => $item, 'output' => $tmp_item];
  602. Hook::callAll('display_item', $arr);
  603. $threads[$threadsid]['id'] = $item['id'];
  604. $threads[$threadsid]['network'] = $item['network'];
  605. $threads[$threadsid]['items'] = [$arr['output']];
  606. }
  607. } else {
  608. // Normal View
  609. $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
  610. $conv = new Thread($mode, $preview, $writable);
  611. /*
  612. * get all the topmost parents
  613. * this shouldn't be needed, as we should have only them in our array
  614. * But for now, this array respects the old style, just in case
  615. */
  616. foreach ($items as $item) {
  617. if (in_array($item['author-id'], $blocklist)) {
  618. continue;
  619. }
  620. // Can we put this after the visibility check?
  621. builtin_activity_puller($item, $conv_responses);
  622. // Only add what is visible
  623. if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
  624. continue;
  625. }
  626. if (!visible_activity($item)) {
  627. continue;
  628. }
  629. /// @todo Check if this call is needed or not
  630. $arr = ['item' => $item];
  631. Hook::callAll('display_item', $arr);
  632. $item['pagedrop'] = $page_dropping;
  633. if ($item['id'] == $item['parent']) {
  634. $item_object = new Post($item);
  635. $conv->addParent($item_object);
  636. }
  637. }
  638. $threads = $conv->getTemplateData($conv_responses);
  639. if (!$threads) {
  640. Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
  641. $threads = [];
  642. }
  643. }
  644. }
  645. $o = Renderer::replaceMacros($page_template, [
  646. '$baseurl' => DI::baseUrl()->get($ssl_state),
  647. '$return_path' => DI::args()->getQueryString(),
  648. '$live_update' => $live_update_div,
  649. '$remove' => L10n::t('remove'),
  650. '$mode' => $mode,
  651. '$user' => $a->user,
  652. '$threads' => $threads,
  653. '$dropping' => ($page_dropping ? L10n::t('Delete Selected Items') : False),
  654. ]);
  655. return $o;
  656. }
  657. /**
  658. * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
  659. *
  660. * @param array $thread_items Database statement with thread posts
  661. * @param boolean $pinned Is the item pinned?
  662. *
  663. * @return array items with parents and comments
  664. */
  665. function conversation_fetch_comments($thread_items, $pinned) {
  666. $comments = [];
  667. $parentlines = [];
  668. $lineno = 0;
  669. $actor = [];
  670. $received = '';
  671. while ($row = Item::fetch($thread_items)) {
  672. if (($row['verb'] == Activity::ANNOUNCE) && !empty($row['contact-uid']) && ($row['received'] > $received) && ($row['thr-parent'] == $row['parent-uri'])) {
  673. $actor = ['link' => $row['author-link'], 'avatar' => $row['author-avatar'], 'name' => $row['author-name']];
  674. $received = $row['received'];
  675. }
  676. if ((($row['gravity'] == GRAVITY_PARENT) && !$row['origin'] && !in_array($row['network'], [Protocol::DIASPORA])) &&
  677. (empty($row['contact-uid']) || !in_array($row['network'], Protocol::NATIVE_SUPPORT))) {
  678. $parentlines[] = $lineno;
  679. }
  680. if ($row['gravity'] == GRAVITY_PARENT) {
  681. $row['pinned'] = $pinned;
  682. }
  683. $comments[] = $row;
  684. $lineno++;
  685. }
  686. DBA::close($thread_items);
  687. if (!empty($actor)) {
  688. foreach ($parentlines as $line) {
  689. $comments[$line]['owner-link'] = $actor['link'];
  690. $comments[$line]['owner-avatar'] = $actor['avatar'];
  691. $comments[$line]['owner-name'] = $actor['name'];
  692. }
  693. }
  694. return $comments;
  695. }
  696. /**
  697. * @brief Add comments to top level entries that had been fetched before
  698. *
  699. * The system will fetch the comments for the local user whenever possible.
  700. * This behaviour is currently needed to allow commenting on Friendica posts.
  701. *
  702. * @param array $parents Parent items
  703. *
  704. * @param $block_authors
  705. * @param $order
  706. * @param $uid
  707. * @return array items with parents and comments
  708. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  709. */
  710. function conversation_add_children(array $parents, $block_authors, $order, $uid) {
  711. $max_comments = Config::get('system', 'max_comments', 100);
  712. $params = ['order' => ['uid', 'commented' => true]];
  713. if ($max_comments > 0) {
  714. $params['limit'] = $max_comments;
  715. }
  716. $items = [];
  717. foreach ($parents AS $parent) {
  718. $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) ",
  719. $parent['uri'], $uid];
  720. if ($block_authors) {
  721. $condition[0] .= "AND NOT `author`.`hidden`";
  722. }
  723. $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['contact-uid', 'gravity']), $condition, $params);
  724. $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false);
  725. if (count($comments) != 0) {
  726. $items = array_merge($items, $comments);
  727. }
  728. }
  729. foreach ($items as $index => $item) {
  730. if ($item['uid'] == 0) {
  731. $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
  732. }
  733. }
  734. $items = conv_sort($items, $order);
  735. return $items;
  736. }
  737. function item_photo_menu($item) {
  738. $sub_link = '';
  739. $poke_link = '';
  740. $contact_url = '';
  741. $pm_url = '';
  742. $status_link = '';
  743. $photos_link = '';
  744. $posts_link = '';
  745. $block_link = '';
  746. $ignore_link = '';
  747. if (local_user() && local_user() == $item['uid'] && $item['parent'] == $item['id'] && !$item['self']) {
  748. $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
  749. }
  750. $author = ['uid' => 0, 'id' => $item['author-id'],
  751. 'network' => $item['author-network'], 'url' => $item['author-link']];
  752. $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
  753. $sparkle = (strpos($profile_link, 'redir/') === 0);
  754. $cid = 0;
  755. $pcid = Contact::getIdForURL($item['author-link'], 0, true);
  756. $network = '';
  757. $rel = 0;
  758. $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
  759. $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
  760. if (DBA::isResult($contact)) {
  761. $cid = $contact['id'];
  762. $network = $contact['network'];
  763. $rel = $contact['rel'];
  764. }
  765. if ($sparkle) {
  766. $status_link = $profile_link . '?tab=status';
  767. $photos_link = str_replace('/profile/', '/photos/', $profile_link);
  768. $profile_link = $profile_link . '?=profile';
  769. }
  770. if (!empty($pcid)) {
  771. $contact_url = 'contact/' . $pcid;
  772. $posts_link = 'contact/' . $pcid . '/posts';
  773. $block_link = 'contact/' . $pcid . '/block';
  774. $ignore_link = 'contact/' . $pcid . '/ignore';
  775. }
  776. if ($cid && !$item['self']) {
  777. $poke_link = 'poke?c=' . $cid;
  778. $contact_url = 'contact/' . $cid;
  779. $posts_link = 'contact/' . $cid . '/posts';
  780. if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
  781. $pm_url = 'message/new/' . $cid;
  782. }
  783. }
  784. if (local_user()) {
  785. $menu = [
  786. L10n::t('Follow Thread') => $sub_link,
  787. L10n::t('View Status') => $status_link,
  788. L10n::t('View Profile') => $profile_link,
  789. L10n::t('View Photos') => $photos_link,
  790. L10n::t('Network Posts') => $posts_link,
  791. L10n::t('View Contact') => $contact_url,
  792. L10n::t('Send PM') => $pm_url,
  793. L10n::t('Block') => $block_link,
  794. L10n::t('Ignore') => $ignore_link
  795. ];
  796. if ($network == Protocol::DFRN) {
  797. $menu[L10n::t("Poke")] = $poke_link;
  798. }
  799. if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
  800. in_array($item['network'], Protocol::FEDERATED)) {
  801. $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
  802. }
  803. } else {
  804. $menu = [L10n::t('View Profile') => $item['author-link']];
  805. }
  806. $args = ['item' => $item, 'menu' => $menu];
  807. Hook::callAll('item_photo_menu', $args);
  808. $menu = $args['menu'];
  809. $o = '';
  810. foreach ($menu as $k => $v) {
  811. if (strpos($v, 'javascript:') === 0) {
  812. $v = substr($v, 11);
  813. $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
  814. } elseif ($v!='') {
  815. $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
  816. }
  817. }
  818. return $o;
  819. }
  820. /**
  821. * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
  822. * Increments the count of each matching activity and adds a link to the author as needed.
  823. *
  824. * @param array $item
  825. * @param array &$conv_responses (already created with builtin activity structure)
  826. * @return void
  827. * @throws ImagickException
  828. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  829. */
  830. function builtin_activity_puller($item, &$conv_responses) {
  831. foreach ($conv_responses as $mode => $v) {
  832. $sparkle = '';
  833. switch ($mode) {
  834. case 'like':
  835. $verb = Activity::LIKE;
  836. break;
  837. case 'dislike':
  838. $verb = Activity::DISLIKE;
  839. break;
  840. case 'attendyes':
  841. $verb = Activity::ATTEND;
  842. break;
  843. case 'attendno':
  844. $verb = Activity::ATTENDNO;
  845. break;
  846. case 'attendmaybe':
  847. $verb = Activity::ATTENDMAYBE;
  848. break;
  849. case 'announce':
  850. $verb = Activity::ANNOUNCE;
  851. break;
  852. default:
  853. return;
  854. }
  855. if (!empty($item['verb']) && DI::activity()->match($item['verb'], $verb) && ($item['id'] != $item['parent'])) {
  856. $author = ['uid' => 0, 'id' => $item['author-id'],
  857. 'network' => $item['author-network'], 'url' => $item['author-link']];
  858. $url = Contact::magicLinkByContact($author);
  859. if (strpos($url, 'redir/') === 0) {
  860. $sparkle = ' class="sparkle" ';
  861. }
  862. $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
  863. if (empty($item['thr-parent'])) {
  864. $item['thr-parent'] = $item['parent-uri'];
  865. }
  866. if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
  867. && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
  868. $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
  869. }
  870. // only list each unique author once
  871. if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
  872. continue;
  873. }
  874. if (!isset($conv_responses[$mode][$item['thr-parent']])) {
  875. $conv_responses[$mode][$item['thr-parent']] = 1;
  876. } else {
  877. $conv_responses[$mode][$item['thr-parent']] ++;
  878. }
  879. if (public_contact() == $item['author-id']) {
  880. $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
  881. }
  882. $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
  883. // there can only be one activity verb per item so if we found anything, we can stop looking
  884. return;
  885. }
  886. }
  887. }
  888. /**
  889. * Format the vote text for a profile item
  890. *
  891. * @param int $cnt = number of people who vote the item
  892. * @param array $arr = array of pre-linked names of likers/dislikers
  893. * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
  894. * @param int $id = item id
  895. * @return string formatted text
  896. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  897. */
  898. function format_like($cnt, array $arr, $type, $id) {
  899. $o = '';
  900. $expanded = '';
  901. $phrase = '';
  902. if ($cnt == 1) {
  903. $likers = $arr[0];
  904. // Phrase if there is only one liker. In other cases it will be uses for the expanded
  905. // list which show all likers
  906. switch ($type) {
  907. case 'like' :
  908. $phrase = L10n::t('%s likes this.', $likers);
  909. break;
  910. case 'dislike' :
  911. $phrase = L10n::t('%s doesn\'t like this.', $likers);
  912. break;
  913. case 'attendyes' :
  914. $phrase = L10n::t('%s attends.', $likers);
  915. break;
  916. case 'attendno' :
  917. $phrase = L10n::t('%s doesn\'t attend.', $likers);
  918. break;
  919. case 'attendmaybe' :
  920. $phrase = L10n::t('%s attends maybe.', $likers);
  921. break;
  922. case 'announce' :
  923. $phrase = L10n::t('%s reshared this.', $likers);
  924. break;
  925. }
  926. }
  927. if ($cnt > 1) {
  928. $total = count($arr);
  929. if ($total < MAX_LIKERS) {
  930. $last = L10n::t('and') . ' ' . $arr[count($arr)-1];
  931. $arr2 = array_slice($arr, 0, -1);
  932. $likers = implode(', ', $arr2) . ' ' . $last;
  933. } else {
  934. $arr = array_slice($arr, 0, MAX_LIKERS - 1);
  935. $likers = implode(', ', $arr);
  936. $likers .= L10n::t('and %d other people', $total - MAX_LIKERS);
  937. }
  938. $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
  939. $explikers = '';
  940. switch ($type) {
  941. case 'like':
  942. $phrase = L10n::t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
  943. $explikers = L10n::t('%s like this.', $likers);
  944. break;
  945. case 'dislike':
  946. $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
  947. $explikers = L10n::t('%s don\'t like this.', $likers);
  948. break;
  949. case 'attendyes':
  950. $phrase = L10n::t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
  951. $explikers = L10n::t('%s attend.', $likers);
  952. break;
  953. case 'attendno':
  954. $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
  955. $explikers = L10n::t('%s don\'t attend.', $likers);
  956. break;
  957. case 'attendmaybe':
  958. $phrase = L10n::t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
  959. $explikers = L10n::t('%s attend maybe.', $likers);
  960. break;
  961. case 'announce':
  962. $phrase = L10n::t('<span %1$s>%2$d people</span> reshared this', $spanatts, $cnt);
  963. $explikers = L10n::t('%s reshared this.', $likers);
  964. break;
  965. }
  966. $expanded .= "\t" . '<p class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
  967. }
  968. $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
  969. '$phrase' => $phrase,
  970. '$type' => $type,
  971. '$id' => $id
  972. ]);
  973. $o .= $expanded;
  974. return $o;
  975. }
  976. function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
  977. {
  978. $o = '';
  979. $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
  980. $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
  981. DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
  982. '$newpost' => 'true',
  983. '$baseurl' => DI::baseUrl()->get(true),
  984. '$geotag' => $geotag</