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