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