3 * @copyright Copyright (C) 2010-2022, the Friendica project
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/>.
22 namespace Friendica\Module\Conversation;
24 use Friendica\BaseModule;
25 use Friendica\Content\BoundariesPager;
26 use Friendica\Content\ForumManager;
27 use Friendica\Content\Nav;
28 use Friendica\Content\Widget;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\ACL;
31 use Friendica\Core\Hook;
32 use Friendica\Core\Renderer;
33 use Friendica\Core\Session;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Group;
38 use Friendica\Model\Item;
39 use Friendica\Model\Post;
40 use Friendica\Model\Profile;
41 use Friendica\Model\User;
42 use Friendica\Model\Verb;
43 use Friendica\Module\Contact as ModuleContact;
44 use Friendica\Module\Security\Login;
45 use Friendica\Protocol\Activity;
46 use Friendica\Util\DateTimeFormat;
48 class Network extends BaseModule
51 private static $groupId;
53 private static $forumContactId;
55 private static $selectedTab;
57 private static $min_id;
59 private static $max_id;
61 private static $accountTypeString;
63 private static $accountType;
65 private static $network;
67 private static $itemsPerPage;
69 private static $dateFrom;
71 private static $dateTo;
75 private static $mention;
77 protected static $order;
79 protected function content(array $request = []): string
85 $this->parseRequest($_GET);
89 DI::page()['aside'] .= Widget::accounttypes($module, self::$accountTypeString);
90 DI::page()['aside'] .= Group::sidebarWidget($module, $module . '/group', 'standard', self::$groupId);
91 DI::page()['aside'] .= ForumManager::widget($module . '/forum', local_user(), self::$forumContactId);
92 DI::page()['aside'] .= Widget::postedByYear($module . '/archive', local_user(), false);
93 DI::page()['aside'] .= Widget::networks($module, !self::$forumContactId ? self::$network : '');
94 DI::page()['aside'] .= Widget\SavedSearches::getHTML(DI::args()->getQueryString());
95 DI::page()['aside'] .= Widget::fileAs('filed', null);
97 $arr = ['query' => DI::args()->getQueryString()];
98 Hook::callAll('network_content_init', $arr);
102 // Fetch a page full of parent items for this page
103 $params = ['limit' => self::$itemsPerPage];
104 $table = 'network-thread-view';
106 $items = self::getItems($table, $params);
108 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
109 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
110 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
113 if (!(isset($_GET['mode']) AND ($_GET['mode'] == 'raw'))) {
114 $o .= self::getTabsHTML(self::$selectedTab);
116 Nav::setSelected(DI::args()->get(0));
120 if (self::$forumContactId) {
121 // If self::$forumContactId belongs to a communitity forum or a privat goup,.add a mention to the status editor
122 $condition = ["`id` = ? AND `contact-type` = ?", self::$forumContactId, Contact::TYPE_COMMUNITY];
123 $contact = DBA::selectFirst('contact', ['addr'], $condition);
124 if (!empty($contact['addr'])) {
125 $content = '!' . $contact['addr'];
131 $default_permissions = [];
132 if (self::$groupId) {
133 $default_permissions['allow_gid'] = [self::$groupId];
137 if (self::$forumContactId) {
138 $allowedCids[] = (int) self::$forumContactId;
139 } elseif (self::$network) {
141 'uid' => local_user(),
142 'network' => self::$network,
147 'rel' => [Contact::SHARING, Contact::FRIEND],
149 $contactStmt = DBA::select('contact', ['id'], $condition);
150 while ($contact = DBA::fetch($contactStmt)) {
151 $allowedCids[] = (int) $contact['id'];
153 DBA::close($contactStmt);
156 if (count($allowedCids)) {
157 $default_permissions['allow_cid'] = $allowedCids;
161 'lockstate' => self::$groupId || self::$forumContactId || self::$network || ACL::getLockstateForUserId($a->getLoggedInUserId()) ? 'lock' : 'unlock',
162 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), true, $default_permissions),
163 'bang' => ((self::$groupId || self::$forumContactId || self::$network) ? '!' : ''),
164 'content' => $content,
167 $o .= DI::conversation()->statusEditor($x);
170 if (self::$groupId) {
171 $group = DBA::selectFirst('group', ['name'], ['id' => self::$groupId, 'uid' => local_user()]);
172 if (!DBA::isResult($group)) {
173 notice(DI::l10n()->t('No such group'));
176 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
177 '$title' => DI::l10n()->t('Group: %s', $group['name'])
179 } elseif (self::$forumContactId) {
180 $contact = Contact::getById(self::$forumContactId);
181 if (DBA::isResult($contact)) {
182 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
183 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
184 'id' => DI::args()->get(0),
187 notice(DI::l10n()->t('Invalid contact.'));
189 } elseif (!DI::config()->get('theme', 'hide_eventlist')) {
190 $o .= Profile::getBirthdays();
191 $o .= Profile::getEventsReminderHTML();
194 if (self::$order === 'received') {
195 $ordering = '`received`';
197 $ordering = '`commented`';
200 $o .= DI::conversation()->create($items, 'network', false, false, $ordering, local_user());
202 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
203 $o .= HTML::scrollLoader();
205 $pager = new BoundariesPager(
207 DI::args()->getQueryString(),
208 $items[0][self::$order] ?? null,
209 $items[count($items) - 1][self::$order] ?? null,
213 $o .= $pager->renderMinimal(count($items));
222 * @param array $condition The array with the SQL condition
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225 private static function setItemsSeenByCondition(array $condition)
227 if (empty($condition)) {
231 $unseen = Post::exists($condition);
234 /// @todo handle huge "unseen" updates in the background to avoid timeout errors
235 Item::update(['unseen' => false], $condition);
240 * Get the network tabs menu
242 * @param string $selectedTab
243 * @return string Html of the network tabs
244 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
246 private static function getTabsHTML(string $selectedTab)
248 $cmd = DI::args()->getCommand();
253 'label' => DI::l10n()->t('Latest Activity'),
254 'url' => $cmd . '?' . http_build_query(['order' => 'commented']),
255 'sel' => !$selectedTab || $selectedTab == 'commented' ? 'active' : '',
256 'title' => DI::l10n()->t('Sort by latest activity'),
257 'id' => 'activity-order-tab',
261 'label' => DI::l10n()->t('Latest Posts'),
262 'url' => $cmd . '?' . http_build_query(['order' => 'received']),
263 'sel' => $selectedTab == 'received' ? 'active' : '',
264 'title' => DI::l10n()->t('Sort by post received date'),
265 'id' => 'post-order-tab',
269 'label' => DI::l10n()->t('Personal'),
270 'url' => $cmd . '?' . http_build_query(['mention' => true]),
271 'sel' => $selectedTab == 'mention' ? 'active' : '',
272 'title' => DI::l10n()->t('Posts that mention or involve you'),
273 'id' => 'personal-tab',
277 'label' => DI::l10n()->t('Starred'),
278 'url' => $cmd . '?' . http_build_query(['star' => true]),
279 'sel' => $selectedTab == 'star' ? 'active' : '',
280 'title' => DI::l10n()->t('Favourite Posts'),
281 'id' => 'starred-posts-tab',
286 $arr = ['tabs' => $tabs];
287 Hook::callAll('network_tabs', $arr);
289 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
291 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
294 protected function parseRequest(array $get)
296 self::$groupId = $this->parameters['group_id'] ?? 0;
298 self::$forumContactId = $this->parameters['contact_id'] ?? 0;
300 self::$selectedTab = Session::get('network-tab', DI::pConfig()->get(local_user(), 'network.view', 'selected_tab', ''));
302 self::$order = 'commented';
304 if (!empty($get['star'])) {
305 self::$selectedTab = 'star';
308 self::$star = self::$selectedTab == 'star';
311 if (!empty($get['mention'])) {
312 self::$selectedTab = 'mention';
313 self::$mention = true;
315 self::$mention = self::$selectedTab == 'mention';
318 if (!empty($get['order'])) {
319 self::$selectedTab = $get['order'];
320 self::$order = $get['order'];
322 self::$mention = false;
323 } elseif (in_array(self::$selectedTab, ['received', 'star', 'mention'])) {
324 self::$order = 'received';
327 self::$selectedTab = self::$selectedTab ?? self::$order;
329 // Prohibit combined usage of "star" and "mention"
330 if (self::$selectedTab == 'star') {
331 self::$mention = false;
332 } elseif (self::$selectedTab == 'mention') {
336 Session::set('network-tab', self::$selectedTab);
337 DI::pConfig()->set(local_user(), 'network.view', 'selected_tab', self::$selectedTab);
339 self::$accountTypeString = $get['accounttype'] ?? $this->parameters['accounttype'] ?? '';
340 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
342 self::$network = $get['nets'] ?? '';
344 self::$dateFrom = $this->parameters['from'] ?? '';
345 self::$dateTo = $this->parameters['to'] ?? '';
347 if (DI::mode()->isMobile()) {
348 self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
349 DI::config()->get('system', 'itemspage_network_mobile'));
351 self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
352 DI::config()->get('system', 'itemspage_network'));
355 self::$min_id = $get['min_id'] ?? null;
356 self::$max_id = $get['max_id'] ?? null;
358 switch (self::$order) {
360 self::$max_id = $get['last_received'] ?? self::$max_id;
363 self::$max_id = $get['last_created'] ?? self::$max_id;
366 self::$max_id = $get['last_uriid'] ?? self::$max_id;
369 self::$order = 'commented';
370 self::$max_id = $get['last_commented'] ?? self::$max_id;
374 protected static function getItems(string $table, array $params, array $conditionFields = [])
376 $conditionFields['uid'] = local_user();
377 $conditionStrings = [];
379 if (!is_null(self::$accountType)) {
380 $conditionFields['contact-type'] = self::$accountType;
384 $conditionFields['starred'] = true;
386 if (self::$mention) {
387 $conditionFields['mention'] = true;
389 if (self::$network) {
390 $conditionFields['network'] = self::$network;
393 if (self::$dateFrom) {
394 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert(self::$dateFrom, 'UTC', DI::app()->getTimeZone())]);
397 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert(self::$dateTo, 'UTC', DI::app()->getTimeZone())]);
400 if (self::$groupId) {
401 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", self::$groupId]);
402 } elseif (self::$forumContactId) {
403 $conditionStrings = DBA::mergeConditions($conditionStrings,
404 ["((`contact-id` = ?) OR EXISTS(SELECT `uri-id` FROM `post-user-view` WHERE `post-user-view`.`parent-uri-id` = " . DBA::quoteIdentifier($table) . ".`uri-id` AND (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
405 self::$forumContactId, self::$forumContactId, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()]);
408 // Currently only the order modes "received" and "commented" are in use
409 if (isset(self::$max_id)) {
410 switch (self::$order) {
412 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", self::$max_id]);
415 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", self::$max_id]);
418 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", self::$max_id]);
421 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", self::$max_id]);
426 if (isset(self::$min_id)) {
427 switch (self::$order) {
429 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", self::$min_id]);
432 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", self::$min_id]);
435 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", self::$min_id]);
438 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", self::$min_id]);
443 if (isset(self::$min_id) && !isset(self::$max_id)) {
444 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
445 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
446 // order of the results.
447 $params['order'] = [self::$order => false];
449 $params['order'] = [self::$order => true];
452 $items = DBA::selectToArray($table, [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
454 // min_id quirk, continued
455 if (isset(self::$min_id) && !isset(self::$max_id)) {
456 $items = array_reverse($items);
459 if (DBA::isResult($items)) {
460 $parents = array_column($items, 'parent-uri-id');
465 // We aren't going to try and figure out at the item, group, and page
466 // level which items you've seen and which you haven't. If you're looking
467 // at the top level network page just mark everything seen.
468 if (!self::$groupId && !self::$forumContactId && !self::$star && !self::$mention) {
469 $condition = ['unseen' => true, 'uid' => local_user()];
470 self::setItemsSeenByCondition($condition);
471 } elseif (!empty($parents)) {
472 $condition = ['unseen' => true, 'uid' => local_user(), 'parent-uri-id' => $parents];
473 self::setItemsSeenByCondition($condition);