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