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