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.

1069 lines
32 KiB

7 years ago
3 years ago
4 years ago
  1. <?php
  2. /**
  3. * @file mod/network.php
  4. */
  5. use Friendica\App;
  6. use Friendica\Content\Feature;
  7. use Friendica\Content\ForumManager;
  8. use Friendica\Content\Nav;
  9. use Friendica\Content\Pager;
  10. use Friendica\Content\Widget;
  11. use Friendica\Content\Text\HTML;
  12. use Friendica\Core\ACL;
  13. use Friendica\Core\Addon;
  14. use Friendica\Core\Config;
  15. use Friendica\Core\Hook;
  16. use Friendica\Core\L10n;
  17. use Friendica\Core\Logger;
  18. use Friendica\Core\PConfig;
  19. use Friendica\Core\Protocol;
  20. use Friendica\Core\Renderer;
  21. use Friendica\Database\DBA;
  22. use Friendica\Model\Contact;
  23. use Friendica\Model\Group;
  24. use Friendica\Model\Item;
  25. use Friendica\Model\Profile;
  26. use Friendica\Module\Login;
  27. use Friendica\Util\DateTimeFormat;
  28. use Friendica\Util\Proxy as ProxyUtils;
  29. use Friendica\Util\Strings;
  30. require_once 'include/conversation.php';
  31. require_once 'include/items.php';
  32. function network_init(App $a)
  33. {
  34. if (!local_user()) {
  35. notice(L10n::t('Permission denied.') . EOL);
  36. return;
  37. }
  38. Hook::add('head', __FILE__, 'network_infinite_scroll_head');
  39. $search = (x($_GET, 'search') ? Strings::escapeTags($_GET['search']) : '');
  40. if (($search != '') && !empty($_GET['submit'])) {
  41. $a->internalRedirect('search?search=' . urlencode($search));
  42. }
  43. if (x($_GET, 'save')) {
  44. $exists = DBA::exists('search', ['uid' => local_user(), 'term' => $search]);
  45. if (!$exists) {
  46. DBA::insert('search', ['uid' => local_user(), 'term' => $search]);
  47. }
  48. }
  49. if (x($_GET, 'remove')) {
  50. DBA::delete('search', ['uid' => local_user(), 'term' => $search]);
  51. }
  52. $is_a_date_query = false;
  53. $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
  54. $cid = 0;
  55. if (x($_GET, 'cid') && intval($_GET['cid']) != 0) {
  56. $cid = $_GET['cid'];
  57. $_GET['nets'] = 'all';
  58. $group_id = 0;
  59. }
  60. if ($a->argc > 1) {
  61. for ($x = 1; $x < $a->argc; $x ++) {
  62. if (is_a_date_arg($a->argv[$x])) {
  63. $is_a_date_query = true;
  64. break;
  65. }
  66. }
  67. }
  68. // convert query string to array. remove friendica args
  69. $query_array = [];
  70. $query_string = str_replace($a->cmd . '?', '', $a->query_string);
  71. parse_str($query_string, $query_array);
  72. array_shift($query_array);
  73. // fetch last used network view and redirect if needed
  74. if (!$is_a_date_query) {
  75. $sel_nets = defaults($_GET, 'nets', false);
  76. $sel_tabs = network_query_get_sel_tab($a);
  77. $sel_groups = network_query_get_sel_group($a);
  78. $last_sel_tabs = PConfig::get(local_user(), 'network.view', 'tab.selected');
  79. $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
  80. $net_baseurl = '/network';
  81. $net_args = [];
  82. if ($sel_groups !== false) {
  83. $net_baseurl .= '/' . $sel_groups;
  84. }
  85. if ($remember_tab) {
  86. // redirect if current selected tab is '/network' and
  87. // last selected tab is _not_ '/network?f=&order=comment'.
  88. // and this isn't a date query
  89. $tab_baseurls = [
  90. '', //all
  91. '', //postord
  92. '', //conv
  93. '/new', //new
  94. '', //starred
  95. '', //bookmarked
  96. ];
  97. $tab_args = [
  98. 'f=&order=comment', //all
  99. 'f=&order=post', //postord
  100. 'f=&conv=1', //conv
  101. '', //new
  102. 'f=&star=1', //starred
  103. 'f=&bmark=1', //bookmarked
  104. ];
  105. $k = array_search('active', $last_sel_tabs);
  106. if ($k != 3) {
  107. $net_baseurl .= $tab_baseurls[$k];
  108. // parse out tab queries
  109. $dest_qa = [];
  110. $dest_qs = $tab_args[$k];
  111. parse_str($dest_qs, $dest_qa);
  112. $net_args = array_merge($net_args, $dest_qa);
  113. } else {
  114. $remember_tab = false;
  115. }
  116. }
  117. if ($sel_nets !== false) {
  118. $net_args['nets'] = $sel_nets;
  119. }
  120. if ($remember_tab) {
  121. $net_args = array_merge($query_array, $net_args);
  122. $net_queries = build_querystring($net_args);
  123. $redir_url = ($net_queries ? $net_baseurl . '?' . $net_queries : $net_baseurl);
  124. $a->internalRedirect($redir_url);
  125. }
  126. }
  127. // If nets is set to all, unset it
  128. if (x($_GET, 'nets') && $_GET['nets'] === 'all') {
  129. unset($_GET['nets']);
  130. }
  131. if (!x($a->page, 'aside')) {
  132. $a->page['aside'] = '';
  133. }
  134. $a->page['aside'] .= (Feature::isEnabled(local_user(), 'groups') ?
  135. Group::sidebarWidget('network/0', 'network', 'standard', $group_id) : '');
  136. $a->page['aside'] .= (Feature::isEnabled(local_user(), 'forumlist_widget') ? ForumManager::widget(local_user(), $cid) : '');
  137. $a->page['aside'] .= posted_date_widget('network', local_user(), false);
  138. $a->page['aside'] .= Widget::networks('network', (x($_GET, 'nets') ? $_GET['nets'] : ''));
  139. $a->page['aside'] .= saved_searches($search);
  140. $a->page['aside'] .= Widget::fileAs('network', (x($_GET, 'file') ? $_GET['file'] : ''));
  141. }
  142. function saved_searches($search)
  143. {
  144. if (!Feature::isEnabled(local_user(), 'savedsearch')) {
  145. return '';
  146. }
  147. $a = get_app();
  148. $srchurl = '/network?f='
  149. . ((x($_GET, 'cid')) ? '&cid=' . $_GET['cid'] : '')
  150. . ((x($_GET, 'star')) ? '&star=' . $_GET['star'] : '')
  151. . ((x($_GET, 'bmark')) ? '&bmark=' . $_GET['bmark'] : '')
  152. . ((x($_GET, 'conv')) ? '&conv=' . $_GET['conv'] : '')
  153. . ((x($_GET, 'nets')) ? '&nets=' . $_GET['nets'] : '')
  154. . ((x($_GET, 'cmin')) ? '&cmin=' . $_GET['cmin'] : '')
  155. . ((x($_GET, 'cmax')) ? '&cmax=' . $_GET['cmax'] : '')
  156. . ((x($_GET, 'file')) ? '&file=' . $_GET['file'] : '');
  157. ;
  158. $o = '';
  159. $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
  160. $saved = [];
  161. while ($rr = DBA::fetch($terms)) {
  162. $saved[] = [
  163. 'id' => $rr['id'],
  164. 'term' => $rr['term'],
  165. 'encodedterm' => urlencode($rr['term']),
  166. 'delete' => L10n::t('Remove term'),
  167. 'selected' => ($search == $rr['term']),
  168. ];
  169. }
  170. $tpl = Renderer::getMarkupTemplate('saved_searches_aside.tpl');
  171. $o = Renderer::replaceMacros($tpl, [
  172. '$title' => L10n::t('Saved Searches'),
  173. '$add' => L10n::t('add'),
  174. '$searchbox' => HTML::search($search, 'netsearch-box', $srchurl, true),
  175. '$saved' => $saved,
  176. ]);
  177. return $o;
  178. }
  179. /**
  180. * Return selected tab from query
  181. *
  182. * urls -> returns
  183. * '/network' => $no_active = 'active'
  184. * '/network?f=&order=comment' => $comment_active = 'active'
  185. * '/network?f=&order=post' => $postord_active = 'active'
  186. * '/network?f=&conv=1', => $conv_active = 'active'
  187. * '/network/new', => $new_active = 'active'
  188. * '/network?f=&star=1', => $starred_active = 'active'
  189. * '/network?f=&bmark=1', => $bookmarked_active = 'active'
  190. *
  191. * @return Array ($no_active, $comment_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active);
  192. */
  193. function network_query_get_sel_tab(App $a)
  194. {
  195. $no_active = '';
  196. $starred_active = '';
  197. $new_active = '';
  198. $bookmarked_active = '';
  199. $all_active = '';
  200. $conv_active = '';
  201. $postord_active = '';
  202. if (($a->argc > 1 && $a->argv[1] === 'new') || ($a->argc > 2 && $a->argv[2] === 'new')) {
  203. $new_active = 'active';
  204. }
  205. if (x($_GET, 'star')) {
  206. $starred_active = 'active';
  207. }
  208. if (x($_GET, 'bmark')) {
  209. $bookmarked_active = 'active';
  210. }
  211. if (x($_GET, 'conv')) {
  212. $conv_active = 'active';
  213. }
  214. if (($new_active == '') && ($starred_active == '') && ($bookmarked_active == '') && ($conv_active == '')) {
  215. $no_active = 'active';
  216. }
  217. if ($no_active == 'active' && x($_GET, 'order')) {
  218. switch($_GET['order']) {
  219. case 'post' : $postord_active = 'active'; $no_active=''; break;
  220. case 'comment' : $all_active = 'active'; $no_active=''; break;
  221. }
  222. }
  223. return [$no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active];
  224. }
  225. function network_query_get_sel_group(App $a)
  226. {
  227. $group = false;
  228. if ($a->argc >= 2 && is_numeric($a->argv[1])) {
  229. $group = $a->argv[1];
  230. }
  231. return $group;
  232. }
  233. /**
  234. * @brief Sets the pager data and returns SQL
  235. *
  236. * @param App $a The global App
  237. * @param integer $update Used for the automatic reloading
  238. * @return string SQL with the appropriate LIMIT clause
  239. */
  240. function networkPager(App $a, Pager $pager, $update)
  241. {
  242. if ($update) {
  243. // only setup pagination on initial page view
  244. return ' LIMIT 100';
  245. }
  246. // check if we serve a mobile device and get the user settings
  247. // accordingly
  248. if ($a->is_mobile) {
  249. $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_mobile_network');
  250. $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 20);
  251. } else {
  252. $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_network');
  253. $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 40);
  254. }
  255. // now that we have the user settings, see if the theme forces
  256. // a maximum item number which is lower then the user choice
  257. if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
  258. $itemspage_network = $a->force_max_items;
  259. }
  260. $pager->setItemsPerPage($itemspage_network);
  261. return sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
  262. }
  263. /**
  264. * @brief Sets items as seen
  265. *
  266. * @param array $condition The array with the SQL condition
  267. */
  268. function networkSetSeen($condition)
  269. {
  270. if (empty($condition)) {
  271. return;
  272. }
  273. $unseen = Item::exists($condition);
  274. if ($unseen) {
  275. $r = Item::update(['unseen' => false], $condition);
  276. }
  277. }
  278. /**
  279. * @brief Create the conversation HTML
  280. *
  281. * @param App $a The global App
  282. * @param array $items Items of the conversation
  283. * @param string $mode Display mode for the conversation
  284. * @param integer $update Used for the automatic reloading
  285. * @return string HTML of the conversation
  286. */
  287. function networkConversation(App $a, $items, Pager $pager, $mode, $update, $ordering = '')
  288. {
  289. // Set this so that the conversation function can find out contact info for our wall-wall items
  290. $a->page_contact = $a->contact;
  291. $o = conversation($a, $items, $pager, $mode, $update, false, $ordering, local_user());
  292. if (!$update) {
  293. if (PConfig::get(local_user(), 'system', 'infinite_scroll')) {
  294. $o .= HTML::scrollLoader();
  295. } else {
  296. $o .= $pager->renderMinimal(count($items));
  297. }
  298. }
  299. return $o;
  300. }
  301. function network_content(App $a, $update = 0, $parent = 0)
  302. {
  303. if (!local_user()) {
  304. return Login::form();
  305. }
  306. /// @TODO Is this really necessary? $a is already available to hooks
  307. $arr = ['query' => $a->query_string];
  308. Addon::callHooks('network_content_init', $arr);
  309. $flat_mode = false;
  310. if ($a->argc > 1) {
  311. for ($x = 1; $x < $a->argc; $x ++) {
  312. if ($a->argv[$x] === 'new') {
  313. $flat_mode = true;
  314. }
  315. }
  316. }
  317. if (!empty($_GET['file'])) {
  318. $flat_mode = true;
  319. }
  320. if ($flat_mode) {
  321. $o = networkFlatView($a, $update);
  322. } else {
  323. $o = networkThreadedView($a, $update, $parent);
  324. }
  325. return $o;
  326. }
  327. /**
  328. * @brief Get the network content in flat view
  329. *
  330. * @param Pager $pager
  331. * @param App $a The global App
  332. * @param integer $update Used for the automatic reloading
  333. * @return string HTML of the network content in flat view
  334. */
  335. function networkFlatView(App $a, $update = 0)
  336. {
  337. global $pager;
  338. // Rawmode is used for fetching new content at the end of the page
  339. $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
  340. if (isset($_GET['last_id'])) {
  341. $last_id = intval($_GET['last_id']);
  342. } else {
  343. $last_id = 0;
  344. }
  345. $o = '';
  346. $file = defaults($_GET, 'file', '');
  347. if (!$update && !$rawmode) {
  348. $tabs = network_tabs($a);
  349. $o .= $tabs;
  350. Nav::setSelected('network');
  351. $x = [
  352. 'is_owner' => true,
  353. 'allow_location' => $a->user['allow_location'],
  354. 'default_location' => $a->user['default-location'],
  355. 'nickname' => $a->user['nickname'],
  356. 'lockstate' => (is_array($a->user) &&
  357. (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
  358. strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock'),
  359. 'default_perms' => ACL::getDefaultUserPermissions($a->user),
  360. 'acl' => ACL::getFullSelectorHTML($a->user, true),
  361. 'bang' => '',
  362. 'visitor' => 'block',
  363. 'profile_uid' => local_user(),
  364. 'content' => '',
  365. ];
  366. $o .= status_editor($a, $x);
  367. if (!Config::get('theme', 'hide_eventlist')) {
  368. $o .= Profile::getBirthdays();
  369. $o .= Profile::getEventsReminderHTML();
  370. }
  371. }
  372. $pager = new Pager($a->query_string);
  373. /// @TODO Figure out why this variable is unused
  374. $pager_sql = networkPager($a, $pager, $update);
  375. if (strlen($file)) {
  376. $condition = ["`term` = ? AND `otype` = ? AND `type` = ? AND `uid` = ?",
  377. $file, TERM_OBJ_POST, TERM_FILE, local_user()];
  378. $params = ['order' => ['tid' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
  379. $result = DBA::select('term', ['oid'], $condition);
  380. $posts = [];
  381. while ($term = DBA::fetch($result)) {
  382. $posts[] = $term['oid'];
  383. }
  384. DBA::close($result);
  385. $condition = ['uid' => local_user(), 'id' => $posts];
  386. } else {
  387. $condition = ['uid' => local_user()];
  388. }
  389. $params = ['order' => ['id' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
  390. $result = Item::selectForUser(local_user(), [], $condition, $params);
  391. $items = Item::inArray($result);
  392. $condition = ['unseen' => true, 'uid' => local_user()];
  393. networkSetSeen($condition);
  394. $o .= networkConversation($a, $items, $pager, 'network-new', $update);
  395. return $o;
  396. }
  397. /**
  398. * @brief Get the network content in threaded view
  399. *
  400. * @global Pager $pager
  401. * @param App $a The global App
  402. * @param integer $update Used for the automatic reloading
  403. * @param integer $parent
  404. * @return string HTML of the network content in flat view
  405. */
  406. function networkThreadedView(App $a, $update, $parent)
  407. {
  408. /// @TODO this will have to be converted to a static property of the converted Module\Network class
  409. global $pager;
  410. // Rawmode is used for fetching new content at the end of the page
  411. $rawmode = (isset($_GET['mode']) AND ( $_GET['mode'] == 'raw'));
  412. if (isset($_GET['last_received']) && isset($_GET['last_commented']) && isset($_GET['last_created']) && isset($_GET['last_id'])) {
  413. $last_received = DateTimeFormat::utc($_GET['last_received']);
  414. $last_commented = DateTimeFormat::utc($_GET['last_commented']);
  415. $last_created = DateTimeFormat::utc($_GET['last_created']);
  416. $last_id = intval($_GET['last_id']);
  417. } else {
  418. $last_received = '';
  419. $last_commented = '';
  420. $last_created = '';
  421. $last_id = 0;
  422. }
  423. $datequery = $datequery2 = '';
  424. $gid = 0;
  425. $default_permissions = [];
  426. if ($a->argc > 1) {
  427. for ($x = 1; $x < $a->argc; $x ++) {
  428. if (is_a_date_arg($a->argv[$x])) {
  429. if ($datequery) {
  430. $datequery2 = Strings::escapeTags($a->argv[$x]);
  431. } else {
  432. $datequery = Strings::escapeTags($a->argv[$x]);
  433. $_GET['order'] = 'post';
  434. }
  435. } elseif (intval($a->argv[$x])) {
  436. $gid = intval($a->argv[$x]);
  437. $default_permissions = ['allow_gid' => '<' . $gid . '>'];
  438. }
  439. }
  440. }
  441. $o = '';
  442. $cid = intval(defaults($_GET, 'cid' , 0));
  443. $star = intval(defaults($_GET, 'star' , 0));
  444. $bmark = intval(defaults($_GET, 'bmark', 0));
  445. $conv = intval(defaults($_GET, 'conv' , 0));
  446. $order = Strings::removeTags(defaults($_GET, 'order', 'comment'));
  447. $nets = defaults($_GET, 'nets' , '');
  448. if ($cid) {
  449. $default_permissions = ['allow_cid' => '<' . intval($cid) . '>'];
  450. }
  451. if ($nets) {
  452. $r = DBA::select('contact', ['id'], ['uid' => local_user(), 'network' => $nets], ['self' => false]);
  453. $str = '';
  454. while ($rr = DBA::fetch($r)) {
  455. $str .= '<' . $rr['id'] . '>';
  456. }
  457. if (strlen($str)) {
  458. $default_permissions = ['allow_cid' => $str];
  459. }
  460. }
  461. if (!$update && !$rawmode) {
  462. $tabs = network_tabs($a);
  463. $o .= $tabs;
  464. if ($gid && ($t = Contact::getOStatusCountByGroupId($gid)) && !PConfig::get(local_user(), 'system', 'nowarn_insecure')) {
  465. notice(L10n::tt("Warning: This group contains %s member from a network that doesn't allow non public messages.",
  466. "Warning: This group contains %s members from a network that doesn't allow non public messages.",
  467. $t) . EOL);
  468. notice(L10n::t("Messages in this group won't be send to these receivers.").EOL);
  469. }
  470. Nav::setSelected('network');
  471. $content = '';
  472. if ($cid) {
  473. // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
  474. $condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
  475. $contact = DBA::selectFirst('contact', ['addr', 'nick'], $condition);
  476. if (DBA::isResult($contact)) {
  477. if ($contact['addr'] != '') {
  478. $content = '!' . $contact['addr'];
  479. } else {
  480. $content = '!' . $contact['nick'] . '+' . $cid;
  481. }
  482. }
  483. }
  484. $x = [
  485. 'is_owner' => true,
  486. 'allow_location' => $a->user['allow_location'],
  487. 'default_location' => $a->user['default-location'],
  488. 'nickname' => $a->user['nickname'],
  489. 'lockstate' => ($gid || $cid || $nets || (is_array($a->user) &&
  490. (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
  491. strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
  492. 'default_perms' => ACL::getDefaultUserPermissions($a->user),
  493. 'acl' => ACL::getFullSelectorHTML($a->user, true, $default_permissions),
  494. 'bang' => (($gid || $cid || $nets) ? '!' : ''),
  495. 'visitor' => 'block',
  496. 'profile_uid' => local_user(),
  497. 'content' => $content,
  498. ];
  499. $o .= status_editor($a, $x);
  500. }
  501. // We don't have to deal with ACLs on this page. You're looking at everything
  502. // that belongs to you, hence you can see all of it. We will filter by group if
  503. // desired.
  504. $sql_post_table = '';
  505. $sql_options = ($star ? " AND `thread`.`starred` " : '');
  506. $sql_options .= ($bmark ? sprintf(" AND `thread`.`post-type` = %d ", Item::PT_PAGE) : '');
  507. $sql_extra = $sql_options;
  508. $sql_extra2 = '';
  509. $sql_extra3 = '';
  510. $sql_table = '`thread`';
  511. $sql_parent = '`iid`';
  512. $sql_order = '';
  513. if ($update) {
  514. $sql_table = '`item`';
  515. $sql_parent = '`parent`';
  516. $sql_post_table = " INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`";
  517. }
  518. $sql_nets = (($nets) ? sprintf(" AND $sql_table.`network` = '%s' ", DBA::escape($nets)) : '');
  519. $sql_tag_nets = (($nets) ? sprintf(" AND `item`.`network` = '%s' ", DBA::escape($nets)) : '');
  520. if ($gid) {
  521. $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
  522. if (!DBA::isResult($group)) {
  523. if ($update) {
  524. killme();
  525. }
  526. notice(L10n::t('No such group') . EOL);
  527. $a->internalRedirect('network/0');
  528. // NOTREACHED
  529. }
  530. $contacts = Group::expand([$gid]);
  531. if ((is_array($contacts)) && count($contacts)) {
  532. $contact_str_self = '';
  533. $contact_str = implode(',', $contacts);
  534. $self = DBA::selectFirst('contact', ['id'], ['uid' => local_user(), 'self' => true]);
  535. if (DBA::isResult($self)) {
  536. $contact_str_self = $self['id'];
  537. }
  538. $sql_post_table .= " INNER JOIN `item` AS `temp1` ON `temp1`.`id` = " . $sql_table . "." . $sql_parent;
  539. $sql_extra3 .= " AND (`thread`.`contact-id` IN ($contact_str) ";
  540. $sql_extra3 .= " OR (`thread`.`contact-id` = '$contact_str_self' AND `temp1`.`allow_gid` LIKE '" . Strings::protectSprintf('%<' . intval($gid) . '>%') . "' AND `temp1`.`private`))";
  541. } else {
  542. $sql_extra3 .= " AND false ";
  543. info(L10n::t('Group is empty'));
  544. }
  545. $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
  546. '$title' => L10n::t('Group: %s', $group['name'])
  547. ]) . $o;
  548. } elseif ($cid) {
  549. $fields = ['id', 'name', 'network', 'writable', 'nurl',
  550. 'forum', 'prv', 'contact-type', 'addr', 'thumb', 'location'];
  551. $condition = ["`id` = ? AND (NOT `blocked` OR `pending`)", $cid];
  552. $contact = DBA::selectFirst('contact', $fields, $condition);
  553. if (DBA::isResult($contact)) {
  554. $sql_extra = " AND " . $sql_table . ".`contact-id` = " . intval($cid);
  555. $entries[0] = [
  556. 'id' => 'network',
  557. 'name' => htmlentities($contact['name']),
  558. 'itemurl' => defaults($contact, 'addr', $contact['nurl']),
  559. 'thumb' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
  560. 'details' => $contact['location'],
  561. ];
  562. $entries[0]['account_type'] = Contact::getAccountType($contact);
  563. $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
  564. 'contacts' => $entries,
  565. 'id' => 'network',
  566. ]) . $o;
  567. if ($contact['network'] === Protocol::OSTATUS && $contact['writable'] && !PConfig::get(local_user(),'system','nowarn_insecure')) {
  568. notice(L10n::t('Private messages to this person are at risk of public disclosure.') . EOL);
  569. }
  570. } else {
  571. notice(L10n::t('Invalid contact.') . EOL);
  572. $a->internalRedirect('network');
  573. // NOTREACHED
  574. }
  575. }
  576. if (!$gid && !$cid && !$update && !Config::get('theme', 'hide_eventlist')) {
  577. $o .= Profile::getBirthdays();
  578. $o .= Profile::getEventsReminderHTML();
  579. }
  580. if ($datequery) {
  581. $sql_extra3 .= Strings::protectSprintf(sprintf(" AND $sql_table.created <= '%s' ",
  582. DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
  583. }
  584. if ($datequery2) {
  585. $sql_extra3 .= Strings::protectSprintf(sprintf(" AND $sql_table.created >= '%s' ",
  586. DBA::escape(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
  587. }
  588. if ($conv) {
  589. $sql_extra3 .= " AND $sql_table.`mention`";
  590. }
  591. // Normal conversation view
  592. if ($order === 'post') {
  593. $ordering = '`created`';
  594. $order_mode = 'created';
  595. } else {
  596. $ordering = '`commented`';
  597. $order_mode = 'commented';
  598. }
  599. $sql_order = "$sql_table.$ordering";
  600. if (!empty($_GET['offset'])) {
  601. $sql_range = sprintf(" AND $sql_order <= '%s'", DBA::escape($_GET['offset']));
  602. } else {
  603. $sql_range = '';
  604. }
  605. $pager = new Pager($a->query_string);
  606. $pager_sql = networkPager($a, $pager, $update);
  607. $last_date = '';
  608. switch ($order_mode) {
  609. case 'received':
  610. if ($last_received != '') {
  611. $last_date = $last_received;
  612. $sql_range .= sprintf(" AND $sql_table.`received` < '%s'", DBA::escape($last_received));
  613. $pager->setPage(1);
  614. $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
  615. }
  616. break;
  617. case 'commented':
  618. if ($last_commented != '') {
  619. $last_date = $last_commented;
  620. $sql_range .= sprintf(" AND $sql_table.`commented` < '%s'", DBA::escape($last_commented));
  621. $pager->setPage(1);
  622. $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
  623. }
  624. break;
  625. case 'created':
  626. if ($last_created != '') {
  627. $last_date = $last_created;
  628. $sql_range .= sprintf(" AND $sql_table.`created` < '%s'", DBA::escape($last_created));
  629. $pager->setPage(1);
  630. $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
  631. }
  632. break;
  633. case 'id':
  634. if (($last_id > 0) && ($sql_table == '`thread`')) {
  635. $sql_range .= sprintf(" AND $sql_table.`iid` < '%s'", DBA::escape($last_id));
  636. $pager->setPage(1);
  637. $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
  638. }
  639. break;
  640. }
  641. // Fetch a page full of parent items for this page
  642. if ($update) {
  643. if (!empty($parent)) {
  644. // Load only a single thread
  645. $sql_extra4 = "`item`.`id` = ".intval($parent);
  646. } else {
  647. // Load all unseen items
  648. $sql_extra4 = "`item`.`unseen`";
  649. if (Config::get("system", "like_no_comment")) {
  650. $sql_extra4 .= " AND `item`.`gravity` IN (" . GRAVITY_PARENT . "," . GRAVITY_COMMENT . ")";
  651. }
  652. if ($order === 'post') {
  653. // Only show toplevel posts when updating posts in this order mode
  654. $sql_extra4 .= " AND `item`.`id` = `item`.`parent`";
  655. }
  656. }
  657. $r = q("SELECT `item`.`parent-uri` AS `uri`, `item`.`parent` AS `item_id`, $sql_order AS `order_date`
  658. FROM `item` $sql_post_table
  659. STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  660. AND (NOT `contact`.`blocked` OR `contact`.`pending`)
  661. AND (`item`.`gravity` != %d
  662. OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
  663. OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
  664. LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
  665. WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted`
  666. AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
  667. AND NOT `item`.`moderated` AND $sql_extra4
  668. $sql_extra3 $sql_extra $sql_range $sql_nets
  669. ORDER BY `order_date` DESC LIMIT 100",
  670. intval(GRAVITY_PARENT),
  671. intval(Contact::SHARING),
  672. intval(Contact::FRIEND),
  673. intval(local_user()),
  674. intval(local_user())
  675. );
  676. } else {
  677. $r = q("SELECT `item`.`uri`, `thread`.`iid` AS `item_id`, $sql_order AS `order_date`
  678. FROM `thread` $sql_post_table
  679. STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
  680. AND (NOT `contact`.`blocked` OR `contact`.`pending`)
  681. STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
  682. AND (`item`.`gravity` != %d
  683. OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
  684. OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
  685. LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
  686. WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
  687. AND NOT `thread`.`moderated`
  688. AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
  689. $sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets
  690. ORDER BY `order_date` DESC $pager_sql",
  691. intval(GRAVITY_PARENT),
  692. intval(Contact::SHARING),
  693. intval(Contact::FRIEND),
  694. intval(local_user()),
  695. intval(local_user())
  696. );
  697. }
  698. // Only show it when unfiltered (no groups, no networks, ...)
  699. if (in_array($nets, ['', Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]) && (strlen($sql_extra . $sql_extra2 . $sql_extra3) == 0)) {
  700. if (DBA::isResult($r)) {
  701. $top_limit = current($r)['order_date'];
  702. $bottom_limit = end($r)['order_date'];
  703. if (empty($_SESSION['network_last_top_limit']) || ($_SESSION['network_last_top_limit'] < $top_limit)) {
  704. $_SESSION['network_last_top_limit'] = $top_limit;
  705. }
  706. } else {
  707. $top_limit = $bottom_limit = DateTimeFormat::utcNow();
  708. }
  709. // When checking for updates we need to fetch from the newest date to the newest date before
  710. // Only do this, when the last stored date isn't too long ago (10 times the update interval)
  711. $browser_update = PConfig::get(local_user(), 'system', 'update_interval', 40000) / 1000;
  712. if (($browser_update > 0) && $update && !empty($_SESSION['network_last_date']) &&
  713. (($bottom_limit < $_SESSION['network_last_date']) || ($top_limit == $bottom_limit)) &&
  714. ((time() - $_SESSION['network_last_date_timestamp']) < ($browser_update * 10))) {
  715. $bottom_limit = $_SESSION['network_last_date'];
  716. }
  717. $_SESSION['network_last_date'] = defaults($_SESSION, 'network_last_top_limit', $top_limit);
  718. $_SESSION['network_last_date_timestamp'] = time();
  719. if ($last_date > $top_limit) {
  720. $top_limit = $last_date;
  721. } elseif ($pager->getPage() == 1) {
  722. // Highest possible top limit when we are on the first page
  723. $top_limit = DateTimeFormat::utcNow();
  724. }
  725. $items = DBA::p("SELECT `item`.`parent-uri` AS `uri`, 0 AS `item_id`, `item`.$ordering AS `order_date`, `author`.`url` AS `author-link` FROM `item`
  726. STRAIGHT_JOIN (SELECT `oid` FROM `term` WHERE `term` IN
  727. (SELECT SUBSTR(`term`, 2) FROM `search` WHERE `uid` = ? AND `term` LIKE '#%') AND `otype` = ? AND `type` = ? AND `uid` = 0) AS `term`
  728. ON `item`.`id` = `term`.`oid`
  729. STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = `item`.`author-id`
  730. WHERE `item`.`uid` = 0 AND `item`.$ordering < ? AND `item`.$ordering > ?
  731. AND NOT `author`.`hidden` AND NOT `author`.`blocked`" . $sql_tag_nets,
  732. local_user(), TERM_OBJ_POST, TERM_HASHTAG,
  733. $top_limit, $bottom_limit);
  734. $data = DBA::toArray($items);
  735. if (count($data) > 0) {
  736. $tag_top_limit = current($data)['order_date'];
  737. if ($_SESSION['network_last_date'] < $tag_top_limit) {
  738. $_SESSION['network_last_date'] = $tag_top_limit;
  739. }
  740. Logger::log('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update);
  741. $s = [];
  742. foreach ($r as $item) {
  743. $s[$item['uri']] = $item;
  744. }
  745. foreach ($data as $item) {
  746. // Don't show hash tag posts from blocked or ignored contacts
  747. $condition = ["`nurl` = ? AND `uid` = ? AND (`blocked` OR `readonly`)",
  748. Strings::normaliseLink($item['author-link']), local_user()];
  749. if (!DBA::exists('contact', $condition)) {
  750. $s[$item['uri']] = $item;
  751. }
  752. }
  753. $r = $s;
  754. }
  755. }
  756. $parents_str = '';
  757. $date_offset = '';
  758. $items = $r;
  759. if (DBA::isResult($items)) {
  760. $parents_arr = [];
  761. foreach ($items as $item) {
  762. if ($date_offset < $item['order_date']) {
  763. $date_offset = $item['order_date'];
  764. }
  765. if (!in_array($item['item_id'], $parents_arr) && ($item['item_id'] > 0)) {
  766. $parents_arr[] = $item['item_id'];
  767. }
  768. }
  769. $parents_str = implode(', ', $parents_arr);
  770. }
  771. if (x($_GET, 'offset')) {
  772. $date_offset = $_GET['offset'];
  773. }
  774. $query_string = $a->query_string;
  775. if ($date_offset && !preg_match('/[?&].offset=/', $query_string)) {
  776. $query_string .= '&offset=' . urlencode($date_offset);
  777. }
  778. $pager->setQueryString($query_string);
  779. // We aren't going to try and figure out at the item, group, and page
  780. // level which items you've seen and which you haven't. If you're looking
  781. // at the top level network page just mark everything seen.
  782. if (!$gid && !$cid && !$star) {
  783. $condition = ['unseen' => true, 'uid' => local_user()];
  784. networkSetSeen($condition);
  785. } elseif ($parents_str) {
  786. $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
  787. networkSetSeen($condition);
  788. }
  789. $mode = 'network';
  790. $o .= networkConversation($a, $items, $pager, $mode, $update, $ordering);
  791. return $o;
  792. }
  793. /**
  794. * @brief Get the network tabs menu
  795. *
  796. * @param App $a The global App
  797. * @return string Html of the networktab
  798. */
  799. function network_tabs(App $a)
  800. {
  801. // item filter tabs
  802. /// @TODO fix this logic, reduce duplication
  803. /// $a->page['content'] .= '<div class="tabs-wrapper">';
  804. list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active) = network_query_get_sel_tab($a);
  805. // if no tabs are selected, defaults to comments
  806. if ($no_active == 'active') {
  807. $all_active = 'active';
  808. }
  809. $cmd = $a->cmd;
  810. // tabs
  811. $tabs = [
  812. [
  813. 'label' => L10n::t('Commented Order'),
  814. 'url' => str_replace('/new', '', $cmd) . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
  815. 'sel' => $all_active,
  816. 'title' => L10n::t('Sort by Comment Date'),
  817. 'id' => 'commented-order-tab',
  818. 'accesskey' => 'e',
  819. ],
  820. [
  821. 'label' => L10n::t('Posted Order'),
  822. 'url' => str_replace('/new', '', $cmd) . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
  823. 'sel' => $postord_active,
  824. 'title' => L10n::t('Sort by Post Date'),
  825. 'id' => 'posted-order-tab',
  826. 'accesskey' => 't',
  827. ],
  828. ];
  829. if (Feature::isEnabled(local_user(), 'personal_tab')) {
  830. $tabs[] = [
  831. 'label' => L10n::t('Personal'),
  832. 'url' => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&conv=1',
  833. 'sel' => $conv_active,
  834. 'title' => L10n::t('Posts that mention or involve you'),
  835. 'id' => 'personal-tab',
  836. 'accesskey' => 'r',
  837. ];
  838. }
  839. if (Feature::isEnabled(local_user(), 'new_tab')) {
  840. $tabs[] = [
  841. 'label' => L10n::t('New'),
  842. 'url' => 'network/new' . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : ''),
  843. 'sel' => $new_active,
  844. 'title' => L10n::t('Activity Stream - by date'),
  845. 'id' => 'activitiy-by-date-tab',
  846. 'accesskey' => 'w',
  847. ];
  848. }
  849. if (Feature::isEnabled(local_user(), 'link_tab')) {
  850. $tabs[] = [
  851. 'label' => L10n::t('Shared Links'),
  852. 'url' => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&bmark=1',
  853. 'sel' => $bookmarked_active,
  854. 'title' => L10n::t('Interesting Links'),
  855. 'id' => 'shared-links-tab',
  856. 'accesskey' => 'b',
  857. ];
  858. }
  859. if (Feature::isEnabled(local_user(), 'star_posts')) {
  860. $tabs[] = [
  861. 'label' => L10n::t('Starred'),
  862. 'url' => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&star=1',
  863. 'sel' => $starred_active,
  864. 'title' => L10n::t('Favourite Posts'),
  865. 'id' => 'starred-posts-tab',
  866. 'accesskey' => 'm',
  867. ];
  868. }
  869. // save selected tab, but only if not in file mode
  870. if (!x($_GET, 'file')) {
  871. PConfig::set(local_user(), 'network.view', 'tab.selected', [
  872. $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active
  873. ]);
  874. }
  875. $arr = ['tabs' => $tabs];
  876. Addon::callHooks('network_tabs', $arr);
  877. $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
  878. return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
  879. // --- end item filter tabs
  880. }
  881. /**
  882. * Network hook into the HTML head to enable infinite scroll.
  883. *
  884. * Since the HTML head is built after the module content has been generated, we need to retrieve the base query string
  885. * of the page to make the correct asynchronous call. This is obtained through the Pager that was instantiated in
  886. * networkThreadedView or networkFlatView.
  887. *
  888. * @global Pager $pager
  889. * @param App $a
  890. * @param string $htmlhead The head tag HTML string
  891. */
  892. function network_infinite_scroll_head(App $a, &$htmlhead)
  893. {
  894. /// @TODO this will have to be converted to a static property of the converted Module\Network class
  895. global $pager;
  896. if (PConfig::get(local_user(), 'system', 'infinite_scroll')
  897. && defaults($_GET, 'mode', '') != 'minimal'
  898. ) {
  899. $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
  900. $htmlhead .= Renderer::replaceMacros($tpl, [
  901. '$pageno' => $pager->getPage(),
  902. '$reload_uri' => $pager->getBaseQueryString()
  903. ]);
  904. }
  905. }