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