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 $is_a_date_query = false;
53 $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
56 if (!empty($_GET['contactid'])) {
57 $cid = $_GET['contactid'];
63 for ($x = 1; $x < $a->argc; $x ++) {
64 if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
65 $is_a_date_query = true;
71 // convert query string to array. remove friendica args
73 parse_str(parse_url(DI::args()->getQueryString(), PHP_URL_QUERY), $query_array);
75 // fetch last used network view and redirect if needed
76 if (!$is_a_date_query) {
77 $sel_nets = $_GET['nets'] ?? '';
78 $sel_tabs = network_query_get_sel_tab($a);
79 $sel_groups = network_query_get_sel_group($a);
80 $last_sel_tabs = DI::pConfig()->get(local_user(), 'network.view', 'tab.selected');
82 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
84 $net_baseurl = '/network';
87 if ($sel_groups !== false) {
88 $net_baseurl .= '/' . $sel_groups;
92 // redirect if current selected tab is '/network' and
93 // last selected tab is _not_ '/network?order=activity'.
94 // and this isn't a date query
97 'order=activity', //all
98 'order=post', //postord
103 $k = array_search('active', $last_sel_tabs);
106 // parse out tab queries
108 $dest_qs = $tab_args[$k];
109 parse_str($dest_qs, $dest_qa);
110 $net_args = array_merge($net_args, $dest_qa);
112 $remember_tab = false;
117 $net_args['nets'] = $sel_nets;
121 $net_args = array_merge($query_array, $net_args);
122 $net_queries = http_build_query($net_args);
124 $redir_url = ($net_queries ? $net_baseurl . '?' . $net_queries : $net_baseurl);
126 DI::baseUrl()->redirect($redir_url);
130 if (empty(DI::page()['aside'])) {
131 DI::page()['aside'] = '';
134 DI::page()['aside'] .= Group::sidebarWidget('network/0', 'network', 'standard', $group_id);
135 DI::page()['aside'] .= ForumManager::widget(local_user(), $cid);
136 DI::page()['aside'] .= Widget::postedByYear('network', local_user(), false);
137 DI::page()['aside'] .= Widget::networks('network', $_GET['nets'] ?? '');
138 DI::page()['aside'] .= Widget\SavedSearches::getHTML(DI::args()->getQueryString());
139 DI::page()['aside'] .= Widget::fileAs('network', $_GET['file'] ?? '');
143 * Return selected tab from query
146 * '/network' => $no_active = 'active'
147 * '/network?order=activity' => $activity_active = 'active'
148 * '/network?order=post' => $postord_active = 'active'
149 * '/network?conv=1', => $conv_active = 'active'
150 * '/network?star=1', => $starred_active = 'active'
153 * @return array ($no_active, $activity_active, $postord_active, $conv_active, $starred_active);
155 function network_query_get_sel_tab(App $a)
158 $starred_active = '';
161 $postord_active = '';
163 if (!empty($_GET['star'])) {
164 $starred_active = 'active';
167 if (!empty($_GET['conv'])) {
168 $conv_active = 'active';
171 if (($starred_active == '') && ($conv_active == '')) {
172 $no_active = 'active';
175 if ($no_active == 'active' && !empty($_GET['order'])) {
176 switch($_GET['order']) {
177 case 'post' : $postord_active = 'active'; $no_active=''; break;
178 case 'activity' : $all_active = 'active'; $no_active=''; break;
182 return [$no_active, $all_active, $postord_active, $conv_active, $starred_active];
185 function network_query_get_sel_group(App $a)
189 if ($a->argc >= 2 && is_numeric($a->argv[1])) {
190 $group = $a->argv[1];
197 * Sets the pager data and returns SQL
199 * @param App $a The global App
200 * @param Pager $pager
201 * @return string SQL with the appropriate LIMIT clause
202 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
204 function networkPager(App $a, Pager $pager)
206 if (DI::mode()->isMobile()) {
207 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
208 DI::config()->get('system', 'itemspage_network_mobile'));
210 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
211 DI::config()->get('system', 'itemspage_network'));
214 // now that we have the user settings, see if the theme forces
215 // a maximum item number which is lower then the user choice
216 if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
217 $itemspage_network = $a->force_max_items;
220 $pager->setItemsPerPage($itemspage_network);
226 * @param array $condition The array with the SQL condition
227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229 function networkSetSeen($condition)
231 if (empty($condition)) {
235 $unseen = Item::exists($condition);
238 Item::update(['unseen' => false], $condition);
243 * Create the conversation HTML
245 * @param App $a The global App
246 * @param array $items Items of the conversation
247 * @param Pager $pager
248 * @param string $mode Display mode for the conversation
249 * @param integer $update Used for the automatic reloading
250 * @param string $ordering
251 * @return string HTML of the conversation
252 * @throws ImagickException
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 function networkConversation(App $a, $items, Pager $pager, $mode, $update, $ordering = '')
257 // Set this so that the conversation function can find out contact info for our wall-wall items
258 $a->page_contact = $a->contact;
260 if (!is_array($items)) {
261 Logger::info('Expecting items to be an array.', ['items' => $items]);
265 $o = conversation($a, $items, $mode, $update, false, $ordering, local_user());
268 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
269 $o .= HTML::scrollLoader();
271 $o .= $pager->renderMinimal(count($items));
278 function network_content(App $a, $update = 0, $parent = 0)
281 return Login::form();
284 /// @TODO Is this really necessary? $a is already available to hooks
285 $arr = ['query' => DI::args()->getQueryString()];
286 Hook::callAll('network_content_init', $arr);
288 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
289 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
290 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
295 if (!empty($_GET['file'])) {
296 $o .= networkFlatView($a, $update);
298 $o .= networkThreadedView($a, $update, $parent);
301 if (!$update && ($o === '')) {
302 notice(DI::l10n()->t("No items found"));
309 * Get the network content in flat view
311 * @param App $a The global App
312 * @param integer $update Used for the automatic reloading
313 * @return string HTML of the network content in flat view
314 * @throws ImagickException
315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
316 * @global Pager $pager
318 function networkFlatView(App $a, $update = 0)
321 // Rawmode is used for fetching new content at the end of the page
322 $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
326 $file = $_GET['file'] ?? '';
328 if (!$update && !$rawmode) {
329 $tabs = network_tabs($a);
332 Nav::setSelected('network');
336 'allow_location' => $a->user['allow_location'],
337 'default_location' => $a->user['default-location'],
338 'nickname' => $a->user['nickname'],
339 'lockstate' => (is_array($a->user) &&
340 (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
341 strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock'),
342 'default_perms' => ACL::getDefaultUserPermissions($a->user),
343 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true),
345 'visitor' => 'block',
346 'profile_uid' => local_user(),
350 $o .= status_editor($a, $x);
352 if (!DI::config()->get('theme', 'hide_eventlist')) {
353 $o .= Profile::getBirthdays();
354 $o .= Profile::getEventsReminderHTML();
358 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
360 networkPager($a, $pager);
363 $item_params = ['order' => ['uri-id' => true]];
364 $term_condition = ['name' => $file, 'type' => Category::FILE, 'uid' => local_user()];
365 $term_params = ['order' => ['uri-id' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
366 $result = DBA::select('category-view', ['uri-id'], $term_condition, $term_params);
369 while ($term = DBA::fetch($result)) {
370 $posts[] = $term['uri-id'];
374 if (count($posts) == 0) {
377 $item_condition = ['uid' => local_user(), 'uri-id' => $posts];
379 $item_params = ['order' => ['id' => true]];
380 $item_condition = ['uid' => local_user()];
381 $item_params['limit'] = [$pager->getStart(), $pager->getItemsPerPage()];
383 networkSetSeen(['unseen' => true, 'uid' => local_user()]);
386 $result = Item::selectForUser(local_user(), [], $item_condition, $item_params);
387 $items = Item::inArray($result);
388 $o .= networkConversation($a, $items, $pager, 'network-new', $update);
394 * Get the network content in threaded view
396 * @param App $a The global App
397 * @param integer $update Used for the automatic reloading
398 * @param integer $parent
399 * @return string HTML of the network content in flat view
400 * @throws ImagickException
401 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
402 * @global Pager $pager
404 function networkThreadedView(App $a, $update, $parent)
406 /// @TODO this will have to be converted to a static property of the converted Module\Network class
409 // Rawmode is used for fetching new content at the end of the page
410 $rawmode = (isset($_GET['mode']) AND ($_GET['mode'] == 'raw'));
412 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
413 $last_commented = isset($_GET['last_commented']) ? DateTimeFormat::utc($_GET['last_commented']) : '';
414 $last_created = isset($_GET['last_created']) ? DateTimeFormat::utc($_GET['last_created']) : '';
415 $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
417 $datequery = $datequery2 = '';
421 $default_permissions = [];
424 for ($x = 1; $x < $a->argc; $x ++) {
425 if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
427 $datequery2 = Strings::escapeHtml($a->argv[$x]);
429 $datequery = Strings::escapeHtml($a->argv[$x]);
430 $_GET['order'] = 'post';
432 } elseif (intval($a->argv[$x])) {
433 $gid = intval($a->argv[$x]);
434 $default_permissions['allow_gid'] = [$gid];
441 $cid = intval($_GET['contactid'] ?? 0);
442 $star = intval($_GET['star'] ?? 0);
443 $conv = intval($_GET['conv'] ?? 0);
444 $order = Strings::escapeTags(($_GET['order'] ?? '') ?: 'activity');
445 $nets = $_GET['nets'] ?? '';
449 $allowedCids[] = (int) $cid;
452 'uid' => local_user(),
458 'rel' => [Contact::SHARING, Contact::FRIEND],
460 $contactStmt = DBA::select('contact', ['id'], $condition);
461 while ($contact = DBA::fetch($contactStmt)) {
462 $allowedCids[] = (int) $contact['id'];
464 DBA::close($contactStmt);
467 if (count($allowedCids)) {
468 $default_permissions['allow_cid'] = $allowedCids;
471 if (!$update && !$rawmode) {
472 $tabs = network_tabs($a);
475 Nav::setSelected('network');
480 // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
481 $condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
482 $contact = DBA::selectFirst('contact', ['addr'], $condition);
483 if (!empty($contact['addr'])) {
484 $content = '!' . $contact['addr'];
490 'allow_location' => $a->user['allow_location'],
491 'default_location' => $a->user['default-location'],
492 'nickname' => $a->user['nickname'],
493 'lockstate' => ($gid || $cid || $nets || (is_array($a->user) &&
494 (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
495 strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
496 'default_perms' => ACL::getDefaultUserPermissions($a->user),
497 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true, $default_permissions),
498 'bang' => (($gid || $cid || $nets) ? '!' : ''),
499 'visitor' => 'block',
500 'profile_uid' => local_user(),
501 'content' => $content,
504 $o .= status_editor($a, $x);
507 $conditionFields = ['uid' => local_user()];
508 $conditionStrings = [];
511 $conditionFields['starred'] = true;
514 $conditionFields['mention'] = true;
517 $conditionFields['network'] = $nets;
521 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get())]);
524 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get())]);
528 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
529 if (!DBA::isResult($group)) {
533 notice(DI::l10n()->t('No such group'));
534 DI::baseUrl()->redirect('network/0');
538 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $gid]);
540 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
541 '$title' => DI::l10n()->t('Group: %s', $group['name'])
544 $contact = Contact::getById($cid);
545 if (DBA::isResult($contact)) {
546 $conditionFields['contact-id'] = $cid;
548 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
549 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
553 notice(DI::l10n()->t('Invalid contact.'));
554 DI::baseUrl()->redirect('network');
557 } elseif (!$update && !DI::config()->get('theme', 'hide_eventlist')) {
558 $o .= Profile::getBirthdays();
559 $o .= Profile::getEventsReminderHTML();
562 // Normal conversation view
563 if ($order === 'post') {
564 $ordering = '`received`';
565 $order_mode = 'received';
567 $ordering = '`commented`';
568 $order_mode = 'commented';
571 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
573 networkPager($a, $pager);
575 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
579 // Currently only the order modes "received" and "commented" are in use
580 switch ($order_mode) {
582 if ($last_received != '') {
583 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $last_received]);
587 if ($last_commented != '') {
588 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $last_commented]);
592 if ($last_created != '') {
593 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $last_created]);
597 if ($last_uriid > 0) {
598 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $last_uriid]);
603 // Fetch a page full of parent items for this page
605 if (!empty($parent)) {
606 // Load only a single thread
607 $conditionFields['parent'] = $parent;
608 } elseif ($order === 'post') {
609 // Only load new toplevel posts
610 $conditionFields['unseen'] = true;
611 $conditionFields['gravity'] = GRAVITY_PARENT;
613 // Load all unseen items
614 $conditionFields['unseen'] = true;
617 $params = ['order' => [$order_mode => true], 'limit' => 100];
618 $table = 'network-item-view';
620 $params = ['order' => [$order_mode => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
621 $table = 'network-thread-view';
623 $r = DBA::selectToArray($table, [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
625 return $o . network_display_post($a, $pager, (!$gid && !$cid && !$star), $update, $ordering, $r);
628 function network_display_post($a, $pager, $mark_all, $update, $ordering, $items)
632 if (DBA::isResult($items)) {
635 foreach ($items as $item) {
636 if (!in_array($item['parent'], $parents_arr) && ($item['parent'] > 0)) {
637 $parents_arr[] = $item['parent'];
640 $parents_str = implode(', ', $parents_arr);
643 $pager->setQueryString(DI::args()->getQueryString());
645 // We aren't going to try and figure out at the item, group, and page
646 // level which items you've seen and which you haven't. If you're looking
647 // at the top level network page just mark everything seen.
650 $condition = ['unseen' => true, 'uid' => local_user()];
651 networkSetSeen($condition);
652 } elseif ($parents_str) {
653 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
654 networkSetSeen($condition);
657 return networkConversation($a, $items, $pager, 'network', $update, $ordering);
661 * Get the network tabs menu
663 * @param App $a The global App
664 * @return string Html of the networktab
665 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
667 function network_tabs(App $a)
670 /// @TODO fix this logic, reduce duplication
671 /// DI::page()['content'] .= '<div class="tabs-wrapper">';
672 list($no_active, $all_active, $post_active, $conv_active, $starred_active) = network_query_get_sel_tab($a);
674 // if no tabs are selected, defaults to activitys
675 if ($no_active == 'active') {
676 $all_active = 'active';
679 $cmd = DI::args()->getCommand();
682 if (!empty($_GET['contactid'])) {
683 $def_param['contactid'] = $_GET['contactid'];
689 'label' => DI::l10n()->t('Latest Activity'),
690 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'activity'])),
691 'sel' => $all_active,
692 'title' => DI::l10n()->t('Sort by latest activity'),
693 'id' => 'activity-order-tab',
697 'label' => DI::l10n()->t('Latest Posts'),
698 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'post'])),
699 'sel' => $post_active,
700 'title' => DI::l10n()->t('Sort by post received date'),
701 'id' => 'post-order-tab',
707 'label' => DI::l10n()->t('Personal'),
708 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['conv' => true])),
709 'sel' => $conv_active,
710 'title' => DI::l10n()->t('Posts that mention or involve you'),
711 'id' => 'personal-tab',
716 'label' => DI::l10n()->t('Starred'),
717 'url' => $cmd . '?' . http_build_query(array_merge($def_param, ['star' => true])),
718 'sel' => $starred_active,
719 'title' => DI::l10n()->t('Favourite Posts'),
720 'id' => 'starred-posts-tab',
724 // save selected tab, but only if not in file mode
725 if (empty($_GET['file'])) {
726 DI::pConfig()->set(local_user(), 'network.view', 'tab.selected', [
727 $all_active, $post_active, $conv_active, $starred_active
731 $arr = ['tabs' => $tabs];
732 Hook::callAll('network_tabs', $arr);
734 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
736 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
738 // --- end item filter tabs