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 $conditionFields = ['uid' => local_user()];
503 $conditionStrings = [];
506 $conditionFields['starred'] = true;
509 $conditionFields['mention'] = true;
512 $conditionFields['network'] = $nets;
516 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get())]);
519 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get())]);
523 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
524 if (!DBA::isResult($group)) {
528 notice(DI::l10n()->t('No such group'));
529 DI::baseUrl()->redirect('network/0');
533 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $gid]);
535 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
536 '$title' => DI::l10n()->t('Group: %s', $group['name'])
539 $contact = Contact::getById($cid);
540 if (DBA::isResult($contact)) {
541 $conditionFields['contact-id'] = $cid;
543 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
544 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
548 notice(DI::l10n()->t('Invalid contact.'));
549 DI::baseUrl()->redirect('network');
552 } elseif (!$update && !DI::config()->get('theme', 'hide_eventlist')) {
553 $o .= Profile::getBirthdays();
554 $o .= Profile::getEventsReminderHTML();
557 // Normal conversation view
558 if ($order === 'post') {
559 $ordering = '`received`';
560 $order_mode = 'received';
562 $ordering = '`commented`';
563 $order_mode = 'commented';
566 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
568 networkPager($a, $pager);
570 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
574 // Currently only the order modes "received" and "commented" are in use
575 switch ($order_mode) {
577 if ($last_received != '') {
578 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $last_received]);
582 if ($last_commented != '') {
583 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $last_commented]);
587 if ($last_created != '') {
588 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $last_created]);
592 if ($last_uriid > 0) {
593 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $last_uriid]);
598 // Fetch a page full of parent items for this page
600 if (!empty($parent)) {
601 // Load only a single thread
602 $conditionFields['parent'] = $parent;
603 } elseif ($order === 'post') {
604 // Only load new toplevel posts
605 $conditionFields['unseen'] = true;
606 $conditionFields['gravity'] = GRAVITY_PARENT;
608 // Load all unseen items
609 $conditionFields['unseen'] = true;
612 $params = ['order' => [$order_mode => true], 'limit' => 100];
613 $table = 'network-item-view';
615 $params = ['order' => [$order_mode => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
616 $table = 'network-thread-view';
618 $r = DBA::selectToArray($table, [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
620 return $o . network_display_post($a, $pager, (!$gid && !$cid && !$star), $update, $ordering, $r);
623 function network_display_post($a, $pager, $mark_all, $update, $ordering, $items)
627 if (DBA::isResult($items)) {
630 foreach ($items as $item) {
631 if (!in_array($item['parent'], $parents_arr) && ($item['parent'] > 0)) {
632 $parents_arr[] = $item['parent'];
635 $parents_str = implode(', ', $parents_arr);
638 $query_string = DI::args()->getQueryString();
640 $pager->setQueryString($query_string);
642 // We aren't going to try and figure out at the item, group, and page
643 // level which items you've seen and which you haven't. If you're looking
644 // at the top level network page just mark everything seen.
647 $condition = ['unseen' => true, 'uid' => local_user()];
648 networkSetSeen($condition);
649 } elseif ($parents_str) {
650 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
651 networkSetSeen($condition);
654 return networkConversation($a, $items, $pager, 'network', $update, $ordering);
658 * Get the network tabs menu
660 * @param App $a The global App
661 * @return string Html of the networktab
662 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
664 function network_tabs(App $a)
667 /// @TODO fix this logic, reduce duplication
668 /// DI::page()['content'] .= '<div class="tabs-wrapper">';
669 list($no_active, $all_active, $post_active, $conv_active, $starred_active) = network_query_get_sel_tab($a);
671 // if no tabs are selected, defaults to activitys
672 if ($no_active == 'active') {
673 $all_active = 'active';
676 $cmd = DI::args()->getCommand();
679 if (!empty($_GET['contactid'])) {
680 $def_param['contactid'] = $_GET['contactid'];
686 'label' => DI::l10n()->t('Latest Activity'),
687 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'activity'])),
688 'sel' => $all_active,
689 'title' => DI::l10n()->t('Sort by latest activity'),
690 'id' => 'activity-order-tab',
694 'label' => DI::l10n()->t('Latest Posts'),
695 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'post'])),
696 'sel' => $post_active,
697 'title' => DI::l10n()->t('Sort by post received date'),
698 'id' => 'post-order-tab',
704 'label' => DI::l10n()->t('Personal'),
705 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['conv' => true])),
706 'sel' => $conv_active,
707 'title' => DI::l10n()->t('Posts that mention or involve you'),
708 'id' => 'personal-tab',
713 'label' => DI::l10n()->t('Starred'),
714 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['star' => true])),
715 'sel' => $starred_active,
716 'title' => DI::l10n()->t('Favourite Posts'),
717 'id' => 'starred-posts-tab',
721 // save selected tab, but only if not in file mode
722 if (empty($_GET['file'])) {
723 DI::pConfig()->set(local_user(), 'network.view', 'tab.selected', [
724 $all_active, $post_active, $conv_active, $starred_active
728 $arr = ['tabs' => $tabs];
729 Hook::callAll('network_tabs', $arr);
731 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
733 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
735 // --- end item filter tabs
739 * Network hook into the HTML head to enable infinite scroll.
741 * Since the HTML head is built after the module content has been generated, we need to retrieve the base query string
742 * of the page to make the correct asynchronous call. This is obtained through the Pager that was instantiated in
743 * networkThreadedView or networkFlatView.
746 * @param string $htmlhead The head tag HTML string
747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
748 * @global Pager $pager
750 function network_infinite_scroll_head(App $a, &$htmlhead)
752 /// @TODO this will have to be converted to a static property of the converted Module\Network class
758 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')
759 && ($_GET['mode'] ?? '') != 'minimal'
761 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
762 $htmlhead .= Renderer::replaceMacros($tpl, [
763 '$pageno' => $pager->getPage(),
764 '$reload_uri' => $pager->getBaseQueryString()