]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Network.php
Merge pull request #9460 from annando/issue-9457
[friendica.git] / src / Module / Conversation / Network.php
1 <?php
2
3 namespace Friendica\Module\Conversation;
4
5 use Friendica\BaseModule;
6 use Friendica\Content\BoundariesPager;
7 use Friendica\Content\ForumManager;
8 use Friendica\Content\Nav;
9 use Friendica\Content\Widget;
10 use Friendica\Content\Text\HTML;
11 use Friendica\Core\ACL;
12 use Friendica\Core\Hook;
13 use Friendica\Core\Renderer;
14 use Friendica\Core\Session;
15 use Friendica\Database\DBA;
16 use Friendica\DI;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Group;
19 use Friendica\Model\Item;
20 use Friendica\Model\Profile;
21 use Friendica\Model\User;
22 use Friendica\Module\Contact as ModuleContact;
23 use Friendica\Module\Security\Login;
24 use Friendica\Util\DateTimeFormat;
25
26 class Network extends BaseModule
27 {
28         /** @var int */
29         private static $groupId;
30         /** @var int */
31         private static $forumContactId;
32         /** @var string */
33         private static $selectedTab;
34         /** @var mixed */
35         private static $min_id;
36         /** @var mixed */
37         private static $max_id;
38         /** @var string */
39         private static $accountTypeString;
40         /** @var int */
41         private static $accountType;
42         /** @var string */
43         private static $network;
44         /** @var int */
45         private static $itemsPerPage;
46         /** @var string */
47         private static $dateFrom;
48         /** @var string */
49         private static $dateTo;
50         /** @var int */
51         private static $star;
52         /** @var int */
53         private static $mention;
54         /** @var string */
55         protected static $order;
56
57         public static function content(array $parameters = [])
58         {
59                 if (!local_user()) {
60                         return Login::form();
61                 }
62
63                 self::parseRequest($parameters, $_GET);
64
65                 $module = 'network';
66
67                 DI::page()['aside'] .= Widget::accounttypes($module, self::$accountTypeString);
68                 DI::page()['aside'] .= Group::sidebarWidget($module, $module . '/group', 'standard', self::$groupId);
69                 DI::page()['aside'] .= ForumManager::widget($module . '/forum', local_user(), self::$forumContactId);
70                 DI::page()['aside'] .= Widget::postedByYear($module . '/archive', local_user(), false);
71                 DI::page()['aside'] .= Widget::networks($module, !self::$forumContactId ? self::$network : '');
72                 DI::page()['aside'] .= Widget\SavedSearches::getHTML(DI::args()->getQueryString());
73                 DI::page()['aside'] .= Widget::fileAs('filed', null);
74
75                 $arr = ['query' => DI::args()->getQueryString()];
76                 Hook::callAll('network_content_init', $arr);
77
78                 $o = '';
79
80                 // Fetch a page full of parent items for this page
81                 $params = ['limit' => self::$itemsPerPage];
82                 $table = 'network-thread-view';
83
84                 $items = self::getItems($table, $params);
85
86                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
87                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
88                         $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
89                 }
90
91                 if (!(isset($_GET['mode']) AND ($_GET['mode'] == 'raw'))) {
92                         $o .= self::getTabsHTML(self::$selectedTab);
93
94                         Nav::setSelected(DI::args()->get(0));
95
96                         $content = '';
97
98                         if (self::$forumContactId) {
99                                 // If self::$forumContactId belongs to a communitity forum or a privat goup,.add a mention to the status editor
100                                 $condition = ["`id` = ? AND (`forum` OR `prv`)", self::$forumContactId];
101                                 $contact = DBA::selectFirst('contact', ['addr'], $condition);
102                                 if (!empty($contact['addr'])) {
103                                         $content = '!' . $contact['addr'];
104                                 }
105                         }
106
107                         $a = DI::app();
108
109                         $default_permissions = [];
110                         if (self::$groupId) {
111                                 $default_permissions['allow_gid'] = [self::$groupId];
112                         }
113
114                         $allowedCids = [];
115                         if (self::$forumContactId) {
116                                 $allowedCids[] = (int) self::$forumContactId;
117                         } elseif (self::$network) {
118                                 $condition = [
119                                         'uid'     => local_user(),
120                                         'network' => self::$network,
121                                         'self'    => false,
122                                         'blocked' => false,
123                                         'pending' => false,
124                                         'archive' => false,
125                                         'rel'     => [Contact::SHARING, Contact::FRIEND],
126                                 ];
127                                 $contactStmt = DBA::select('contact', ['id'], $condition);
128                                 while ($contact = DBA::fetch($contactStmt)) {
129                                         $allowedCids[] = (int) $contact['id'];
130                                 }
131                                 DBA::close($contactStmt);
132                         }
133
134                         if (count($allowedCids)) {
135                                 $default_permissions['allow_cid'] = $allowedCids;
136                         }
137
138                         $x = [
139                                 'is_owner' => true,
140                                 'allow_location' => $a->user['allow_location'],
141                                 'default_location' => $a->user['default-location'],
142                                 'nickname' => $a->user['nickname'],
143                                 'lockstate' => (self::$groupId || self::$forumContactId || self::$network || (is_array($a->user) &&
144                                         (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
145                                                 strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
146                                 'default_perms' => ACL::getDefaultUserPermissions($a->user),
147                                 'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true, $default_permissions),
148                                 'bang' => ((self::$groupId || self::$forumContactId || self::$network) ? '!' : ''),
149                                 'visitor' => 'block',
150                                 'profile_uid' => local_user(),
151                                 'content' => $content,
152                         ];
153
154                         $o .= status_editor($a, $x);
155                 }
156
157                 if (self::$groupId) {
158                         $group = DBA::selectFirst('group', ['name'], ['id' => self::$groupId, 'uid' => local_user()]);
159                         if (!DBA::isResult($group)) {
160                                 notice(DI::l10n()->t('No such group'));
161                         }
162
163                         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
164                                 '$title' => DI::l10n()->t('Group: %s', $group['name'])
165                         ]) . $o;
166                 } elseif (self::$forumContactId) {
167                         $contact = Contact::getById(self::$forumContactId);
168                         if (DBA::isResult($contact)) {
169                                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
170                                         'contacts' => [ModuleContact::getContactTemplateVars($contact)],
171                                         'id' => DI::args()->get(0),
172                                 ]) . $o;
173                         } else {
174                                 notice(DI::l10n()->t('Invalid contact.'));
175                         }
176                 } elseif (!DI::config()->get('theme', 'hide_eventlist')) {
177                         $o .= Profile::getBirthdays();
178                         $o .= Profile::getEventsReminderHTML();
179                 }
180
181                 if (self::$order === 'received') {
182                         $ordering = '`received`';
183                 } else {
184                         $ordering = '`commented`';
185                 }
186
187                 $o .= conversation(DI::app(), $items, 'network', false, false, $ordering, local_user());
188
189                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
190                         $o .= HTML::scrollLoader();
191                 } else {
192                         $pager = new BoundariesPager(
193                                 DI::l10n(),
194                                 DI::args()->getQueryString(),
195                                 $items[0][self::$order],
196                                 $items[count($items) - 1][self::$order],
197                                 self::$itemsPerPage
198                         );
199
200                         $o .= $pager->renderMinimal(count($items));
201                 }
202
203                 return $o;
204         }
205
206         /**
207          * Sets items as seen
208          *
209          * @param array $condition The array with the SQL condition
210          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
211          */
212         private static function setItemsSeenByCondition(array $condition)
213         {
214                 if (empty($condition)) {
215                         return;
216                 }
217
218                 $unseen = Item::exists($condition);
219
220                 if ($unseen) {
221                         Item::update(['unseen' => false], $condition);
222                 }
223         }
224
225         /**
226          * Get the network tabs menu
227          *
228          * @param string $selectedTab
229          * @return string Html of the network tabs
230          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231          */
232         private static function getTabsHTML(string $selectedTab)
233         {
234                 $cmd = DI::args()->getCommand();
235
236                 // tabs
237                 $tabs = [
238                         [
239                                 'label' => DI::l10n()->t('Latest Activity'),
240                                 'url'   => $cmd . '?' . http_build_query(['order' => 'commented']),
241                                 'sel'   => !$selectedTab || $selectedTab == 'commented' ? 'active' : '',
242                                 'title' => DI::l10n()->t('Sort by latest activity'),
243                                 'id'    => 'activity-order-tab',
244                                 'accesskey' => 'e',
245                         ],
246                         [
247                                 'label' => DI::l10n()->t('Latest Posts'),
248                                 'url'   => $cmd . '?' . http_build_query(['order' => 'received']),
249                                 'sel'   => $selectedTab == 'received' ? 'active' : '',
250                                 'title' => DI::l10n()->t('Sort by post received date'),
251                                 'id'    => 'post-order-tab',
252                                 'accesskey' => 't',
253                         ],
254                         [
255                                 'label' => DI::l10n()->t('Personal'),
256                                 'url'   => $cmd . '?' . http_build_query(['mention' => true]),
257                                 'sel'   => $selectedTab == 'mention' ? 'active' : '',
258                                 'title' => DI::l10n()->t('Posts that mention or involve you'),
259                                 'id'    => 'personal-tab',
260                                 'accesskey' => 'r',
261                         ],
262                         [
263                                 'label' => DI::l10n()->t('Starred'),
264                                 'url'   => $cmd . '?' . http_build_query(['star' => true]),
265                                 'sel'   => $selectedTab == 'star' ? 'active' : '',
266                                 'title' => DI::l10n()->t('Favourite Posts'),
267                                 'id'    => 'starred-posts-tab',
268                                 'accesskey' => 'm',
269                         ],
270                 ];
271
272                 $arr = ['tabs' => $tabs];
273                 Hook::callAll('network_tabs', $arr);
274
275                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
276
277                 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
278         }
279
280         protected static function parseRequest(array $parameters, array $get)
281         {
282                 self::$groupId = $parameters['group_id'] ?? 0;
283
284                 self::$forumContactId = $parameters['contact_id'] ?? 0;
285
286                 self::$selectedTab = Session::get('network-tab', DI::pConfig()->get(local_user(), 'network.view', 'selected_tab', ''));
287
288                 self::$order = 'commented';
289
290                 if (!empty($get['star'])) {
291                         self::$selectedTab = 'star';
292                         self::$order = 'received';
293                 }
294
295                 if (!empty($get['mention'])) {
296                         self::$selectedTab = 'mention';
297                         self::$order = 'received';
298                 }
299
300                 if (!empty($get['order'])) {
301                         self::$selectedTab = $get['order'];
302                         self::$order = $get['order'];
303                 }
304
305                 self::$star    = intval($get['star'] ?? 0);
306                 self::$mention = intval($get['mention'] ?? 0);
307
308                 self::$selectedTab = self::$selectedTab ?? self::$order;
309
310                 Session::set('network-tab', self::$selectedTab);
311                 DI::pConfig()->set(local_user(), 'network.view', 'selected_tab', self::$selectedTab);
312
313                 self::$accountTypeString = $get['accounttype'] ?? $parameters['accounttype'] ?? '';
314                 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
315
316                 self::$network = $get['nets'] ?? '';
317
318                 self::$dateFrom = $parameters['from'] ?? '';
319                 self::$dateTo = $parameters['to'] ?? '';
320
321                 if (DI::mode()->isMobile()) {
322                         self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
323                                 DI::config()->get('system', 'itemspage_network_mobile'));
324                 } else {
325                         self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
326                                 DI::config()->get('system', 'itemspage_network'));
327                 }
328
329                 self::$min_id = $get['min_id'] ?? null;
330                 self::$max_id = $get['max_id'] ?? null;
331
332                 switch (self::$order) {
333                         case 'received':
334                                 self::$max_id = $get['last_received'] ?? self::$max_id;
335                                 break;
336                         case 'created':
337                                 self::$max_id = $get['last_created'] ?? self::$max_id;
338                                 break;
339                         case 'uriid':
340                                 self::$max_id = $get['last_uriid'] ?? self::$max_id;
341                                 break;
342                         default:
343                                 self::$order = 'commented';
344                                 self::$max_id = $get['last_commented'] ?? self::$max_id;
345                 }
346         }
347
348         protected static function getItems(string $table, array $params, array $conditionFields = [])
349         {
350                 $conditionFields['uid'] = local_user();
351                 $conditionStrings = [];
352
353                 if (!is_null(self::$accountType)) {
354                         $conditionFields['contact-type'] = self::$accountType;
355                 }
356
357                 if (self::$star) {
358                         $conditionFields['starred'] = true;
359                 }
360                 if (self::$mention) {
361                         $conditionFields['mention'] = true;
362                 }
363                 if (self::$network) {
364                         $conditionFields['network'] = self::$network;
365                 }
366
367                 if (self::$dateFrom) {
368                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert(self::$dateFrom, 'UTC', date_default_timezone_get())]);
369                 }
370                 if (self::$dateTo) {
371                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert(self::$dateTo, 'UTC', date_default_timezone_get())]);
372                 }
373
374                 if (self::$groupId) {
375                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", self::$groupId]);
376                 } elseif (self::$forumContactId) {
377                         $conditionFields['contact-id'] = self::$forumContactId;
378                 }
379
380                 // Currently only the order modes "received" and "commented" are in use
381                 if (isset(self::$max_id)) {
382                         switch (self::$order) {
383                                 case 'received':
384                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", self::$max_id]);
385                                         break;
386                                 case 'commented':
387                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", self::$max_id]);
388                                         break;
389                                 case 'created':
390                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", self::$max_id]);
391                                         break;
392                                 case 'uriid':
393                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", self::$max_id]);
394                                         break;
395                         }
396                 }
397
398                 if (isset(self::$min_id)) {
399                         switch (self::$order) {
400                                 case 'received':
401                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", self::$min_id]);
402                                         break;
403                                 case 'commented':
404                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", self::$min_id]);
405                                         break;
406                                 case 'created':
407                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", self::$min_id]);
408                                         break;
409                                 case 'uriid':
410                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", self::$min_id]);
411                                         break;
412                         }
413                 }
414
415                 if (isset(self::$min_id) && !isset(self::$max_id)) {
416                         // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
417                         // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
418                         // order of the results.
419                         $params['order'] = [self::$order => false];
420                 } else {
421                         $params['order'] = [self::$order => true];
422                 }
423
424                 $items = DBA::selectToArray($table, [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
425
426                 // min_id quirk, continued
427                 if (isset(self::$min_id) && !isset(self::$max_id)) {
428                         $items = array_reverse($items);
429                 }
430
431                 if (DBA::isResult($items)) {
432                         $parents = array_column($items, 'parent');
433                 } else {
434                         $parents = [];
435                 }
436
437                 // We aren't going to try and figure out at the item, group, and page
438                 // level which items you've seen and which you haven't. If you're looking
439                 // at the top level network page just mark everything seen.
440                 if (!self::$groupId && !self::$forumContactId && !self::$star && !self::$mention) {
441                         $condition = ['unseen' => true, 'uid' => local_user()];
442                         self::setItemsSeenByCondition($condition);
443                 } elseif (!empty($parents)) {
444                         $condition = ['unseen' => true, 'uid' => local_user(), 'parent' => $parents];
445                         self::setItemsSeenByCondition($condition);
446                 }
447
448                 return $items;
449         }
450 }