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