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