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