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