Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

1604 строки
49 KiB

  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,
  985. '$nickname' => $x['nickname'],
  986. '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
  987. '$linkurl' => L10n::t('Please enter a image/video/audio/webpage URL:'),
  988. '$term' => L10n::t('Tag term:'),
  989. '$fileas' => L10n::t('Save to Folder:'),
  990. '$whereareu' => L10n::t('Where are you right now?'),
  991. '$delitems' => L10n::t("Delete item\x28s\x29?")
  992. ]);
  993. $jotplugins = '';
  994. Hook::callAll('jot_tool', $jotplugins);
  995. // Private/public post links for the non-JS ACL form
  996. $private_post = 1;
  997. if (!empty($_REQUEST['public'])) {
  998. $private_post = 0;
  999. }
  1000. $query_str = DI::args()->getQueryString();
  1001. if (strpos($query_str, 'public=1') !== false) {
  1002. $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
  1003. }
  1004. /*
  1005. * I think $a->query_string may never have ? in it, but I could be wrong
  1006. * It looks like it's from the index.php?q=[etc] rewrite that the web
  1007. * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
  1008. */
  1009. if (strpos($query_str, '?') === false) {
  1010. $public_post_link = '?public=1';
  1011. } else {
  1012. $public_post_link = '&public=1';
  1013. }
  1014. // $tpl = Renderer::replaceMacros($tpl,array('$jotplugins' => $jotplugins));
  1015. $tpl = Renderer::getMarkupTemplate("jot.tpl");
  1016. $o .= Renderer::replaceMacros($tpl,[
  1017. '$new_post' => L10n::t('New Post'),
  1018. '$return_path' => $query_str,
  1019. '$action' => 'item',
  1020. '$share' => ($x['button'] ?? '') ?: L10n::t('Share'),
  1021. '$upload' => L10n::t('Upload photo'),
  1022. '$shortupload' => L10n::t('upload photo'),
  1023. '$attach' => L10n::t('Attach file'),
  1024. '$shortattach' => L10n::t('attach file'),
  1025. '$edbold' => L10n::t('Bold'),
  1026. '$editalic' => L10n::t('Italic'),
  1027. '$eduline' => L10n::t('Underline'),
  1028. '$edquote' => L10n::t('Quote'),
  1029. '$edcode' => L10n::t('Code'),
  1030. '$edimg' => L10n::t('Image'),
  1031. '$edurl' => L10n::t('Link'),
  1032. '$edattach' => L10n::t('Link or Media'),
  1033. '$setloc' => L10n::t('Set your location'),
  1034. '$shortsetloc' => L10n::t('set location'),
  1035. '$noloc' => L10n::t('Clear browser location'),
  1036. '$shortnoloc' => L10n::t('clear location'),
  1037. '$title' => $x['title'] ?? '',
  1038. '$placeholdertitle' => L10n::t('Set title'),
  1039. '$category' => $x['category'] ?? '',
  1040. '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? L10n::t("Categories \x28comma-separated list\x29") : '',
  1041. '$wait' => L10n::t('Please wait'),
  1042. '$permset' => L10n::t('Permission settings'),
  1043. '$shortpermset' => L10n::t('permissions'),
  1044. '$wall' => $notes_cid ? 0 : 1,
  1045. '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
  1046. '$content' => $x['content'] ?? '',
  1047. '$post_id' => $x['post_id'] ?? '',
  1048. '$baseurl' => DI::baseUrl()->get(true),
  1049. '$defloc' => $x['default_location'],
  1050. '$visitor' => $x['visitor'],
  1051. '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
  1052. '$public' => L10n::t('Public post'),
  1053. '$lockstate' => $x['lockstate'],
  1054. '$bang' => $x['bang'],
  1055. '$profile_uid' => $x['profile_uid'],
  1056. '$preview' => L10n::t('Preview'),
  1057. '$jotplugins' => $jotplugins,
  1058. '$notes_cid' => $notes_cid,
  1059. '$sourceapp' => L10n::t($a->sourcename),
  1060. '$cancel' => L10n::t('Cancel'),
  1061. '$rand_num' => Crypto::randomDigits(12),
  1062. // ACL permissions box
  1063. '$acl' => $x['acl'],
  1064. '$group_perms' => L10n::t('Post to Groups'),
  1065. '$contact_perms' => L10n::t('Post to Contacts'),
  1066. '$private' => L10n::t('Private post'),
  1067. '$is_private' => $private_post,
  1068. '$public_link' => $public_post_link,
  1069. //jot nav tab (used in some themes)
  1070. '$message' => L10n::t('Message'),
  1071. '$browser' => L10n::t('Browser'),
  1072. ]);
  1073. if ($popup == true) {
  1074. $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
  1075. }
  1076. return $o;
  1077. }
  1078. /**
  1079. * Plucks the children of the given parent from a given item list.
  1080. *
  1081. * @brief Plucks all the children in the given item list of the given parent
  1082. *
  1083. * @param array $item_list
  1084. * @param array $parent
  1085. * @param bool $recursive
  1086. * @return array
  1087. */
  1088. function get_item_children(array &$item_list, array $parent, $recursive = true)
  1089. {
  1090. $children = [];
  1091. foreach ($item_list as $i => $item) {
  1092. if ($item['id'] != $item['parent']) {
  1093. if ($recursive) {
  1094. // Fallback to parent-uri if thr-parent is not set
  1095. $thr_parent = $item['thr-parent'];
  1096. if ($thr_parent == '') {
  1097. $thr_parent = $item['parent-uri'];
  1098. }
  1099. if ($thr_parent == $parent['uri']) {
  1100. $item['children'] = get_item_children($item_list, $item);
  1101. $children[] = $item;
  1102. unset($item_list[$i]);
  1103. }
  1104. } elseif ($item['parent'] == $parent['id']) {
  1105. $children[] = $item;
  1106. unset($item_list[$i]);
  1107. }
  1108. }
  1109. }
  1110. return $children;
  1111. }
  1112. /**
  1113. * @brief Recursively sorts a tree-like item array
  1114. *
  1115. * @param array $items
  1116. * @return array
  1117. */
  1118. function sort_item_children(array $items)
  1119. {
  1120. $result = $items;
  1121. usort($result, 'sort_thr_received_rev');
  1122. foreach ($result as $k => $i) {
  1123. if (isset($result[$k]['children'])) {
  1124. $result[$k]['children'] = sort_item_children($result[$k]['children']);
  1125. }
  1126. }
  1127. return $result;
  1128. }
  1129. /**
  1130. * @brief Recursively add all children items at the top level of a list
  1131. *
  1132. * @param array $children List of items to append
  1133. * @param array $item_list
  1134. */
  1135. function add_children_to_list(array $children, array &$item_list)
  1136. {
  1137. foreach ($children as $child) {
  1138. $item_list[] = $child;
  1139. if (isset($child['children'])) {
  1140. add_children_to_list($child['children'], $item_list);
  1141. }
  1142. }
  1143. }
  1144. /**
  1145. * This recursive function takes the item tree structure created by conv_sort() and
  1146. * flatten the extraneous depth levels when people reply sequentially, removing the
  1147. * stairs effect in threaded conversations limiting the available content width.
  1148. *
  1149. * The basic principle is the following: if a post item has only one reply and is
  1150. * the last reply of its parent, then the reply is moved to the parent.
  1151. *
  1152. * This process is rendered somewhat more complicated because items can be either
  1153. * replies or likes, and these don't factor at all in the reply count/last reply.
  1154. *
  1155. * @brief Selectively flattens a tree-like item structure to prevent threading stairs
  1156. *
  1157. * @param array $parent A tree-like array of items
  1158. * @return array
  1159. */
  1160. function smart_flatten_conversation(array $parent)
  1161. {
  1162. if (!isset($parent['children']) || count($parent['children']) == 0) {
  1163. return $parent;
  1164. }
  1165. // We use a for loop to ensure we process the newly-moved items
  1166. for ($i = 0; $i < count($parent['children']); $i++) {
  1167. $child = $parent['children'][$i];
  1168. if (isset($child['children']) && count($child['children'])) {
  1169. // This helps counting only the regular posts
  1170. $count_post_closure = function($var) {
  1171. return $var['verb'] === Activity::POST;
  1172. };
  1173. $child_post_count = count(array_filter($child['children'], $count_post_closure));
  1174. $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
  1175. // If there's only one child's children post and this is the last child post
  1176. if ($child_post_count == 1 && $remaining_post_count == 1) {
  1177. // Searches the post item in the children
  1178. $j = 0;
  1179. while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
  1180. $j ++;
  1181. }
  1182. $moved_item = $child['children'][$j];
  1183. unset($parent['children'][$i]['children'][$j]);
  1184. $parent['children'][] = $moved_item;
  1185. } else {
  1186. $parent['children'][$i] = smart_flatten_conversation($child);
  1187. }
  1188. }
  1189. }
  1190. return $parent;
  1191. }
  1192. /**
  1193. * Expands a flat list of items into corresponding tree-like conversation structures,
  1194. * sort the top-level posts either on "received" or "commented", and finally
  1195. * append all the items at the top level (???)
  1196. *
  1197. * @brief Expands a flat item list into a conversation array for display
  1198. *
  1199. * @param array $item_list A list of items belonging to one or more conversations
  1200. * @param string $order Either on "received" or "commented"
  1201. * @return array
  1202. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1203. */
  1204. function conv_sort(array $item_list, $order)
  1205. {
  1206. $parents = [];
  1207. if (!(is_array($item_list) && count($item_list))) {
  1208. return $parents;
  1209. }
  1210. $blocklist = conv_get_blocklist();
  1211. $item_array = [];
  1212. // Dedupes the item list on the uri to prevent infinite loops
  1213. foreach ($item_list as $item) {
  1214. if (in_array($item['author-id'], $blocklist)) {
  1215. continue;
  1216. }
  1217. $item_array[$item['uri']] = $item;
  1218. }
  1219. // Extract the top level items
  1220. foreach ($item_array as $item) {
  1221. if ($item['id'] == $item['parent']) {
  1222. $parents[] = $item;
  1223. }
  1224. }
  1225. if (stristr($order, 'pinned_received')) {
  1226. usort($parents, 'sort_thr_pinned_received');
  1227. } elseif (stristr($order, 'received')) {
  1228. usort($parents, 'sort_thr_received');
  1229. } elseif (stristr($order, 'commented')) {
  1230. usort($parents, 'sort_thr_commented');
  1231. }
  1232. /*
  1233. * Plucks children from the item_array, second pass collects eventual orphan
  1234. * items and add them as children of their top-level post.
  1235. */
  1236. foreach ($parents as $i => $parent) {
  1237. $parents[$i]['children'] =
  1238. array_merge(get_item_children($item_array, $parent, true),
  1239. get_item_children($item_array, $parent, false));
  1240. }
  1241. foreach ($parents as $i => $parent) {
  1242. $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
  1243. }
  1244. if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
  1245. foreach ($parents as $i => $parent) {
  1246. $parents[$i] = smart_flatten_conversation($parent);
  1247. }
  1248. }
  1249. /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
  1250. /// However, this apparently ensures responses (likes, attendance) display (?!)
  1251. foreach ($parents as $parent) {
  1252. if (count($parent['children'])) {
  1253. add_children_to_list($parent['children'], $parents);
  1254. }
  1255. }
  1256. return $parents;
  1257. }
  1258. /**
  1259. * @brief usort() callback to sort item arrays by pinned and the received key
  1260. *
  1261. * @param array $a
  1262. * @param array $b
  1263. * @return int
  1264. */
  1265. function sort_thr_pinned_received(array $a, array $b)
  1266. {
  1267. if ($b['pinned'] && !$a['pinned']) {
  1268. return 1;
  1269. } elseif (!$b['pinned'] && $a['pinned']) {
  1270. return -1;
  1271. }
  1272. return strcmp($b['received'], $a['received']);
  1273. }
  1274. /**
  1275. * @brief usort() callback to sort item arrays by the received key
  1276. *
  1277. * @param array $a
  1278. * @param array $b
  1279. * @return int
  1280. */
  1281. function sort_thr_received(array $a, array $b)
  1282. {
  1283. return strcmp($b['received'], $a['received']);
  1284. }
  1285. /**
  1286. * @brief usort() callback to reverse sort item arrays by the received key
  1287. *
  1288. * @param array $a
  1289. * @param array $b
  1290. * @return int
  1291. */
  1292. function sort_thr_received_rev(array $a, array $b)
  1293. {
  1294. return strcmp($a['received'], $b['received']);
  1295. }
  1296. /**
  1297. * @brief usort() callback to sort item arrays by the commented key
  1298. *
  1299. * @param array $a
  1300. * @param array $b
  1301. * @return int
  1302. */
  1303. function sort_thr_commented(array $a, array $b)
  1304. {
  1305. return strcmp($b['commented'], $a['commented']);
  1306. }
  1307. function render_location_dummy(array $item) {
  1308. if (!empty($item['location']) && !empty($item['location'])) {
  1309. return $item['location'];
  1310. }
  1311. if (!empty($item['coord']) && !empty($item['coord'])) {
  1312. return $item['coord'];
  1313. }
  1314. }
  1315. function get_responses(array $conv_responses, array $response_verbs, array $item, Post $ob = null) {
  1316. $ret = [];
  1317. foreach ($response_verbs as $v) {
  1318. $ret[$v] = [];
  1319. $ret[$v]['count'] = $conv_responses[$v][$item['uri']] ?? 0;
  1320. $ret[$v]['list'] = $conv_responses[$v][$item['uri'] . '-l'] ?? [];
  1321. $ret[$v]['self'] = $conv_responses[$v][$item['uri'] . '-self'] ?? '0';
  1322. if (count($ret[$v]['list']) > MAX_LIKERS) {
  1323. $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
  1324. array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
  1325. . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . L10n::t('View all') . '</b></a>');
  1326. } else {
  1327. $ret[$v]['list_part'] = '';
  1328. }
  1329. $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
  1330. $ret[$v]['title'] = $conv_responses[$v]['title'];
  1331. }
  1332. $count = 0;
  1333. foreach ($ret as $key) {
  1334. if ($key['count'] == true) {
  1335. $count++;
  1336. }
  1337. }
  1338. $ret['count'] = $count;
  1339. return $ret;
  1340. }
  1341. function get_response_button_text($v, $count)
  1342. {
  1343. $return = '';
  1344. switch ($v) {
  1345. case 'like':
  1346. $return = L10n::tt('Like', 'Likes', $count);
  1347. break;
  1348. case 'dislike':
  1349. $return = L10n::tt('Dislike', 'Dislikes', $count);
  1350. break;
  1351. case 'attendyes':
  1352. $return = L10n::tt('Attending', 'Attending', $count);
  1353. break;
  1354. case 'attendno':
  1355. $return = L10n::tt('Not Attending', 'Not Attending', $count);
  1356. break;
  1357. case 'attendmaybe':
  1358. $return = L10n::tt('Undecided', 'Undecided', $count);
  1359. break;
  1360. }
  1361. return $return;
  1362. }