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