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