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\Model\User;
40 use Friendica\Module\Contact as ModuleContact;
41 use Friendica\Module\Security\Login;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Strings;
45 function network_init(App $a)
48 notice(DI::l10n()->t('Permission denied.'));
52 $is_a_date_query = false;
54 $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
57 if (!empty($_GET['contactid'])) {
58 $cid = $_GET['contactid'];
64 for ($x = 1; $x < $a->argc; $x ++) {
65 if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
66 $is_a_date_query = true;
72 // convert query string to array. remove friendica args
74 parse_str(parse_url(DI::args()->getQueryString(), PHP_URL_QUERY), $query_array);
76 // fetch last used network view and redirect if needed
77 if (!$is_a_date_query) {
78 $sel_nets = $_GET['nets'] ?? '';
79 $sel_tabs = network_query_get_sel_tab($a);
80 $sel_groups = network_query_get_sel_group($a);
81 $last_sel_tabs = DI::pConfig()->get(local_user(), 'network.view', 'tab.selected');
83 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
85 $net_baseurl = '/network';
88 if ($sel_groups !== false) {
89 $net_baseurl .= '/' . $sel_groups;
93 // redirect if current selected tab is '/network' and
94 // last selected tab is _not_ '/network?order=activity'.
95 // and this isn't a date query
98 'order=activity', //all
99 'order=post', //postord
104 $k = array_search('active', $last_sel_tabs);
107 // parse out tab queries
109 $dest_qs = $tab_args[$k];
110 parse_str($dest_qs, $dest_qa);
111 $net_args = array_merge($net_args, $dest_qa);
113 $remember_tab = false;
118 $net_args['nets'] = $sel_nets;
122 $net_args = array_merge($query_array, $net_args);
123 $net_queries = http_build_query($net_args);
125 $redir_url = ($net_queries ? $net_baseurl . '?' . $net_queries : $net_baseurl);
127 DI::baseUrl()->redirect($redir_url);
131 if (empty(DI::page()['aside'])) {
132 DI::page()['aside'] = '';
135 if (!empty(User::getAccountTypeByString($a->argv[1] ?? ''))) {
136 $accounttype = $a->argv[1];
141 DI::page()['aside'] .= Widget::accounts('network', $accounttype);
142 DI::page()['aside'] .= Group::sidebarWidget('network/0', 'network', 'standard', $group_id);
143 DI::page()['aside'] .= ForumManager::widget(local_user(), $cid);
144 DI::page()['aside'] .= Widget::postedByYear('network', local_user(), false);
145 DI::page()['aside'] .= Widget::networks('network', $_GET['nets'] ?? '');
146 DI::page()['aside'] .= Widget\SavedSearches::getHTML(DI::args()->getQueryString());
147 DI::page()['aside'] .= Widget::fileAs('network', $_GET['file'] ?? '');
151 * Return selected tab from query
154 * '/network' => $no_active = 'active'
155 * '/network?order=activity' => $activity_active = 'active'
156 * '/network?order=post' => $postord_active = 'active'
157 * '/network?conv=1', => $conv_active = 'active'
158 * '/network?star=1', => $starred_active = 'active'
161 * @return array ($no_active, $activity_active, $postord_active, $conv_active, $starred_active);
163 function network_query_get_sel_tab(App $a)
166 $starred_active = '';
169 $postord_active = '';
171 if (!empty($_GET['star'])) {
172 $starred_active = 'active';
175 if (!empty($_GET['conv'])) {
176 $conv_active = 'active';
179 if (($starred_active == '') && ($conv_active == '')) {
180 $no_active = 'active';
183 if ($no_active == 'active' && !empty($_GET['order'])) {
184 switch($_GET['order']) {
185 case 'post' : $postord_active = 'active'; $no_active=''; break;
186 case 'activity' : $all_active = 'active'; $no_active=''; break;
190 return [$no_active, $all_active, $postord_active, $conv_active, $starred_active];
193 function network_query_get_sel_group(App $a)
197 if ($a->argc >= 2 && is_numeric($a->argv[1])) {
198 $group = $a->argv[1];
205 * Sets the pager data and returns SQL
207 * @param App $a The global App
208 * @param Pager $pager
209 * @return string SQL with the appropriate LIMIT clause
210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212 function networkPager(App $a, Pager $pager)
214 if (DI::mode()->isMobile()) {
215 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
216 DI::config()->get('system', 'itemspage_network_mobile'));
218 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
219 DI::config()->get('system', 'itemspage_network'));
222 // now that we have the user settings, see if the theme forces
223 // a maximum item number which is lower then the user choice
224 if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
225 $itemspage_network = $a->force_max_items;
228 $pager->setItemsPerPage($itemspage_network);
234 * @param array $condition The array with the SQL condition
235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
237 function networkSetSeen($condition)
239 if (empty($condition)) {
243 $unseen = Item::exists($condition);
246 Item::update(['unseen' => false], $condition);
251 * Create the conversation HTML
253 * @param App $a The global App
254 * @param array $items Items of the conversation
255 * @param Pager $pager
256 * @param string $mode Display mode for the conversation
257 * @param integer $update Used for the automatic reloading
258 * @param string $ordering
259 * @return string HTML of the conversation
260 * @throws ImagickException
261 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
263 function networkConversation(App $a, $items, Pager $pager, $mode, $update, $ordering = '')
265 // Set this so that the conversation function can find out contact info for our wall-wall items
266 $a->page_contact = $a->contact;
268 if (!is_array($items)) {
269 Logger::info('Expecting items to be an array.', ['items' => $items]);
273 $o = conversation($a, $items, $mode, $update, false, $ordering, local_user());
276 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
277 $o .= HTML::scrollLoader();
279 $o .= $pager->renderMinimal(count($items));
286 function network_content(App $a, $update = 0, $parent = 0)
289 return Login::form();
292 /// @TODO Is this really necessary? $a is already available to hooks
293 $arr = ['query' => DI::args()->getQueryString()];
294 Hook::callAll('network_content_init', $arr);
296 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
297 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
298 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
303 $account = User::getAccountTypeByString($a->argv[1] ?? '');
305 if (!empty($_GET['file'])) {
306 $o .= networkFlatView($a, $update, $account);
308 $o .= networkThreadedView($a, $update, $parent, $account);
311 if (!$update && ($o === '')) {
312 notice(DI::l10n()->t("No items found"));
319 * Get the network content in flat view
321 * @param App $a The global App
322 * @param integer $update Used for the automatic reloading
323 * @return string HTML of the network content in flat view
324 * @throws ImagickException
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326 * @global Pager $pager
328 function networkFlatView(App $a, $update, $account)
331 // Rawmode is used for fetching new content at the end of the page
332 $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
336 $file = $_GET['file'] ?? '';
338 if (!$update && !$rawmode) {
339 $tabs = network_tabs($a);
342 Nav::setSelected('network');
346 'allow_location' => $a->user['allow_location'],
347 'default_location' => $a->user['default-location'],
348 'nickname' => $a->user['nickname'],
349 'lockstate' => (is_array($a->user) &&
350 (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
351 strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock'),
352 'default_perms' => ACL::getDefaultUserPermissions($a->user),
353 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true),
355 'visitor' => 'block',
356 'profile_uid' => local_user(),
360 $o .= status_editor($a, $x);
362 if (!DI::config()->get('theme', 'hide_eventlist')) {
363 $o .= Profile::getBirthdays();
364 $o .= Profile::getEventsReminderHTML();
368 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
370 networkPager($a, $pager);
373 $item_params = ['order' => ['uri-id' => true]];
374 $term_condition = ['name' => $file, 'type' => Category::FILE, 'uid' => local_user()];
375 $term_params = ['order' => ['uri-id' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
376 $result = DBA::select('category-view', ['uri-id'], $term_condition, $term_params);
379 while ($term = DBA::fetch($result)) {
380 $posts[] = $term['uri-id'];
384 if (count($posts) == 0) {
387 $item_condition = ['uid' => local_user(), 'uri-id' => $posts];
389 $item_params = ['order' => ['id' => true]];
390 $item_condition = ['uid' => local_user()];
391 $item_params['limit'] = [$pager->getStart(), $pager->getItemsPerPage()];
393 networkSetSeen(['unseen' => true, 'uid' => local_user()]);
396 if (!empty($account)) {
397 $item_condition['contact-type'] = $account;
400 $result = Item::selectForUser(local_user(), [], $item_condition, $item_params);
401 $items = Item::inArray($result);
402 $o .= networkConversation($a, $items, $pager, 'network-new', $update);
408 * Get the network content in threaded view
410 * @param App $a The global App
411 * @param integer $update Used for the automatic reloading
412 * @param integer $parent
413 * @return string HTML of the network content in flat view
414 * @throws ImagickException
415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
416 * @global Pager $pager
418 function networkThreadedView(App $a, $update, $parent, $account)
420 /// @TODO this will have to be converted to a static property of the converted Module\Network class
423 // Rawmode is used for fetching new content at the end of the page
424 $rawmode = (isset($_GET['mode']) AND ($_GET['mode'] == 'raw'));
426 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
427 $last_commented = isset($_GET['last_commented']) ? DateTimeFormat::utc($_GET['last_commented']) : '';
428 $last_created = isset($_GET['last_created']) ? DateTimeFormat::utc($_GET['last_created']) : '';
429 $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
431 $datequery = $datequery2 = '';
435 $default_permissions = [];
438 for ($x = 1; $x < $a->argc; $x ++) {
439 if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
441 $datequery2 = Strings::escapeHtml($a->argv[$x]);
443 $datequery = Strings::escapeHtml($a->argv[$x]);
444 $_GET['order'] = 'post';
446 } elseif (intval($a->argv[$x])) {
447 $gid = intval($a->argv[$x]);
448 $default_permissions['allow_gid'] = [$gid];
455 $cid = intval($_GET['contactid'] ?? 0);
456 $star = intval($_GET['star'] ?? 0);
457 $conv = intval($_GET['conv'] ?? 0);
458 $order = Strings::escapeTags(($_GET['order'] ?? '') ?: 'activity');
459 $nets = $_GET['nets'] ?? '';
463 $allowedCids[] = (int) $cid;
466 'uid' => local_user(),
472 'rel' => [Contact::SHARING, Contact::FRIEND],
474 $contactStmt = DBA::select('contact', ['id'], $condition);
475 while ($contact = DBA::fetch($contactStmt)) {
476 $allowedCids[] = (int) $contact['id'];
478 DBA::close($contactStmt);
481 if (count($allowedCids)) {
482 $default_permissions['allow_cid'] = $allowedCids;
485 if (!$update && !$rawmode) {
486 $tabs = network_tabs($a);
489 Nav::setSelected('network');
494 // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
495 $condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
496 $contact = DBA::selectFirst('contact', ['addr'], $condition);
497 if (!empty($contact['addr'])) {
498 $content = '!' . $contact['addr'];
504 'allow_location' => $a->user['allow_location'],
505 'default_location' => $a->user['default-location'],
506 'nickname' => $a->user['nickname'],
507 'lockstate' => ($gid || $cid || $nets || (is_array($a->user) &&
508 (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
509 strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
510 'default_perms' => ACL::getDefaultUserPermissions($a->user),
511 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true, $default_permissions),
512 'bang' => (($gid || $cid || $nets) ? '!' : ''),
513 'visitor' => 'block',
514 'profile_uid' => local_user(),
515 'content' => $content,
518 $o .= status_editor($a, $x);
521 $conditionFields = ['uid' => local_user()];
522 $conditionStrings = [];
524 if (!empty($account)) {
525 $conditionFields['contact-type'] = $account;
529 $conditionFields['starred'] = true;
532 $conditionFields['mention'] = true;
535 $conditionFields['network'] = $nets;
539 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get())]);
542 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get())]);
546 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
547 if (!DBA::isResult($group)) {
551 notice(DI::l10n()->t('No such group'));
552 DI::baseUrl()->redirect('network/0');
556 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $gid]);
558 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
559 '$title' => DI::l10n()->t('Group: %s', $group['name'])
562 $contact = Contact::getById($cid);
563 if (DBA::isResult($contact)) {
564 $conditionFields['contact-id'] = $cid;
566 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
567 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
571 notice(DI::l10n()->t('Invalid contact.'));
572 DI::baseUrl()->redirect('network');
575 } elseif (!$update && !DI::config()->get('theme', 'hide_eventlist')) {
576 $o .= Profile::getBirthdays();
577 $o .= Profile::getEventsReminderHTML();
580 // Normal conversation view
581 if ($order === 'post') {
582 $ordering = '`received`';
583 $order_mode = 'received';
585 $ordering = '`commented`';
586 $order_mode = 'commented';
589 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
591 networkPager($a, $pager);
593 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
597 // Currently only the order modes "received" and "commented" are in use
598 switch ($order_mode) {
600 if ($last_received != '') {
601 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $last_received]);
605 if ($last_commented != '') {
606 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $last_commented]);
610 if ($last_created != '') {
611 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $last_created]);
615 if ($last_uriid > 0) {
616 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $last_uriid]);
621 // Fetch a page full of parent items for this page
623 if (!empty($parent)) {
624 // Load only a single thread
625 $conditionFields['parent'] = $parent;
626 } elseif ($order === 'post') {
627 // Only load new toplevel posts
628 $conditionFields['unseen'] = true;
629 $conditionFields['gravity'] = GRAVITY_PARENT;
631 // Load all unseen items
632 $conditionFields['unseen'] = true;
635 $params = ['order' => [$order_mode => true], 'limit' => 100];
636 $table = 'network-item-view';
638 $params = ['order' => [$order_mode => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
639 $table = 'network-thread-view';
641 $r = DBA::selectToArray($table, [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
643 return $o . network_display_post($a, $pager, (!$gid && !$cid && !$star), $update, $ordering, $r);
646 function network_display_post($a, $pager, $mark_all, $update, $ordering, $items)
650 if (DBA::isResult($items)) {
653 foreach ($items as $item) {
654 if (!in_array($item['parent'], $parents_arr) && ($item['parent'] > 0)) {
655 $parents_arr[] = $item['parent'];
658 $parents_str = implode(', ', $parents_arr);
661 $pager->setQueryString(DI::args()->getQueryString());
663 // We aren't going to try and figure out at the item, group, and page
664 // level which items you've seen and which you haven't. If you're looking
665 // at the top level network page just mark everything seen.
668 $condition = ['unseen' => true, 'uid' => local_user()];
669 networkSetSeen($condition);
670 } elseif ($parents_str) {
671 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
672 networkSetSeen($condition);
675 return networkConversation($a, $items, $pager, 'network', $update, $ordering);
679 * Get the network tabs menu
681 * @param App $a The global App
682 * @return string Html of the networktab
683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
685 function network_tabs(App $a)
688 /// @TODO fix this logic, reduce duplication
689 /// DI::page()['content'] .= '<div class="tabs-wrapper">';
690 list($no_active, $all_active, $post_active, $conv_active, $starred_active) = network_query_get_sel_tab($a);
692 // if no tabs are selected, defaults to activitys
693 if ($no_active == 'active') {
694 $all_active = 'active';
697 $cmd = DI::args()->getCommand();
700 if (!empty($_GET['contactid'])) {
701 $def_param['contactid'] = $_GET['contactid'];
707 'label' => DI::l10n()->t('Latest Activity'),
708 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'activity'])),
709 'sel' => $all_active,
710 'title' => DI::l10n()->t('Sort by latest activity'),
711 'id' => 'activity-order-tab',
715 'label' => DI::l10n()->t('Latest Posts'),
716 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'post'])),
717 'sel' => $post_active,
718 'title' => DI::l10n()->t('Sort by post received date'),
719 'id' => 'post-order-tab',
725 'label' => DI::l10n()->t('Personal'),
726 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['conv' => true])),
727 'sel' => $conv_active,
728 'title' => DI::l10n()->t('Posts that mention or involve you'),
729 'id' => 'personal-tab',
734 'label' => DI::l10n()->t('Starred'),
735 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['star' => true])),
736 'sel' => $starred_active,
737 'title' => DI::l10n()->t('Favourite Posts'),
738 'id' => 'starred-posts-tab',
742 // save selected tab, but only if not in file mode
743 if (empty($_GET['file'])) {
744 DI::pConfig()->set(local_user(), 'network.view', 'tab.selected', [
745 $all_active, $post_active, $conv_active, $starred_active
749 $arr = ['tabs' => $tabs];
750 Hook::callAll('network_tabs', $arr);
752 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
754 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
756 // --- end item filter tabs