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