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