Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

1593 righe
49 KiB

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