3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 use Friendica\Content\ForumManager;
24 use Friendica\Content\Nav;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Widget;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\ACL;
29 use Friendica\Core\Hook;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Renderer;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Group;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post\Category;
38 use Friendica\Model\Profile;
39 use Friendica\Module\Contact as ModuleContact;
40 use Friendica\Module\Security\Login;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Strings;
44 function network_init(App $a)
47 notice(DI::l10n()->t('Permission denied.'));
51 Hook::add('head', __FILE__, 'network_infinite_scroll_head');
53 $is_a_date_query = false;
55 $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
58 if (!empty($_GET['contactid'])) {
59 $cid = $_GET['contactid'];
65 for ($x = 1; $x < $a->argc; $x ++) {
66 if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
67 $is_a_date_query = true;
73 // convert query string to array. remove friendica args
75 parse_str(parse_url(DI::args()->getQueryString(), PHP_URL_QUERY), $query_array);
77 // fetch last used network view and redirect if needed
78 if (!$is_a_date_query) {
79 $sel_nets = $_GET['nets'] ?? '';
80 $sel_tabs = network_query_get_sel_tab($a);
81 $sel_groups = network_query_get_sel_group($a);
82 $last_sel_tabs = DI::pConfig()->get(local_user(), 'network.view', 'tab.selected');
84 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
86 $net_baseurl = '/network';
89 if ($sel_groups !== false) {
90 $net_baseurl .= '/' . $sel_groups;
94 // redirect if current selected tab is '/network' and
95 // last selected tab is _not_ '/network?order=activity'.
96 // and this isn't a date query
99 'order=activity', //all
100 'order=post', //postord
105 $k = array_search('active', $last_sel_tabs);
108 // parse out tab queries
110 $dest_qs = $tab_args[$k];
111 parse_str($dest_qs, $dest_qa);
112 $net_args = array_merge($net_args, $dest_qa);
114 $remember_tab = false;
119 $net_args['nets'] = $sel_nets;
123 $net_args = array_merge($query_array, $net_args);
124 $net_queries = http_build_query($net_args);
126 $redir_url = ($net_queries ? $net_baseurl . '?' . $net_queries : $net_baseurl);
128 DI::baseUrl()->redirect($redir_url);
132 if (empty(DI::page()['aside'])) {
133 DI::page()['aside'] = '';
136 DI::page()['aside'] .= Group::sidebarWidget('network/0', 'network', 'standard', $group_id);
137 DI::page()['aside'] .= ForumManager::widget(local_user(), $cid);
138 DI::page()['aside'] .= Widget::postedByYear('network', local_user(), false);
139 DI::page()['aside'] .= Widget::networks('network', $_GET['nets'] ?? '');
140 DI::page()['aside'] .= Widget\SavedSearches::getHTML(DI::args()->getQueryString());
141 DI::page()['aside'] .= Widget::fileAs('network', $_GET['file'] ?? '');
145 * Return selected tab from query
148 * '/network' => $no_active = 'active'
149 * '/network?order=activity' => $activity_active = 'active'
150 * '/network?order=post' => $postord_active = 'active'
151 * '/network?conv=1', => $conv_active = 'active'
152 * '/network?star=1', => $starred_active = 'active'
155 * @return array ($no_active, $activity_active, $postord_active, $conv_active, $starred_active);
157 function network_query_get_sel_tab(App $a)
160 $starred_active = '';
163 $postord_active = '';
165 if (!empty($_GET['star'])) {
166 $starred_active = 'active';
169 if (!empty($_GET['conv'])) {
170 $conv_active = 'active';
173 if (($starred_active == '') && ($conv_active == '')) {
174 $no_active = 'active';
177 if ($no_active == 'active' && !empty($_GET['order'])) {
178 switch($_GET['order']) {
179 case 'post' : $postord_active = 'active'; $no_active=''; break;
180 case 'activity' : $all_active = 'active'; $no_active=''; break;
184 return [$no_active, $all_active, $postord_active, $conv_active, $starred_active];
187 function network_query_get_sel_group(App $a)
191 if ($a->argc >= 2 && is_numeric($a->argv[1])) {
192 $group = $a->argv[1];
199 * Sets the pager data and returns SQL
201 * @param App $a The global App
202 * @param Pager $pager
203 * @return string SQL with the appropriate LIMIT clause
204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
206 function networkPager(App $a, Pager $pager)
208 if (DI::mode()->isMobile()) {
209 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
210 DI::config()->get('system', 'itemspage_network_mobile'));
212 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
213 DI::config()->get('system', 'itemspage_network'));
216 // now that we have the user settings, see if the theme forces
217 // a maximum item number which is lower then the user choice
218 if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
219 $itemspage_network = $a->force_max_items;
222 $pager->setItemsPerPage($itemspage_network);
228 * @param array $condition The array with the SQL condition
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 function networkSetSeen($condition)
233 if (empty($condition)) {
237 $unseen = Item::exists($condition);
240 Item::update(['unseen' => false], $condition);
245 * Create the conversation HTML
247 * @param App $a The global App
248 * @param array $items Items of the conversation
249 * @param Pager $pager
250 * @param string $mode Display mode for the conversation
251 * @param integer $update Used for the automatic reloading
252 * @param string $ordering
253 * @return string HTML of the conversation
254 * @throws ImagickException
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257 function networkConversation(App $a, $items, Pager $pager, $mode, $update, $ordering = '')
259 // Set this so that the conversation function can find out contact info for our wall-wall items
260 $a->page_contact = $a->contact;
262 if (!is_array($items)) {
263 Logger::info('Expecting items to be an array.', ['items' => $items]);
267 $o = conversation($a, $items, $mode, $update, false, $ordering, local_user());
270 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
271 $o .= HTML::scrollLoader();
273 $o .= $pager->renderMinimal(count($items));
280 function network_content(App $a, $update = 0, $parent = 0)
283 return Login::form();
286 /// @TODO Is this really necessary? $a is already available to hooks
287 $arr = ['query' => DI::args()->getQueryString()];
288 Hook::callAll('network_content_init', $arr);
290 if (!empty($_GET['file'])) {
291 $o = networkFlatView($a, $update);
293 $o = networkThreadedView($a, $update, $parent);
296 if (!$update && ($o === '')) {
297 notice(DI::l10n()->t("No items found"));
304 * Get the network content in flat view
306 * @param App $a The global App
307 * @param integer $update Used for the automatic reloading
308 * @return string HTML of the network content in flat view
309 * @throws ImagickException
310 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
311 * @global Pager $pager
313 function networkFlatView(App $a, $update = 0)
316 // Rawmode is used for fetching new content at the end of the page
317 $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
321 $file = $_GET['file'] ?? '';
323 if (!$update && !$rawmode) {
324 $tabs = network_tabs($a);
327 Nav::setSelected('network');
331 'allow_location' => $a->user['allow_location'],
332 'default_location' => $a->user['default-location'],
333 'nickname' => $a->user['nickname'],
334 'lockstate' => (is_array($a->user) &&
335 (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
336 strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock'),
337 'default_perms' => ACL::getDefaultUserPermissions($a->user),
338 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true),
340 'visitor' => 'block',
341 'profile_uid' => local_user(),
345 $o .= status_editor($a, $x);
347 if (!DI::config()->get('theme', 'hide_eventlist')) {
348 $o .= Profile::getBirthdays();
349 $o .= Profile::getEventsReminderHTML();
353 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
355 networkPager($a, $pager);
358 $item_params = ['order' => ['uri-id' => true]];
359 $term_condition = ['name' => $file, 'type' => Category::FILE, 'uid' => local_user()];
360 $term_params = ['order' => ['uri-id' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
361 $result = DBA::select('category-view', ['uri-id'], $term_condition, $term_params);
364 while ($term = DBA::fetch($result)) {
365 $posts[] = $term['uri-id'];
369 if (count($posts) == 0) {
372 $item_condition = ['uid' => local_user(), 'uri-id' => $posts];
374 $item_params = ['order' => ['id' => true]];
375 $item_condition = ['uid' => local_user()];
376 $item_params['limit'] = [$pager->getStart(), $pager->getItemsPerPage()];
378 networkSetSeen(['unseen' => true, 'uid' => local_user()]);
381 $result = Item::selectForUser(local_user(), [], $item_condition, $item_params);
382 $items = Item::inArray($result);
383 $o .= networkConversation($a, $items, $pager, 'network-new', $update);
389 * Get the network content in threaded view
391 * @param App $a The global App
392 * @param integer $update Used for the automatic reloading
393 * @param integer $parent
394 * @return string HTML of the network content in flat view
395 * @throws ImagickException
396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
397 * @global Pager $pager
399 function networkThreadedView(App $a, $update, $parent)
401 /// @TODO this will have to be converted to a static property of the converted Module\Network class
404 // Rawmode is used for fetching new content at the end of the page
405 $rawmode = (isset($_GET['mode']) AND ($_GET['mode'] == 'raw'));
407 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
408 $last_commented = isset($_GET['last_commented']) ? DateTimeFormat::utc($_GET['last_commented']) : '';
409 $last_created = isset($_GET['last_created']) ? DateTimeFormat::utc($_GET['last_created']) : '';
410 $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
412 $datequery = $datequery2 = '';
416 $default_permissions = [];
419 for ($x = 1; $x < $a->argc; $x ++) {
420 if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
422 $datequery2 = Strings::escapeHtml($a->argv[$x]);
424 $datequery = Strings::escapeHtml($a->argv[$x]);
425 $_GET['order'] = 'post';
427 } elseif (intval($a->argv[$x])) {
428 $gid = intval($a->argv[$x]);
429 $default_permissions['allow_gid'] = [$gid];
436 $cid = intval($_GET['contactid'] ?? 0);
437 $star = intval($_GET['star'] ?? 0);
438 $conv = intval($_GET['conv'] ?? 0);
439 $order = Strings::escapeTags(($_GET['order'] ?? '') ?: 'activity');
440 $nets = $_GET['nets'] ?? '';
444 $allowedCids[] = (int) $cid;
447 'uid' => local_user(),
453 'rel' => [Contact::SHARING, Contact::FRIEND],
455 $contactStmt = DBA::select('contact', ['id'], $condition);
456 while ($contact = DBA::fetch($contactStmt)) {
457 $allowedCids[] = (int) $contact['id'];
459 DBA::close($contactStmt);
462 if (count($allowedCids)) {
463 $default_permissions['allow_cid'] = $allowedCids;
466 if (!$update && !$rawmode) {
467 $tabs = network_tabs($a);
470 Nav::setSelected('network');
475 // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
476 $condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
477 $contact = DBA::selectFirst('contact', ['addr'], $condition);
478 if (!empty($contact['addr'])) {
479 $content = '!' . $contact['addr'];
485 'allow_location' => $a->user['allow_location'],
486 'default_location' => $a->user['default-location'],
487 'nickname' => $a->user['nickname'],
488 'lockstate' => ($gid || $cid || $nets || (is_array($a->user) &&
489 (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
490 strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
491 'default_perms' => ACL::getDefaultUserPermissions($a->user),
492 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true, $default_permissions),
493 'bang' => (($gid || $cid || $nets) ? '!' : ''),
494 'visitor' => 'block',
495 'profile_uid' => local_user(),
496 'content' => $content,
499 $o .= status_editor($a, $x);
502 $sql_table = $update ? '`item`' : '`thread`';
504 $sql_extra = ($star ? " AND `thread`.`starred` " : '') .
505 ($conv ? " AND $sql_table.`mention`" : '') .
506 ($nets ? sprintf(" AND $sql_table.`network` = '%s' ", DBA::escape($nets)) : '');
509 $sql_extra .= Strings::protectSprintf(sprintf(" AND $sql_table.received <= '%s' ",
510 DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
513 $sql_extra .= Strings::protectSprintf(sprintf(" AND $sql_table.received >= '%s' ",
514 DBA::escape(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
518 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
519 if (!DBA::isResult($group)) {
523 notice(DI::l10n()->t('No such group'));
524 DI::baseUrl()->redirect('network/0');
528 $sql_extra .= sprintf(" AND `thread`.`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = %d) ", intval($gid));
530 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
531 '$title' => DI::l10n()->t('Group: %s', $group['name'])
534 $contact = Contact::getById($cid);
535 if (DBA::isResult($contact)) {
536 $sql_extra .= " AND " . $sql_table . ".`contact-id` = " . intval($cid);
538 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
539 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
543 notice(DI::l10n()->t('Invalid contact.'));
544 DI::baseUrl()->redirect('network');
547 } elseif (!$update && !DI::config()->get('theme', 'hide_eventlist')) {
548 $o .= Profile::getBirthdays();
549 $o .= Profile::getEventsReminderHTML();
552 // Normal conversation view
553 if ($order === 'post') {
554 $ordering = '`received`';
555 $order_mode = 'received';
557 $ordering = '`commented`';
558 $order_mode = 'commented';
561 $sql_order = "$sql_table.$ordering";
563 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
565 networkPager($a, $pager);
567 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
571 // Currently only the order modes "received" and "commented" are in use
572 switch ($order_mode) {
574 if ($last_received != '') {
575 $sql_extra .= sprintf(" AND $sql_table.`received` < '%s'", DBA::escape($last_received));
579 if ($last_commented != '') {
580 $sql_extra .= sprintf(" AND $sql_table.`commented` < '%s'", DBA::escape($last_commented));
584 if ($last_created != '') {
585 $sql_extra .= sprintf(" AND $sql_table.`created` < '%s'", DBA::escape($last_created));
589 if ($last_uriid > 0) {
590 $sql_extra .= sprintf(" AND $sql_table.`uri-id` < '%s'", DBA::escape($last_uriid));
595 // Fetch a page full of parent items for this page
597 if (!empty($parent)) {
598 // Load only a single thread
599 $sql_extra2 = "`item`.`id` = ".intval($parent);
601 // Load all unseen items
602 $sql_extra2 = "`item`.`unseen`";
605 $r = q("SELECT `item`.`parent-uri` AS `uri`, `item`.`parent` AS `item_id`, $sql_order AS `order_date`
607 INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`
608 STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
609 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
610 LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
611 WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
612 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
613 AND NOT `thread`.`moderated` AND $sql_extra2
615 ORDER BY `order_date` DESC LIMIT 100",
616 intval(local_user()),
620 $r = q("SELECT `item`.`uri`, `thread`.`iid` AS `item_id`, $sql_order AS `order_date`
622 STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
623 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
624 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
625 LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
626 WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
627 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
628 AND NOT `thread`.`moderated`
630 ORDER BY `order_date` DESC LIMIT %d, %d",
631 intval(local_user()),
632 intval(local_user()),
633 intval($pager->getStart()),
634 intval($pager->getItemsPerPage())
638 return $o . network_display_post($a, $pager, (!$gid && !$cid && !$star), $update, $ordering, $r);
641 function network_display_post($a, $pager, $mark_all, $update, $ordering, $items)
645 if (DBA::isResult($items)) {
648 foreach ($items as $item) {
649 if (!in_array($item['item_id'], $parents_arr) && ($item['item_id'] > 0)) {
650 $parents_arr[] = $item['item_id'];
653 $parents_str = implode(', ', $parents_arr);
656 $query_string = DI::args()->getQueryString();
658 $pager->setQueryString($query_string);
660 // We aren't going to try and figure out at the item, group, and page
661 // level which items you've seen and which you haven't. If you're looking
662 // at the top level network page just mark everything seen.
665 $condition = ['unseen' => true, 'uid' => local_user()];
666 networkSetSeen($condition);
667 } elseif ($parents_str) {
668 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
669 networkSetSeen($condition);
672 return networkConversation($a, $items, $pager, 'network', $update, $ordering);
676 * Get the network tabs menu
678 * @param App $a The global App
679 * @return string Html of the networktab
680 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
682 function network_tabs(App $a)
685 /// @TODO fix this logic, reduce duplication
686 /// DI::page()['content'] .= '<div class="tabs-wrapper">';
687 list($no_active, $all_active, $post_active, $conv_active, $starred_active) = network_query_get_sel_tab($a);
689 // if no tabs are selected, defaults to activitys
690 if ($no_active == 'active') {
691 $all_active = 'active';
694 $cmd = DI::args()->getCommand();
697 if (!empty($_GET['contactid'])) {
698 $def_param['contactid'] = $_GET['contactid'];
704 'label' => DI::l10n()->t('Latest Activity'),
705 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'activity'])),
706 'sel' => $all_active,
707 'title' => DI::l10n()->t('Sort by latest activity'),
708 'id' => 'activity-order-tab',
712 'label' => DI::l10n()->t('Latest Posts'),
713 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'post'])),
714 'sel' => $post_active,
715 'title' => DI::l10n()->t('Sort by post received date'),
716 'id' => 'post-order-tab',
722 'label' => DI::l10n()->t('Personal'),
723 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['conv' => true])),
724 'sel' => $conv_active,
725 'title' => DI::l10n()->t('Posts that mention or involve you'),
726 'id' => 'personal-tab',
731 'label' => DI::l10n()->t('Starred'),
732 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['star' => true])),
733 'sel' => $starred_active,
734 'title' => DI::l10n()->t('Favourite Posts'),
735 'id' => 'starred-posts-tab',
739 // save selected tab, but only if not in file mode
740 if (empty($_GET['file'])) {
741 DI::pConfig()->set(local_user(), 'network.view', 'tab.selected', [
742 $all_active, $post_active, $conv_active, $starred_active
746 $arr = ['tabs' => $tabs];
747 Hook::callAll('network_tabs', $arr);
749 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
751 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
753 // --- end item filter tabs
757 * Network hook into the HTML head to enable infinite scroll.
759 * Since the HTML head is built after the module content has been generated, we need to retrieve the base query string
760 * of the page to make the correct asynchronous call. This is obtained through the Pager that was instantiated in
761 * networkThreadedView or networkFlatView.
764 * @param string $htmlhead The head tag HTML string
765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766 * @global Pager $pager
768 function network_infinite_scroll_head(App $a, &$htmlhead)
770 /// @TODO this will have to be converted to a static property of the converted Module\Network class
776 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')
777 && ($_GET['mode'] ?? '') != 'minimal'
779 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
780 $htmlhead .= Renderer::replaceMacros($tpl, [
781 '$pageno' => $pager->getPage(),
782 '$reload_uri' => $pager->getBaseQueryString()