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