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