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