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.
 
 
 
 
 
 

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