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.
 
 
 
 
 
 

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