]> git.mxchange.org Git - friendica.git/blob - mod/network.php
Merge pull request #7204 from MrPetovan/bug/notices
[friendica.git] / mod / network.php
1 <?php
2
3 /**
4  * @file mod/network.php
5  */
6
7 use Friendica\App;
8 use Friendica\Content\Feature;
9 use Friendica\Content\ForumManager;
10 use Friendica\Content\Nav;
11 use Friendica\Content\Pager;
12 use Friendica\Content\Widget;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\ACL;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\Renderer;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\Term;
28 use Friendica\Module\Login;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Proxy as ProxyUtils;
31 use Friendica\Util\Strings;
32
33 function network_init(App $a)
34 {
35         if (!local_user()) {
36                 notice(L10n::t('Permission denied.') . EOL);
37                 return;
38         }
39
40         Hook::add('head', __FILE__, 'network_infinite_scroll_head');
41
42         $search = (!empty($_GET['search']) ? Strings::escapeHtml($_GET['search']) : '');
43
44         if (($search != '') && !empty($_GET['submit'])) {
45                 $a->internalRedirect('search?search=' . urlencode($search));
46         }
47
48         if (!empty($_GET['save'])) {
49                 $exists = DBA::exists('search', ['uid' => local_user(), 'term' => $search]);
50                 if (!$exists) {
51                         DBA::insert('search', ['uid' => local_user(), 'term' => $search]);
52                 }
53         }
54         if (!empty($_GET['remove'])) {
55                 DBA::delete('search', ['uid' => local_user(), 'term' => $search]);
56         }
57
58         $is_a_date_query = false;
59
60         $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
61
62         $cid = 0;
63         if (!empty($_GET['cid'])) {
64                 $cid = $_GET['cid'];
65                 $_GET['nets'] = '';
66                 $group_id = 0;
67         }
68
69         if ($a->argc > 1) {
70                 for ($x = 1; $x < $a->argc; $x ++) {
71                         if (is_a_date_arg($a->argv[$x])) {
72                                 $is_a_date_query = true;
73                                 break;
74                         }
75                 }
76         }
77
78         // convert query string to array. remove friendica args
79         $query_array = [];
80         parse_str(parse_url($a->query_string, PHP_URL_QUERY), $query_array);
81
82         // fetch last used network view and redirect if needed
83         if (!$is_a_date_query) {
84                 $sel_nets = defaults($_GET, 'nets', '');
85                 $sel_tabs = network_query_get_sel_tab($a);
86                 $sel_groups = network_query_get_sel_group($a);
87                 $last_sel_tabs = PConfig::get(local_user(), 'network.view', 'tab.selected');
88
89                 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
90
91                 $net_baseurl = '/network';
92                 $net_args = [];
93
94                 if ($sel_groups !== false) {
95                         $net_baseurl .= '/' . $sel_groups;
96                 }
97
98                 if ($remember_tab) {
99                         // redirect if current selected tab is '/network' and
100                         // last selected tab is _not_ '/network?order=comment'.
101                         // and this isn't a date query
102
103                         $tab_baseurls = [
104                                 '',     //all
105                                 '',     //postord
106                                 '',     //conv
107                                 '/new', //new
108                                 '',     //starred
109                                 '',     //bookmarked
110                         ];
111                         $tab_args = [
112                                 'order=comment', //all
113                                 'order=post',    //postord
114                                 'conv=1',        //conv
115                                 '',                 //new
116                                 'star=1',        //starred
117                                 'bmark=1',       //bookmarked
118                         ];
119
120                         $k = array_search('active', $last_sel_tabs);
121
122                         if ($k != 3) {
123                                 $net_baseurl .= $tab_baseurls[$k];
124
125                                 // parse out tab queries
126                                 $dest_qa = [];
127                                 $dest_qs = $tab_args[$k];
128                                 parse_str($dest_qs, $dest_qa);
129                                 $net_args = array_merge($net_args, $dest_qa);
130                         } else {
131                                 $remember_tab = false;
132                         }
133                 }
134
135                 if ($sel_nets) {
136                         $net_args['nets'] = $sel_nets;
137                 }
138
139                 if ($remember_tab) {
140                         $net_args = array_merge($query_array, $net_args);
141                         $net_queries = http_build_query($net_args);
142
143                         $redir_url = ($net_queries ? $net_baseurl . '?' . $net_queries : $net_baseurl);
144
145                         $a->internalRedirect($redir_url);
146                 }
147         }
148
149         if (empty($a->page['aside'])) {
150                 $a->page['aside'] = '';
151         }
152
153         $a->page['aside'] .= Group::sidebarWidget('network/0', 'network', 'standard', $group_id);
154         $a->page['aside'] .= ForumManager::widget(local_user(), $cid);
155         $a->page['aside'] .= Widget::postedByYear('network', local_user(), false);
156         $a->page['aside'] .= Widget::networks('network', defaults($_GET, 'nets', '') );
157         $a->page['aside'] .= saved_searches($search);
158         $a->page['aside'] .= Widget::fileAs('network', defaults($_GET, 'file', '') );
159 }
160
161 function saved_searches($search)
162 {
163         $srchurl = '/network?f='
164                 . (!empty($_GET['cid'])   ? '&cid='   . rawurlencode($_GET['cid'])   : '')
165                 . (!empty($_GET['star'])  ? '&star='  . rawurlencode($_GET['star'])  : '')
166                 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
167                 . (!empty($_GET['conv'])  ? '&conv='  . rawurlencode($_GET['conv'])  : '')
168                 . (!empty($_GET['nets'])  ? '&nets='  . rawurlencode($_GET['nets'])  : '')
169                 . (!empty($_GET['cmin'])  ? '&cmin='  . rawurlencode($_GET['cmin'])  : '')
170                 . (!empty($_GET['cmax'])  ? '&cmax='  . rawurlencode($_GET['cmax'])  : '')
171                 . (!empty($_GET['file'])  ? '&file='  . rawurlencode($_GET['file'])  : '');
172         ;
173
174         $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
175         $saved = [];
176
177         while ($rr = DBA::fetch($terms)) {
178                 $saved[] = [
179                         'id'          => $rr['id'],
180                         'term'        => $rr['term'],
181                         'encodedterm' => urlencode($rr['term']),
182                         'delete'      => L10n::t('Remove term'),
183                         'selected'    => ($search == $rr['term']),
184                 ];
185         }
186
187         $tpl = Renderer::getMarkupTemplate('saved_searches_aside.tpl');
188         $o = Renderer::replaceMacros($tpl, [
189                 '$title'     => L10n::t('Saved Searches'),
190                 '$add'       => L10n::t('add'),
191                 '$searchbox' => HTML::search($search, 'netsearch-box', $srchurl),
192                 '$saved'     => $saved,
193         ]);
194
195         return $o;
196 }
197
198 /**
199  * Return selected tab from query
200  *
201  * urls -> returns
202  *        '/network'                    => $no_active = 'active'
203  *        '/network?order=comment'    => $comment_active = 'active'
204  *        '/network?order=post'    => $postord_active = 'active'
205  *        '/network?conv=1',        => $conv_active = 'active'
206  *        '/network/new',                => $new_active = 'active'
207  *        '/network?star=1',        => $starred_active = 'active'
208  *        '/network?bmark=1',        => $bookmarked_active = 'active'
209  *
210  * @param App $a
211  * @return array ($no_active, $comment_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active);
212  */
213 function network_query_get_sel_tab(App $a)
214 {
215         $no_active = '';
216         $starred_active = '';
217         $new_active = '';
218         $bookmarked_active = '';
219         $all_active = '';
220         $conv_active = '';
221         $postord_active = '';
222
223         if (($a->argc > 1 && $a->argv[1] === 'new') || ($a->argc > 2 && $a->argv[2] === 'new')) {
224                 $new_active = 'active';
225         }
226
227         if (!empty($_GET['star'])) {
228                 $starred_active = 'active';
229         }
230
231         if (!empty($_GET['bmark'])) {
232                 $bookmarked_active = 'active';
233         }
234
235         if (!empty($_GET['conv'])) {
236                 $conv_active = 'active';
237         }
238
239         if (($new_active == '') && ($starred_active == '') && ($bookmarked_active == '') && ($conv_active == '')) {
240                 $no_active = 'active';
241         }
242
243         if ($no_active == 'active' && !empty($_GET['order'])) {
244                 switch($_GET['order']) {
245                         case 'post'    : $postord_active = 'active'; $no_active=''; break;
246                         case 'comment' : $all_active     = 'active'; $no_active=''; break;
247                 }
248         }
249
250         return [$no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active];
251 }
252
253 function network_query_get_sel_group(App $a)
254 {
255         $group = false;
256
257         if ($a->argc >= 2 && is_numeric($a->argv[1])) {
258                 $group = $a->argv[1];
259         }
260
261         return $group;
262 }
263
264 /**
265  * @brief Sets the pager data and returns SQL
266  *
267  * @param App     $a      The global App
268  * @param Pager   $pager
269  * @param integer $update Used for the automatic reloading
270  * @return string SQL with the appropriate LIMIT clause
271  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272  */
273 function networkPager(App $a, Pager $pager, $update)
274 {
275         if ($update) {
276                 // only setup pagination on initial page view
277                 return ' LIMIT 100';
278         }
279
280         //  check if we serve a mobile device and get the user settings
281         //  accordingly
282         if ($a->is_mobile) {
283                 $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_mobile_network');
284                 $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 20);
285         } else {
286                 $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_network');
287                 $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 40);
288         }
289
290         //  now that we have the user settings, see if the theme forces
291         //  a maximum item number which is lower then the user choice
292         if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
293                 $itemspage_network = $a->force_max_items;
294         }
295
296         $pager->setItemsPerPage($itemspage_network);
297
298         return sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
299 }
300
301 /**
302  * @brief Sets items as seen
303  *
304  * @param array $condition The array with the SQL condition
305  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
306  */
307 function networkSetSeen($condition)
308 {
309         if (empty($condition)) {
310                 return;
311         }
312
313         $unseen = Item::exists($condition);
314
315         if ($unseen) {
316                 Item::update(['unseen' => false], $condition);
317         }
318 }
319
320 /**
321  * @brief Create the conversation HTML
322  *
323  * @param App     $a      The global App
324  * @param array   $items  Items of the conversation
325  * @param Pager   $pager
326  * @param string  $mode   Display mode for the conversation
327  * @param integer $update Used for the automatic reloading
328  * @param string  $ordering
329  * @return string HTML of the conversation
330  * @throws ImagickException
331  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
332  */
333 function networkConversation(App $a, $items, Pager $pager, $mode, $update, $ordering = '')
334 {
335         // Set this so that the conversation function can find out contact info for our wall-wall items
336         $a->page_contact = $a->contact;
337
338         if (!is_array($items)) {
339                 Logger::log("Expecting items to be an array. Got " . print_r($items, true));
340                 $items = [];
341         }
342
343         $o = conversation($a, $items, $pager, $mode, $update, false, $ordering, local_user());
344
345         if (!$update) {
346                 if (PConfig::get(local_user(), 'system', 'infinite_scroll')) {
347                         $o .= HTML::scrollLoader();
348                 } else {
349                         $o .= $pager->renderMinimal(count($items));
350                 }
351         }
352
353         return $o;
354 }
355
356 function network_content(App $a, $update = 0, $parent = 0)
357 {
358         if (!local_user()) {
359                 return Login::form();
360         }
361
362         /// @TODO Is this really necessary? $a is already available to hooks
363         $arr = ['query' => $a->query_string];
364         Hook::callAll('network_content_init', $arr);
365
366         $flat_mode = false;
367
368         if ($a->argc > 1) {
369                 for ($x = 1; $x < $a->argc; $x ++) {
370                         if ($a->argv[$x] === 'new') {
371                                 $flat_mode = true;
372                         }
373                 }
374         }
375
376         if (!empty($_GET['file'])) {
377                 $flat_mode = true;
378         }
379
380         if ($flat_mode) {
381                 $o = networkFlatView($a, $update);
382         } else {
383                 $o = networkThreadedView($a, $update, $parent);
384         }
385
386         if ($o === '') {
387                 info("No items found");
388         }
389
390         return $o;
391 }
392
393 /**
394  * @brief Get the network content in flat view
395  *
396  * @param App     $a      The global App
397  * @param integer $update Used for the automatic reloading
398  * @return string HTML of the network content in flat view
399  * @throws ImagickException
400  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
401  * @global Pager  $pager
402  */
403 function networkFlatView(App $a, $update = 0)
404 {
405         global $pager;
406         // Rawmode is used for fetching new content at the end of the page
407         $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
408
409         $o = '';
410
411         $file = defaults($_GET, 'file', '');
412
413         if (!$update && !$rawmode) {
414                 $tabs = network_tabs($a);
415                 $o .= $tabs;
416
417                 Nav::setSelected('network');
418
419                 $x = [
420                         'is_owner' => true,
421                         'allow_location' => $a->user['allow_location'],
422                         'default_location' => $a->user['default-location'],
423                         'nickname' => $a->user['nickname'],
424                         'lockstate' => (is_array($a->user) &&
425                         (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
426                         strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock'),
427                         'default_perms' => ACL::getDefaultUserPermissions($a->user),
428                         'acl' => ACL::getFullSelectorHTML($a->user, true),
429                         'bang' => '',
430                         'visitor' => 'block',
431                         'profile_uid' => local_user(),
432                         'content' => '',
433                 ];
434
435                 $o .= status_editor($a, $x);
436
437                 if (!Config::get('theme', 'hide_eventlist')) {
438                         $o .= Profile::getBirthdays();
439                         $o .= Profile::getEventsReminderHTML();
440                 }
441         }
442
443         $pager = new Pager($a->query_string);
444
445         networkPager($a, $pager, $update);
446
447         $item_params = ['order' => ['id' => true]];
448
449         if (strlen($file)) {
450                 $term_condition = ["`term` = ? AND `otype` = ? AND `type` = ? AND `uid` = ?",
451                         $file, Term::OBJECT_TYPE_POST, Term::FILE, local_user()];
452                 $term_params = ['order' => ['tid' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
453                 $result = DBA::select('term', ['oid'], $term_condition, $term_params);
454
455                 $posts = [];
456                 while ($term = DBA::fetch($result)) {
457                         $posts[] = $term['oid'];
458                 }
459                 DBA::close($result);
460
461                 if (count($posts) == 0) {
462                         return '';
463                 }
464                 $item_condition = ['uid' => local_user(), 'id' => $posts];
465         } else {
466                 $item_condition = ['uid' => local_user()];
467                 $item_params['limit'] = [$pager->getStart(), $pager->getItemsPerPage()];
468
469                 networkSetSeen(['unseen' => true, 'uid' => local_user()]);
470         }
471
472         $result = Item::selectForUser(local_user(), [], $item_condition, $item_params);
473         $items = Item::inArray($result);
474         $o .= networkConversation($a, $items, $pager, 'network-new', $update);
475
476         return $o;
477 }
478
479 /**
480  * @brief Get the network content in threaded view
481  *
482  * @param  App     $a      The global App
483  * @param  integer $update Used for the automatic reloading
484  * @param  integer $parent
485  * @return string HTML of the network content in flat view
486  * @throws ImagickException
487  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
488  * @global Pager   $pager
489  */
490 function networkThreadedView(App $a, $update, $parent)
491 {
492         /// @TODO this will have to be converted to a static property of the converted Module\Network class
493         global $pager;
494
495         // Rawmode is used for fetching new content at the end of the page
496         $rawmode = (isset($_GET['mode']) AND ( $_GET['mode'] == 'raw'));
497
498         if (isset($_GET['last_received']) && isset($_GET['last_commented']) && isset($_GET['last_created']) && isset($_GET['last_id'])) {
499                 $last_received = DateTimeFormat::utc($_GET['last_received']);
500                 $last_commented = DateTimeFormat::utc($_GET['last_commented']);
501                 $last_created = DateTimeFormat::utc($_GET['last_created']);
502                 $last_id = intval($_GET['last_id']);
503         } else {
504                 $last_received = '';
505                 $last_commented = '';
506                 $last_created = '';
507                 $last_id = 0;
508         }
509
510         $datequery = $datequery2 = '';
511
512         $gid = 0;
513
514         $default_permissions = [];
515
516         if ($a->argc > 1) {
517                 for ($x = 1; $x < $a->argc; $x ++) {
518                         if (is_a_date_arg($a->argv[$x])) {
519                                 if ($datequery) {
520                                         $datequery2 = Strings::escapeHtml($a->argv[$x]);
521                                 } else {
522                                         $datequery = Strings::escapeHtml($a->argv[$x]);
523                                         $_GET['order'] = 'post';
524                                 }
525                         } elseif (intval($a->argv[$x])) {
526                                 $gid = intval($a->argv[$x]);
527                                 $default_permissions['allow_gid'] = [$gid];
528                         }
529                 }
530         }
531
532         $o = '';
533
534         $cid   = intval(defaults($_GET, 'cid'  , 0));
535         $star  = intval(defaults($_GET, 'star' , 0));
536         $bmark = intval(defaults($_GET, 'bmark', 0));
537         $conv  = intval(defaults($_GET, 'conv' , 0));
538         $order = Strings::escapeTags(defaults($_GET, 'order', 'comment'));
539         $nets  =        defaults($_GET, 'nets' , '');
540
541         $allowedCids = [];
542         if ($cid) {
543                 $allowedCids[] = (int) $cid;
544         } elseif ($nets) {
545                 $condition = [
546                         'uid'     => local_user(),
547                         'network' => $nets,
548                         'self'    => false,
549                         'blocked' => false,
550                         'pending' => false,
551                         'archive' => false,
552                         'rel'     => [Contact::SHARING, Contact::FRIEND],
553                 ];
554                 $contactStmt = DBA::select('contact', ['id'], $condition);
555                 while ($contact = DBA::fetch($contactStmt)) {
556                         $allowedCids[] = (int) $contact['id'];
557                 }
558                 DBA::close($contactStmt);
559         }
560
561         if (count($allowedCids)) {
562                 $default_permissions['allow_cid'] = $allowedCids;
563         }
564
565         if (!$update && !$rawmode) {
566                 $tabs = network_tabs($a);
567                 $o .= $tabs;
568
569                 if ($gid && ($t = Contact::getOStatusCountByGroupId($gid)) && !PConfig::get(local_user(), 'system', 'nowarn_insecure')) {
570                         notice(L10n::tt("Warning: This group contains %s member from a network that doesn't allow non public messages.",
571                                 "Warning: This group contains %s members from a network that doesn't allow non public messages.",
572                                 $t) . EOL);
573                         notice(L10n::t("Messages in this group won't be send to these receivers.").EOL);
574                 }
575
576                 Nav::setSelected('network');
577
578                 $content = '';
579
580                 if ($cid) {
581                         // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
582                         $condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
583                         $contact = DBA::selectFirst('contact', ['addr', 'nick'], $condition);
584                         if (DBA::isResult($contact)) {
585                                 if ($contact['addr'] != '') {
586                                         $content = '!' . $contact['addr'];
587                                 } else {
588                                         $content = '!' . $contact['nick'] . '+' . $cid;
589                                 }
590                         }
591                 }
592
593                 $x = [
594                         'is_owner' => true,
595                         'allow_location' => $a->user['allow_location'],
596                         'default_location' => $a->user['default-location'],
597                         'nickname' => $a->user['nickname'],
598                         'lockstate' => ($gid || $cid || $nets || (is_array($a->user) &&
599                         (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
600                         strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
601                         'default_perms' => ACL::getDefaultUserPermissions($a->user),
602                         'acl' => ACL::getFullSelectorHTML($a->user, true, $default_permissions),
603                         'bang' => (($gid || $cid || $nets) ? '!' : ''),
604                         'visitor' => 'block',
605                         'profile_uid' => local_user(),
606                         'content' => $content,
607                 ];
608
609                 $o .= status_editor($a, $x);
610         }
611
612         // We don't have to deal with ACLs on this page. You're looking at everything
613         // that belongs to you, hence you can see all of it. We will filter by group if
614         // desired.
615
616         $sql_post_table = '';
617         $sql_options = ($star ? " AND `thread`.`starred` " : '');
618         $sql_options .= ($bmark ? sprintf(" AND `thread`.`post-type` = %d ", Item::PT_PAGE) : '');
619         $sql_extra = $sql_options;
620         $sql_extra2 = '';
621         $sql_extra3 = '';
622         $sql_table = '`thread`';
623         $sql_parent = '`iid`';
624
625         if ($update) {
626                 $sql_table = '`item`';
627                 $sql_parent = '`parent`';
628                 $sql_post_table = " INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`";
629         }
630
631         $sql_nets = (($nets) ? sprintf(" AND $sql_table.`network` = '%s' ", DBA::escape($nets)) : '');
632         $sql_tag_nets = (($nets) ? sprintf(" AND `item`.`network` = '%s' ", DBA::escape($nets)) : '');
633
634         if ($gid) {
635                 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
636                 if (!DBA::isResult($group)) {
637                         if ($update) {
638                                 exit();
639                         }
640                         notice(L10n::t('No such group') . EOL);
641                         $a->internalRedirect('network/0');
642                         // NOTREACHED
643                 }
644
645                 $contacts = Group::expand([$gid]);
646
647                 if ((is_array($contacts)) && count($contacts)) {
648                         $contact_str_self = '';
649
650                         $contact_str = implode(',', $contacts);
651                         $self = DBA::selectFirst('contact', ['id'], ['uid' => local_user(), 'self' => true]);
652                         if (DBA::isResult($self)) {
653                                 $contact_str_self = $self['id'];
654                         }
655
656                         $sql_post_table .= " INNER JOIN `item` AS `temp1` ON `temp1`.`id` = " . $sql_table . "." . $sql_parent;
657                         $sql_extra3 .= " AND (`thread`.`contact-id` IN ($contact_str) ";
658                         $sql_extra3 .= " OR (`thread`.`contact-id` = '$contact_str_self' AND `temp1`.`allow_gid` LIKE '" . Strings::protectSprintf('%<' . intval($gid) . '>%') . "' AND `temp1`.`private`))";
659                 } else {
660                         $sql_extra3 .= " AND false ";
661                         info(L10n::t('Group is empty'));
662                 }
663
664                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
665                         '$title' => L10n::t('Group: %s', $group['name'])
666                 ]) . $o;
667         } elseif ($cid) {
668                 $fields = ['id', 'name', 'network', 'writable', 'nurl',
669                         'forum', 'prv', 'contact-type', 'addr', 'thumb', 'location'];
670                 $condition = ["`id` = ? AND (NOT `blocked` OR `pending`)", $cid];
671                 $contact = DBA::selectFirst('contact', $fields, $condition);
672                 if (DBA::isResult($contact)) {
673                         $sql_extra = " AND " . $sql_table . ".`contact-id` = " . intval($cid);
674
675                         $entries[0] = [
676                                 'id' => 'network',
677                                 'name' => $contact['name'],
678                                 'itemurl' => defaults($contact, 'addr', $contact['nurl']),
679                                 'thumb' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
680                                 'details' => $contact['location'],
681                         ];
682
683                         $entries[0]['account_type'] = Contact::getAccountType($contact);
684
685                         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
686                                 'contacts' => $entries,
687                                 'id' => 'network',
688                         ]) . $o;
689
690                         if ($contact['network'] === Protocol::OSTATUS && $contact['writable'] && !PConfig::get(local_user(),'system','nowarn_insecure')) {
691                                 notice(L10n::t('Private messages to this person are at risk of public disclosure.') . EOL);
692                         }
693                 } else {
694                         notice(L10n::t('Invalid contact.') . EOL);
695                         $a->internalRedirect('network');
696                         // NOTREACHED
697                 }
698         }
699
700         if (!$gid && !$cid && !$update && !Config::get('theme', 'hide_eventlist')) {
701                 $o .= Profile::getBirthdays();
702                 $o .= Profile::getEventsReminderHTML();
703         }
704
705         if ($datequery) {
706                 $sql_extra3 .= Strings::protectSprintf(sprintf(" AND $sql_table.created <= '%s' ",
707                                 DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
708         }
709         if ($datequery2) {
710                 $sql_extra3 .= Strings::protectSprintf(sprintf(" AND $sql_table.created >= '%s' ",
711                                 DBA::escape(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
712         }
713
714         if ($conv) {
715                 $sql_extra3 .= " AND $sql_table.`mention`";
716         }
717
718         // Normal conversation view
719         if ($order === 'post') {
720                 $ordering = '`created`';
721                 $order_mode = 'created';
722         } else {
723                 $ordering = '`commented`';
724                 $order_mode = 'commented';
725         }
726
727         $sql_order = "$sql_table.$ordering";
728
729         if (!empty($_GET['offset'])) {
730                 $sql_range = sprintf(" AND $sql_order <= '%s'", DBA::escape($_GET['offset']));
731         } else {
732                 $sql_range = '';
733         }
734
735         $pager = new Pager($a->query_string);
736
737         $pager_sql = networkPager($a, $pager, $update);
738
739         $last_date = '';
740
741         switch ($order_mode) {
742                 case 'received':
743                         if ($last_received != '') {
744                                 $last_date = $last_received;
745                                 $sql_range .= sprintf(" AND $sql_table.`received` < '%s'", DBA::escape($last_received));
746                                 $pager->setPage(1);
747                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
748                         }
749                         break;
750                 case 'commented':
751                         if ($last_commented != '') {
752                                 $last_date = $last_commented;
753                                 $sql_range .= sprintf(" AND $sql_table.`commented` < '%s'", DBA::escape($last_commented));
754                                 $pager->setPage(1);
755                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
756                         }
757                         break;
758                 case 'created':
759                         if ($last_created != '') {
760                                 $last_date = $last_created;
761                                 $sql_range .= sprintf(" AND $sql_table.`created` < '%s'", DBA::escape($last_created));
762                                 $pager->setPage(1);
763                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
764                         }
765                         break;
766                 case 'id':
767                         if (($last_id > 0) && ($sql_table == '`thread`')) {
768                                 $sql_range .= sprintf(" AND $sql_table.`iid` < '%s'", DBA::escape($last_id));
769                                 $pager->setPage(1);
770                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
771                         }
772                         break;
773         }
774
775         // Fetch a page full of parent items for this page
776         if ($update) {
777                 if (!empty($parent)) {
778                         // Load only a single thread
779                         $sql_extra4 = "`item`.`id` = ".intval($parent);
780                 } else {
781                         // Load all unseen items
782                         $sql_extra4 = "`item`.`unseen`";
783                         if (Config::get("system", "like_no_comment")) {
784                                 $sql_extra4 .= " AND `item`.`gravity` IN (" . GRAVITY_PARENT . "," . GRAVITY_COMMENT . ")";
785                         }
786                         if ($order === 'post') {
787                                 // Only show toplevel posts when updating posts in this order mode
788                                 $sql_extra4 .= " AND `item`.`id` = `item`.`parent`";
789                         }
790                 }
791
792                 $r = q("SELECT `item`.`parent-uri` AS `uri`, `item`.`parent` AS `item_id`, $sql_order AS `order_date`
793                         FROM `item` $sql_post_table
794                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
795                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
796                                 AND (`item`.`gravity` != %d
797                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
798                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
799                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
800                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted`
801                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
802                         AND NOT `item`.`moderated` AND $sql_extra4
803                         $sql_extra3 $sql_extra $sql_range $sql_nets
804                         ORDER BY `order_date` DESC LIMIT 100",
805                         intval(GRAVITY_PARENT),
806                         intval(Contact::SHARING),
807                         intval(Contact::FRIEND),
808                         intval(local_user()),
809                         intval(local_user())
810                 );
811         } else {
812                 $r = q("SELECT `item`.`uri`, `thread`.`iid` AS `item_id`, $sql_order AS `order_date`
813                         FROM `thread` $sql_post_table
814                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
815                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
816                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
817                                 AND (`item`.`gravity` != %d
818                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
819                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
820                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
821                         WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
822                         AND NOT `thread`.`moderated`
823                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
824                         $sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets
825                         ORDER BY `order_date` DESC $pager_sql",
826                         intval(GRAVITY_PARENT),
827                         intval(Contact::SHARING),
828                         intval(Contact::FRIEND),
829                         intval(local_user()),
830                         intval(local_user())
831                 );
832         }
833
834         // Only show it when unfiltered (no groups, no networks, ...)
835         if (in_array($nets, ['', Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]) && (strlen($sql_extra . $sql_extra2 . $sql_extra3) == 0)) {
836                 if (DBA::isResult($r)) {
837                         $top_limit = current($r)['order_date'];
838                         $bottom_limit = end($r)['order_date'];
839                         if (empty($_SESSION['network_last_top_limit']) || ($_SESSION['network_last_top_limit'] < $top_limit)) {
840                                 $_SESSION['network_last_top_limit'] = $top_limit;
841                         }
842                 } else {
843                         $top_limit = $bottom_limit = DateTimeFormat::utcNow();
844                 }
845
846                 // When checking for updates we need to fetch from the newest date to the newest date before
847                 // Only do this, when the last stored date isn't too long ago (10 times the update interval)
848                 $browser_update = PConfig::get(local_user(), 'system', 'update_interval', 40000) / 1000;
849
850                 if (($browser_update > 0) && $update && !empty($_SESSION['network_last_date']) &&
851                         (($bottom_limit < $_SESSION['network_last_date']) || ($top_limit == $bottom_limit)) &&
852                         ((time() - $_SESSION['network_last_date_timestamp']) < ($browser_update * 10))) {
853                         $bottom_limit = $_SESSION['network_last_date'];
854                 }
855                 $_SESSION['network_last_date'] = defaults($_SESSION, 'network_last_top_limit', $top_limit);
856                 $_SESSION['network_last_date_timestamp'] = time();
857
858                 if ($last_date > $top_limit) {
859                         $top_limit = $last_date;
860                 } elseif ($pager->getPage() == 1) {
861                         // Highest possible top limit when we are on the first page
862                         $top_limit = DateTimeFormat::utcNow();
863                 }
864
865                 $items = DBA::p("SELECT `item`.`parent-uri` AS `uri`, 0 AS `item_id`, `item`.$ordering AS `order_date`, `author`.`url` AS `author-link` FROM `item`
866                         STRAIGHT_JOIN (SELECT `oid` FROM `term` WHERE `term` IN
867                                 (SELECT SUBSTR(`term`, 2) FROM `search` WHERE `uid` = ? AND `term` LIKE '#%') AND `otype` = ? AND `type` = ? AND `uid` = 0) AS `term`
868                         ON `item`.`id` = `term`.`oid`
869                         STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = `item`.`author-id`
870                         WHERE `item`.`uid` = 0 AND `item`.$ordering < ? AND `item`.$ordering > ?
871                                 AND NOT `author`.`hidden` AND NOT `author`.`blocked`" . $sql_tag_nets,
872                         local_user(), TERM_OBJ_POST, TERM_HASHTAG,
873                         $top_limit, $bottom_limit);
874
875                 $data = DBA::toArray($items);
876
877                 if (count($data) > 0) {
878                         $tag_top_limit = current($data)['order_date'];
879                         if ($_SESSION['network_last_date'] < $tag_top_limit) {
880                                 $_SESSION['network_last_date'] = $tag_top_limit;
881                         }
882
883                         Logger::log('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update);
884                         $s = [];
885                         foreach ($r as $item) {
886                                 $s[$item['uri']] = $item;
887                         }
888                         foreach ($data as $item) {
889                                 // Don't show hash tag posts from blocked or ignored contacts
890                                 $condition = ["`nurl` = ? AND `uid` = ? AND (`blocked` OR `readonly`)",
891                                         Strings::normaliseLink($item['author-link']), local_user()];
892                                 if (!DBA::exists('contact', $condition)) {
893                                         $s[$item['uri']] = $item;
894                                 }
895                         }
896                         $r = $s;
897                 }
898         }
899
900         $parents_str = '';
901         $date_offset = '';
902
903         $items = $r;
904
905         if (DBA::isResult($items)) {
906                 $parents_arr = [];
907
908                 foreach ($items as $item) {
909                         if ($date_offset < $item['order_date']) {
910                                 $date_offset = $item['order_date'];
911                         }
912                         if (!in_array($item['item_id'], $parents_arr) && ($item['item_id'] > 0)) {
913                                 $parents_arr[] = $item['item_id'];
914                         }
915                 }
916                 $parents_str = implode(', ', $parents_arr);
917         }
918
919         if (!empty($_GET['offset'])) {
920                 $date_offset = $_GET['offset'];
921         }
922
923         $query_string = $a->query_string;
924         if ($date_offset && !preg_match('/[?&].offset=/', $query_string)) {
925                 $query_string .= '&offset=' . urlencode($date_offset);
926         }
927
928         $pager->setQueryString($query_string);
929
930         // We aren't going to try and figure out at the item, group, and page
931         // level which items you've seen and which you haven't. If you're looking
932         // at the top level network page just mark everything seen.
933
934         if (!$gid && !$cid && !$star) {
935                 $condition = ['unseen' => true, 'uid' => local_user()];
936                 networkSetSeen($condition);
937         } elseif ($parents_str) {
938                 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
939                 networkSetSeen($condition);
940         }
941
942
943         $mode = 'network';
944         $o .= networkConversation($a, $items, $pager, $mode, $update, $ordering);
945
946         return $o;
947 }
948
949 /**
950  * @brief Get the network tabs menu
951  *
952  * @param App $a The global App
953  * @return string Html of the networktab
954  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
955  */
956 function network_tabs(App $a)
957 {
958         // item filter tabs
959         /// @TODO fix this logic, reduce duplication
960         /// $a->page['content'] .= '<div class="tabs-wrapper">';
961         list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active) = network_query_get_sel_tab($a);
962
963         // if no tabs are selected, defaults to comments
964         if ($no_active == 'active') {
965                 $all_active = 'active';
966         }
967
968         $cmd = $a->cmd;
969
970         // tabs
971         $tabs = [
972                 [
973                         'label' => L10n::t('Commented Order'),
974                         'url'   => str_replace('/new', '', $cmd) . '?order=comment' . (!empty($_GET['cid']) ? '&cid=' . $_GET['cid'] : ''),
975                         'sel'   => $all_active,
976                         'title' => L10n::t('Sort by Comment Date'),
977                         'id'    => 'commented-order-tab',
978                         'accesskey' => 'e',
979                 ],
980                 [
981                         'label' => L10n::t('Posted Order'),
982                         'url'   => str_replace('/new', '', $cmd) . '?order=post' . (!empty($_GET['cid']) ? '&cid=' . $_GET['cid'] : ''),
983                         'sel'   => $postord_active,
984                         'title' => L10n::t('Sort by Post Date'),
985                         'id'    => 'posted-order-tab',
986                         'accesskey' => 't',
987                 ],
988         ];
989
990         $tabs[] = [
991                 'label' => L10n::t('Personal'),
992                 'url'   => str_replace('/new', '', $cmd) . (!empty($_GET['cid']) ? '/?cid=' . $_GET['cid'] : '/?f=') . '&conv=1',
993                 'sel'   => $conv_active,
994                 'title' => L10n::t('Posts that mention or involve you'),
995                 'id'    => 'personal-tab',
996                 'accesskey' => 'r',
997         ];
998
999         if (Feature::isEnabled(local_user(), 'new_tab')) {
1000                 $tabs[] = [
1001                         'label' => L10n::t('New'),
1002                         'url'   => 'network/new' . (!empty($_GET['cid']) ? '/?cid=' . $_GET['cid'] : ''),
1003                         'sel'   => $new_active,
1004                         'title' => L10n::t('Activity Stream - by date'),
1005                         'id'    => 'activitiy-by-date-tab',
1006                         'accesskey' => 'w',
1007                 ];
1008         }
1009
1010         if (Feature::isEnabled(local_user(), 'link_tab')) {
1011                 $tabs[] = [
1012                         'label' => L10n::t('Shared Links'),
1013                         'url'   => str_replace('/new', '', $cmd) . (!empty($_GET['cid']) ? '/?cid=' . $_GET['cid'] : '/?f=') . '&bmark=1',
1014                         'sel'   => $bookmarked_active,
1015                         'title' => L10n::t('Interesting Links'),
1016                         'id'    => 'shared-links-tab',
1017                         'accesskey' => 'b',
1018                 ];
1019         }
1020
1021         $tabs[] = [
1022                 'label' => L10n::t('Starred'),
1023                 'url'   => str_replace('/new', '', $cmd) . (!empty($_GET['cid']) ? '/?cid=' . $_GET['cid'] : '/?f=') . '&star=1',
1024                 'sel'   => $starred_active,
1025                 'title' => L10n::t('Favourite Posts'),
1026                 'id'    => 'starred-posts-tab',
1027                 'accesskey' => 'm',
1028         ];
1029
1030         // save selected tab, but only if not in file mode
1031         if (empty($_GET['file'])) {
1032                 PConfig::set(local_user(), 'network.view', 'tab.selected', [
1033                         $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active
1034                 ]);
1035         }
1036
1037         $arr = ['tabs' => $tabs];
1038         Hook::callAll('network_tabs', $arr);
1039
1040         $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1041
1042         return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1043
1044         // --- end item filter tabs
1045 }
1046
1047 /**
1048  * Network hook into the HTML head to enable infinite scroll.
1049  *
1050  * Since the HTML head is built after the module content has been generated, we need to retrieve the base query string
1051  * of the page to make the correct asynchronous call. This is obtained through the Pager that was instantiated in
1052  * networkThreadedView or networkFlatView.
1053  *
1054  * @param App     $a
1055  * @param  string $htmlhead The head tag HTML string
1056  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1057  * @global Pager  $pager
1058  */
1059 function network_infinite_scroll_head(App $a, &$htmlhead)
1060 {
1061         /// @TODO this will have to be converted to a static property of the converted Module\Network class
1062         /**
1063          * @var $pager Pager
1064          */
1065         global $pager;
1066
1067         if (PConfig::get(local_user(), 'system', 'infinite_scroll')
1068                 && defaults($_GET, 'mode', '') != 'minimal'
1069         ) {
1070                 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1071                 $htmlhead .= Renderer::replaceMacros($tpl, [
1072                         '$pageno'     => $pager->getPage(),
1073                         '$reload_uri' => $pager->getBaseQueryString()
1074                 ]);
1075         }
1076 }