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

1504 lines
48 KiB

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