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