]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Network.php
Improve photo loading speed
[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] ?? null,
196                                 $items[count($items) - 1][self::$order] ?? null,
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                         /// @todo handle huge "unseen" updates in the background to avoid timeout errors
222                         Item::update(['unseen' => false], $condition);
223                 }
224         }
225
226         /**
227          * Get the network tabs menu
228          *
229          * @param string $selectedTab
230          * @return string Html of the network tabs
231          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232          */
233         private static function getTabsHTML(string $selectedTab)
234         {
235                 $cmd = DI::args()->getCommand();
236
237                 // tabs
238                 $tabs = [
239                         [
240                                 'label' => DI::l10n()->t('Latest Activity'),
241                                 'url'   => $cmd . '?' . http_build_query(['order' => 'commented']),
242                                 'sel'   => !$selectedTab || $selectedTab == 'commented' ? 'active' : '',
243                                 'title' => DI::l10n()->t('Sort by latest activity'),
244                                 'id'    => 'activity-order-tab',
245                                 'accesskey' => 'e',
246                         ],
247                         [
248                                 'label' => DI::l10n()->t('Latest Posts'),
249                                 'url'   => $cmd . '?' . http_build_query(['order' => 'received']),
250                                 'sel'   => $selectedTab == 'received' ? 'active' : '',
251                                 'title' => DI::l10n()->t('Sort by post received date'),
252                                 'id'    => 'post-order-tab',
253                                 'accesskey' => 't',
254                         ],
255                         [
256                                 'label' => DI::l10n()->t('Personal'),
257                                 'url'   => $cmd . '?' . http_build_query(['mention' => true]),
258                                 'sel'   => $selectedTab == 'mention' ? 'active' : '',
259                                 'title' => DI::l10n()->t('Posts that mention or involve you'),
260                                 'id'    => 'personal-tab',
261                                 'accesskey' => 'r',
262                         ],
263                         [
264                                 'label' => DI::l10n()->t('Starred'),
265                                 'url'   => $cmd . '?' . http_build_query(['star' => true]),
266                                 'sel'   => $selectedTab == 'star' ? 'active' : '',
267                                 'title' => DI::l10n()->t('Favourite Posts'),
268                                 'id'    => 'starred-posts-tab',
269                                 'accesskey' => 'm',
270                         ],
271                 ];
272
273                 $arr = ['tabs' => $tabs];
274                 Hook::callAll('network_tabs', $arr);
275
276                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
277
278                 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
279         }
280
281         protected static function parseRequest(array $parameters, array $get)
282         {
283                 self::$groupId = $parameters['group_id'] ?? 0;
284
285                 self::$forumContactId = $parameters['contact_id'] ?? 0;
286
287                 self::$selectedTab = Session::get('network-tab', DI::pConfig()->get(local_user(), 'network.view', 'selected_tab', ''));
288
289                 self::$order = 'commented';
290
291                 if (!empty($get['star'])) {
292                         self::$selectedTab = 'star';
293                         self::$star = true;
294                 } else {
295                         self::$star = self::$selectedTab == 'star';
296                 }
297
298                 if (!empty($get['mention'])) {
299                         self::$selectedTab = 'mention';
300                         self::$mention = true;
301                 } else {
302                         self::$mention = self::$selectedTab == 'mention';
303                 }
304
305                 if (!empty($get['order'])) {
306                         self::$selectedTab = $get['order'];
307                         self::$order = $get['order'];
308                 } elseif (in_array(self::$selectedTab, ['received', 'star', 'mention'])) {
309                         self::$order = 'received';
310                 }
311
312                 self::$selectedTab = self::$selectedTab ?? self::$order;
313
314                 Session::set('network-tab', self::$selectedTab);
315                 DI::pConfig()->set(local_user(), 'network.view', 'selected_tab', self::$selectedTab);
316
317                 self::$accountTypeString = $get['accounttype'] ?? $parameters['accounttype'] ?? '';
318                 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
319
320                 self::$network = $get['nets'] ?? '';
321
322                 self::$dateFrom = $parameters['from'] ?? '';
323                 self::$dateTo = $parameters['to'] ?? '';
324
325                 if (DI::mode()->isMobile()) {
326                         self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
327                                 DI::config()->get('system', 'itemspage_network_mobile'));
328                 } else {
329                         self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
330                                 DI::config()->get('system', 'itemspage_network'));
331                 }
332
333                 self::$min_id = $get['min_id'] ?? null;
334                 self::$max_id = $get['max_id'] ?? null;
335
336                 switch (self::$order) {
337                         case 'received':
338                                 self::$max_id = $get['last_received'] ?? self::$max_id;
339                                 break;
340                         case 'created':
341                                 self::$max_id = $get['last_created'] ?? self::$max_id;
342                                 break;
343                         case 'uriid':
344                                 self::$max_id = $get['last_uriid'] ?? self::$max_id;
345                                 break;
346                         default:
347                                 self::$order = 'commented';
348                                 self::$max_id = $get['last_commented'] ?? self::$max_id;
349                 }
350         }
351
352         protected static function getItems(string $table, array $params, array $conditionFields = [])
353         {
354                 $conditionFields['uid'] = local_user();
355                 $conditionStrings = [];
356
357                 if (!is_null(self::$accountType)) {
358                         $conditionFields['contact-type'] = self::$accountType;
359                 }
360
361                 if (self::$star) {
362                         $conditionFields['starred'] = true;
363                 }
364                 if (self::$mention) {
365                         $conditionFields['mention'] = true;
366                 }
367                 if (self::$network) {
368                         $conditionFields['network'] = self::$network;
369                 }
370
371                 if (self::$dateFrom) {
372                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert(self::$dateFrom, 'UTC', date_default_timezone_get())]);
373                 }
374                 if (self::$dateTo) {
375                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert(self::$dateTo, 'UTC', date_default_timezone_get())]);
376                 }
377
378                 if (self::$groupId) {
379                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", self::$groupId]);
380                 } elseif (self::$forumContactId) {
381                         $conditionFields['contact-id'] = self::$forumContactId;
382                 }
383
384                 // Currently only the order modes "received" and "commented" are in use
385                 if (isset(self::$max_id)) {
386                         switch (self::$order) {
387                                 case 'received':
388                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", self::$max_id]);
389                                         break;
390                                 case 'commented':
391                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", self::$max_id]);
392                                         break;
393                                 case 'created':
394                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", self::$max_id]);
395                                         break;
396                                 case 'uriid':
397                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", self::$max_id]);
398                                         break;
399                         }
400                 }
401
402                 if (isset(self::$min_id)) {
403                         switch (self::$order) {
404                                 case 'received':
405                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", self::$min_id]);
406                                         break;
407                                 case 'commented':
408                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", self::$min_id]);
409                                         break;
410                                 case 'created':
411                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", self::$min_id]);
412                                         break;
413                                 case 'uriid':
414                                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", self::$min_id]);
415                                         break;
416                         }
417                 }
418
419                 if (isset(self::$min_id) && !isset(self::$max_id)) {
420                         // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
421                         // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
422                         // order of the results.
423                         $params['order'] = [self::$order => false];
424                 } else {
425                         $params['order'] = [self::$order => true];
426                 }
427
428                 $items = DBA::selectToArray($table, [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
429
430                 // min_id quirk, continued
431                 if (isset(self::$min_id) && !isset(self::$max_id)) {
432                         $items = array_reverse($items);
433                 }
434
435                 if (DBA::isResult($items)) {
436                         $parents = array_column($items, 'parent');
437                 } else {
438                         $parents = [];
439                 }
440
441                 // We aren't going to try and figure out at the item, group, and page
442                 // level which items you've seen and which you haven't. If you're looking
443                 // at the top level network page just mark everything seen.
444                 if (!self::$groupId && !self::$forumContactId && !self::$star && !self::$mention) {
445                         $condition = ['unseen' => true, 'uid' => local_user()];
446                         self::setItemsSeenByCondition($condition);
447                 } elseif (!empty($parents)) {
448                         $condition = ['unseen' => true, 'uid' => local_user(), 'parent' => $parents];
449                         self::setItemsSeenByCondition($condition);
450                 }
451
452                 return $items;
453         }
454 }