]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Community.php
Implement correct behavior for min_id in boundary pagination
[friendica.git] / src / Module / Conversation / Community.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  * See update_profile.php for documentation
21  */
22
23 namespace Friendica\Module\Conversation;
24
25 use Friendica\BaseModule;
26 use Friendica\Content\BoundariesPager;
27 use Friendica\Content\Feature;
28 use Friendica\Content\Nav;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Content\Widget;
31 use Friendica\Content\Widget\TrendingTags;
32 use Friendica\Core\ACL;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\Session;
35 use Friendica\Database\DBA;
36 use Friendica\DI;
37 use Friendica\Model\Item;
38 use Friendica\Model\User;
39 use Friendica\Network\HTTPException;
40
41 class Community extends BaseModule
42 {
43         protected static $page_style;
44         protected static $content;
45         protected static $accounttype;
46         protected static $itemsPerPage;
47         protected static $min_id;
48         protected static $max_id;
49         protected static $item_id;
50
51         public static function content(array $parameters = [])
52         {
53                 self::parseRequest($parameters);
54
55                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
56                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
57                         $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
58                 } else {
59                         $o = '';
60                 }
61
62                 if (empty($_GET['mode']) || ($_GET['mode'] != 'raw')) {
63                         $tabs = [];
64
65                         if ((Session::isAuthenticated() || in_array(self::$page_style, [CP_USERS_AND_GLOBAL, CP_USERS_ON_SERVER])) && empty(DI::config()->get('system', 'singleuser'))) {
66                                 $tabs[] = [
67                                         'label' => DI::l10n()->t('Local Community'),
68                                         'url' => 'community/local',
69                                         'sel' => self::$content == 'local' ? 'active' : '',
70                                         'title' => DI::l10n()->t('Posts from local users on this server'),
71                                         'id' => 'community-local-tab',
72                                         'accesskey' => 'l'
73                                 ];
74                         }
75         
76                         if (Session::isAuthenticated() || in_array(self::$page_style, [CP_USERS_AND_GLOBAL, CP_GLOBAL_COMMUNITY])) {
77                                 $tabs[] = [
78                                         'label' => DI::l10n()->t('Global Community'),
79                                         'url' => 'community/global',
80                                         'sel' => self::$content == 'global' ? 'active' : '',
81                                         'title' => DI::l10n()->t('Posts from users of the whole federated network'),
82                                         'id' => 'community-global-tab',
83                                         'accesskey' => 'g'
84                                 ];
85                         }
86
87                         $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
88                         $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
89
90                         Nav::setSelected('community');
91
92                         DI::page()['aside'] .= Widget::accounts('community/' . self::$content, $parameters['accounttype'] ?? '');
93         
94                         if (local_user() && DI::config()->get('system', 'community_no_sharer')) {
95                                 $path = self::$content;
96                                 if (!empty($parameters['accounttype'])) {
97                                         $path .= '/' . $parameters['accounttype'];
98                                 }
99                                 $query_parameters = [];
100                 
101                                 if (!empty($_GET['min_id'])) {
102                                         $query_parameters['min_id'] = $_GET['min_id'];
103                                 }
104                                 if (!empty($_GET['max_id'])) {
105                                         $query_parameters['max_id'] = $_GET['max_id'];
106                                 }
107                                 if (!empty($_GET['last_commented'])) {
108                                         $query_parameters['max_id'] = $_GET['last_commented'];
109                                 }
110                 
111                                 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
112                                 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
113                                 DI::page()['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
114                                         '$title'           => DI::l10n()->t('Own Contacts'),
115                                         '$path_all'        => $path_all,
116                                         '$path_no_sharer'  => $path_no_sharer,
117                                         '$no_sharer'       => !empty($_REQUEST['no_sharer']),
118                                         '$all'             => DI::l10n()->t('Include'),
119                                         '$no_sharer_label' => DI::l10n()->t('Hide'),
120                                 ]);
121                         }
122         
123                         if (Feature::isEnabled(local_user(), 'trending_tags')) {
124                                 DI::page()['aside'] .= TrendingTags::getHTML(self::$content);
125                         }
126
127                         // We need the editor here to be able to reshare an item.
128                         if (Session::isAuthenticated()) {
129                                 $x = [
130                                         'is_owner' => true,
131                                         'allow_location' => DI::app()->user['allow_location'],
132                                         'default_location' => DI::app()->user['default-location'],
133                                         'nickname' => DI::app()->user['nickname'],
134                                         'lockstate' => (is_array(DI::app()->user) && (strlen(DI::app()->user['allow_cid']) || strlen(DI::app()->user['allow_gid']) || strlen(DI::app()->user['deny_cid']) || strlen(DI::app()->user['deny_gid'])) ? 'lock' : 'unlock'),
135                                         'acl' => ACL::getFullSelectorHTML(DI::page(), DI::app()->user, true),
136                                         'bang' => '',
137                                         'visitor' => 'block',
138                                         'profile_uid' => local_user(),
139                                 ];
140                                 $o .= status_editor(DI::app(), $x, 0, true);
141                         }
142                 }
143
144                 $items = self::getItems();
145
146                 if (!DBA::isResult($items)) {
147                         notice(DI::l10n()->t('No results.'));
148                         return $o;
149                 }
150
151                 $o .= conversation(DI::app(), $items, 'community', false, false, 'commented', local_user());
152
153                 $pager = new BoundariesPager(
154                         DI::l10n(),
155                         DI::args()->getQueryString(),
156                         $items[0]['commented'],
157                         $items[count($items) - 1]['commented'],
158                         self::$itemsPerPage
159                 );
160
161                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
162                         $o .= HTML::scrollLoader();
163                 } else {
164                         $o .= $pager->renderMinimal(count($items));
165                 }
166
167                 $t = Renderer::getMarkupTemplate("community.tpl");
168                 return Renderer::replaceMacros($t, [
169                         '$content' => $o,
170                         '$header' => '',
171                         '$show_global_community_hint' => (self::$content == 'global') && DI::config()->get('system', 'show_global_community_hint'),
172                         '$global_community_hint' => DI::l10n()->t("This community stream shows all public posts received by this node. They may not reflect the opinions of this node’s users.")
173                 ]);
174         }
175
176         /**
177          * Computes module parameters from the request and local configuration
178          *
179          * @param array $parameters
180          * @throws HTTPException\BadRequestException
181          * @throws HTTPException\ForbiddenException
182          */
183         protected static function parseRequest(array $parameters)
184         {
185                 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
186                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Public access denied.'));
187                 }
188
189                 self::$page_style = DI::config()->get('system', 'community_page_style');
190
191                 if (self::$page_style == CP_NO_INTERNAL_COMMUNITY) {
192                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Access denied.'));
193                 }
194
195                 self::$accounttype = User::getAccountTypeByString($parameters['accounttype'] ?? '');
196
197                 self::$content = $parameters['content'] ?? '';
198                 if (!self::$content) {
199                         if (!empty(DI::config()->get('system', 'singleuser'))) {
200                                 // On single user systems only the global page does make sense
201                                 self::$content = 'global';
202                         } else {
203                                 // When only the global community is allowed, we use this as default
204                                 self::$content = self::$page_style == CP_GLOBAL_COMMUNITY ? 'global' : 'local';
205                         }
206                 }
207
208                 if (!in_array(self::$content, ['local', 'global'])) {
209                         throw new HTTPException\BadRequestException(DI::l10n()->t('Community option not available.'));
210                 }
211
212                 // Check if we are allowed to display the content to visitors
213                 if (!Session::isAuthenticated()) {
214                         $available = self::$page_style == CP_USERS_AND_GLOBAL;
215
216                         if (!$available) {
217                                 $available = (self::$page_style == CP_USERS_ON_SERVER) && (self::$content == 'local');
218                         }
219
220                         if (!$available) {
221                                 $available = (self::$page_style == CP_GLOBAL_COMMUNITY) && (self::$content == 'global');
222                         }
223
224                         if (!$available) {
225                                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Not available.'));
226                         }
227                 }
228
229                 if (DI::mode()->isMobile()) {
230                         self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
231                                 DI::config()->get('system', 'itemspage_network_mobile'));
232                 } else {
233                         self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
234                                 DI::config()->get('system', 'itemspage_network'));
235                 }
236
237                 // now that we have the user settings, see if the theme forces
238                 // a maximum item number which is lower then the user choice
239                 if ((DI::app()->force_max_items > 0) && (DI::app()->force_max_items < self::$itemsPerPage)) {
240                         self::$itemsPerPage = DI::app()->force_max_items;
241                 }
242
243                 if (!empty($_GET['item'])) {
244                         $item = Item::selectFirst(['parent'], ['id' => $_GET['item']]);
245                         self::$item_id = $item['parent'] ?? 0;
246                 } else {
247                         self::$item_id = 0;
248                 }
249
250                 self::$min_id = $_GET['min_id'] ?? null;
251                 self::$max_id   = $_GET['max_id']   ?? null;
252                 self::$max_id   = $_GET['last_commented'] ?? self::$max_id;
253         }
254
255         /**
256          * Computes the displayed items.
257          *
258          * Community pages have a restriction on how many successive posts by the same author can show on any given page,
259          * so we may have to retrieve more content beyond the first query
260          *
261          * @return array
262          * @throws \Exception
263          */
264         protected static function getItems()
265         {
266                 $items = self::selectItems(self::$min_id, self::$max_id, self::$item_id, self::$itemsPerPage);
267
268                 $maxpostperauthor = (int) DI::config()->get('system', 'max_author_posts_community_page');
269                 if ($maxpostperauthor != 0 && self::$content == 'local') {
270                         $count = 1;
271                         $previousauthor = '';
272                         $numposts = 0;
273                         $selected_items = [];
274
275                         while (count($selected_items) < self::$itemsPerPage && ++$count < 50 && count($items) > 0) {
276                                 foreach ($items as $item) {
277                                         if ($previousauthor == $item["author-link"]) {
278                                                 ++$numposts;
279                                         } else {
280                                                 $numposts = 0;
281                                         }
282                                         $previousauthor = $item["author-link"];
283
284                                         if (($numposts < $maxpostperauthor) && (count($selected_items) < self::$itemsPerPage)) {
285                                                 $selected_items[] = $item;
286                                         }
287                                 }
288
289                                 // If we're looking at a "previous page", the lookup continues forward in time because the list is
290                                 // sorted in chronologically decreasing order
291                                 if (isset(self::$min_id)) {
292                                         self::$min_id = $items[0]['commented'];
293                                 } else {
294                                         // In any other case, the lookup continues backwards in time
295                                         self::$max_id = $items[count($items) - 1]['commented'];
296                                 }
297
298                                 $items = self::selectItems(self::$min_id, self::$max_id, self::$item_id, self::$itemsPerPage);
299                         }
300                 } else {
301                         $selected_items = $items;
302                 }
303
304                 return $selected_items;
305         }
306
307         /**
308          * Database query for the comunity page
309          *
310          * @param $min_id
311          * @param $max_id
312          * @param $itemspage
313          * @return array
314          * @throws \Exception
315          * @TODO Move to repository/factory
316          */
317         private static function selectItems($min_id, $max_id, $item_id, $itemspage)
318         {
319                 if (self::$content == 'local') {
320                         if (!is_null(self::$accounttype)) {
321                                 $condition = ["`wall` AND `origin` AND `private` = ? AND `owner`.`contact-type` = ?", Item::PUBLIC, self::$accounttype];
322                         } else {
323                                 $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
324                         }
325                 } elseif (self::$content == 'global') {
326                         if (!is_null(self::$accounttype)) {
327                                 $condition = ["`uid` = ? AND `private` = ? AND `owner`.`contact-type` = ?", 0, Item::PUBLIC, self::$accounttype];
328                         } else {
329                                 $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
330                         }
331                 } else {
332                         return [];
333                 }
334
335                 $params = ['order' => ['commented' => true], 'limit' => $itemspage];
336
337                 if (!empty($item_id)) {
338                         $condition[0] .= " AND `iid` = ?";
339                         $condition[] = $item_id;
340                 } else {
341                         if (local_user() && !empty($_REQUEST['no_sharer'])) {
342                                 $condition[0] .= " AND NOT EXISTS (SELECT `uri-id` FROM `thread` AS t1 WHERE `t1`.`uri-id` = `thread`.`uri-id` AND `t1`.`uid` = ?)";
343                                 $condition[] = local_user();
344                         }
345         
346                         if (isset($max_id)) {
347                                 $condition[0] .= " AND `commented` < ?";
348                                 $condition[] = $max_id;
349                         }
350
351                         if (isset($min_id)) {
352                                 $condition[0] .= " AND `commented` > ?";
353                                 $condition[] = $min_id;
354
355                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
356                                 if (!isset($max_id)) {
357                                         $params['order']['commented'] = false;
358                                 }
359                         }
360                 }
361
362                 $r = Item::selectThreadForUser(0, ['uri', 'commented', 'author-link'], $condition, $params);
363
364                 $items = DBA::toArray($r);
365
366                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
367                 if (empty($item_id) && isset($min_id) && !isset($max_id)) {
368                         $items = array_reverse($items);
369                 }
370
371                 return $items;
372         }
373 }