]> git.mxchange.org Git - friendica.git/blob - mod/network.php
5e94429b5c8a5b35d3997df62c9edaf99cefebc1
[friendica.git] / mod / network.php
1 <?php
2 function network_init(App $a) {
3         if (! local_user()) {
4                 notice( t('Permission denied.') . EOL);
5                 return;
6         }
7
8         $is_a_date_query = false;
9         if (x($_GET, 'cid') && intval($_GET['cid']) != 0) {
10                 $cid = $_GET['cid'];
11         }
12
13         if ($a->argc > 1) {
14                 for ($x = 1; $x < $a->argc; $x ++) {
15                         if (is_a_date_arg($a->argv[$x])) {
16                                 $is_a_date_query = true;
17                                 break;
18                         }
19                 }
20         }
21
22         // convert query string to array. remove friendica args
23         $query_array = array();
24         $query_string = str_replace($a->cmd."?", "", $a->query_string);
25         parse_str($query_string, $query_array);
26         array_shift($query_array);
27
28         // fetch last used network view and redirect if needed
29         if (! $is_a_date_query) {
30                 $sel_tabs = network_query_get_sel_tab($a);
31                 $sel_nets = network_query_get_sel_net();
32                 $sel_groups = network_query_get_sel_group($a);
33                 $last_sel_tabs = get_pconfig(local_user(), 'network.view','tab.selected');
34                 $last_sel_nets = get_pconfig(local_user(), 'network.view', 'net.selected');
35                 $last_sel_groups = get_pconfig(local_user(), 'network.view', 'group.selected');
36
37                 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
38                 $remember_net = ($sel_nets === false && $last_sel_nets && $last_sel_nets !== 'all');
39                 $remember_group = ($sel_groups === false && $last_sel_groups && $last_sel_groups != 0);
40
41                 $net_baseurl = '/network';
42                 $net_args = array();
43
44                 if ($remember_group) {
45                         $net_baseurl .= '/' . $last_sel_groups; // Note that the group number must come before the "/new" tab selection
46                 } elseif($sel_groups !== false) {
47                         $net_baseurl .= '/' . $sel_groups;
48                 }
49
50                 if ($remember_tab) {
51                         // redirect if current selected tab is '/network' and
52                         // last selected tab is _not_ '/network?f=&order=comment'.
53                         // and this isn't a date query
54
55                         $tab_baseurls = array(
56                                 '',             //all
57                                 '',             //postord
58                                 '',             //conv
59                                 '/new',         //new
60                                 '',             //starred
61                                 '',             //bookmarked
62                                 '',             //spam
63                         );
64                         $tab_args = array(
65                                 'f=&order=comment',     //all
66                                 'f=&order=post',        //postord
67                                 'f=&conv=1',            //conv
68                                 '',                     //new
69                                 'f=&star=1',            //starred
70                                 'f=&bmark=1',           //bookmarked
71                                 'f=&spam=1',            //spam
72                         );
73
74                         $k = array_search('active', $last_sel_tabs);
75
76                         if ($k != 3) {
77                                 $net_baseurl .= $tab_baseurls[$k];
78
79                                 // parse out tab queries
80                                 $dest_qa = array();
81                                 $dest_qs = $tab_args[$k];
82                                 parse_str($dest_qs, $dest_qa);
83                                 $net_args = array_merge($net_args, $dest_qa);
84                         } else {
85                                 $remember_tab = false;
86                         }
87                 } elseif ($sel_tabs[4] === 'active') {
88                         // The '/new' tab is selected
89                         $remember_group = false;
90                 }
91
92                 if ($remember_net) {
93                         $net_args['nets'] = $last_sel_nets;
94                 }
95                 else if($sel_nets!==false) {
96                         $net_args['nets'] = $sel_nets;
97                 }
98
99                 if($remember_tab || $remember_net || $remember_group) {
100                         $net_args = array_merge($query_array, $net_args);
101                         $net_queries = build_querystring($net_args);
102
103                         $redir_url = ($net_queries ? $net_baseurl."?".$net_queries : $net_baseurl);
104
105                         goaway(App::get_baseurl() . $redir_url);
106                 }
107         }
108
109         // If nets is set to all, unset it
110         if (x($_GET, 'nets') && $_GET['nets'] === 'all') {
111                 unset($_GET['nets']);
112         }
113
114         $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
115
116         set_pconfig(local_user(), 'network.view', 'group.selected', $group_id);
117
118         require_once 'include/group.php';
119         require_once 'include/contact_widgets.php';
120         require_once 'include/items.php';
121         require_once 'include/ForumManager.php';
122
123         if (! x($a->page, 'aside')) {
124                 $a->page['aside'] = '';
125         }
126
127         $search = ((x($_GET, 'search')) ? escape_tags($_GET['search']) : '');
128
129         if (x($_GET, 'save')) {
130                 $r = qu("SELECT * FROM `search` WHERE `uid` = %d AND `term` = '%s' LIMIT 1",
131                         intval(local_user()),
132                         dbesc($search)
133                 );
134                 if (! dbm::is_result($r)) {
135                         q("INSERT INTO `search` ( `uid`,`term` ) VALUES ( %d, '%s') ",
136                                 intval(local_user()),
137                                 dbesc($search)
138                         );
139                 }
140         }
141         if (x($_GET, 'remove')) {
142                 q("DELETE FROM `search` WHERE `uid` = %d AND `term` = '%s'",
143                         intval(local_user()),
144                         dbesc($search)
145                 );
146         }
147
148         // search terms header
149         if (x($_GET, 'search')) {
150                 $a->page['content'] .= replace_macros(get_markup_template("section_title.tpl"),array(
151                         '$title' => sprintf( t('Results for: %s'), $search)
152                 ));
153         }
154
155         $a->page['aside'] .= (feature_enabled(local_user(),'groups') ? group_side('network/0','network','standard',$group_id) : '');
156         $a->page['aside'] .= (feature_enabled(local_user(),'forumlist_widget') ? ForumManager::widget(local_user(),$cid) : '');
157         $a->page['aside'] .= posted_date_widget('network',local_user(),false);
158         $a->page['aside'] .= networks_widget('network',(x($_GET, 'nets') ? $_GET['nets'] : ''));
159         $a->page['aside'] .= saved_searches($search);
160         $a->page['aside'] .= fileas_widget('network',(x($_GET, 'file') ? $_GET['file'] : ''));
161
162 }
163
164 function saved_searches($search) {
165
166         if (! feature_enabled(local_user(),'savedsearch')) {
167                 return '';
168         }
169
170         $a = get_app();
171
172         $srchurl = '/network?f='
173                 . ((x($_GET,'cid'))   ? '&cid='   . $_GET['cid']   : '')
174                 . ((x($_GET,'star'))  ? '&star='  . $_GET['star']  : '')
175                 . ((x($_GET,'bmark')) ? '&bmark=' . $_GET['bmark'] : '')
176                 . ((x($_GET,'conv'))  ? '&conv='  . $_GET['conv']  : '')
177                 . ((x($_GET,'nets'))  ? '&nets='  . $_GET['nets']  : '')
178                 . ((x($_GET,'cmin'))  ? '&cmin='  . $_GET['cmin']  : '')
179                 . ((x($_GET,'cmax'))  ? '&cmax='  . $_GET['cmax']  : '')
180                 . ((x($_GET,'file'))  ? '&file='  . $_GET['file']  : '');
181         ;
182
183         $o = '';
184
185         $r = qu("SELECT `id`,`term` FROM `search` WHERE `uid` = %d",
186                 intval(local_user())
187         );
188
189         $saved = array();
190
191         if (dbm::is_result($r)) {
192                 foreach ($r as $rr) {
193                         $saved[] = array(
194                                 'id'          => $rr['id'],
195                                 'term'        => $rr['term'],
196                                 'encodedterm' => urlencode($rr['term']),
197                                 'delete'      => t('Remove term'),
198                                 'selected'    => ($search==$rr['term']),
199                         );
200                 }
201         }
202
203
204         $tpl = get_markup_template("saved_searches_aside.tpl");
205         $o = replace_macros($tpl, array(
206                 '$title'     => t('Saved Searches'),
207                 '$add'       => t('add'),
208                 '$searchbox' => search($search,'netsearch-box',$srchurl,true),
209                 '$saved'     => $saved,
210         ));
211
212         return $o;
213
214 }
215
216 /**
217  * Return selected tab from query
218  *
219  * urls -> returns
220  *              '/network'                                      => $no_active = 'active'
221  *              '/network?f=&order=comment'     => $comment_active = 'active'
222  *              '/network?f=&order=post'        => $postord_active = 'active'
223  *              '/network?f=&conv=1',           => $conv_active = 'active'
224  *              '/network/new',                         => $new_active = 'active'
225  *              '/network?f=&star=1',           => $starred_active = 'active'
226  *              '/network?f=&bmark=1',          => $bookmarked_active = 'active'
227  *              '/network?f=&spam=1',           => $spam_active = 'active'
228  *
229  * @return Array ( $no_active, $comment_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active );
230  */
231 function network_query_get_sel_tab(App $a) {
232         $no_active='';
233         $starred_active = '';
234         $new_active = '';
235         $bookmarked_active = '';
236         $all_active = '';
237         $search_active = '';
238         $conv_active = '';
239         $spam_active = '';
240         $postord_active = '';
241
242         if(($a->argc > 1 && $a->argv[1] === 'new')
243                 || ($a->argc > 2 && $a->argv[2] === 'new')) {
244                         $new_active = 'active';
245         }
246
247         if(x($_GET,'search')) {
248                 $search_active = 'active';
249         }
250
251         if(x($_GET,'star')) {
252                 $starred_active = 'active';
253         }
254
255         if(x($_GET,'bmark')) {
256                 $bookmarked_active = 'active';
257         }
258
259         if(x($_GET,'conv')) {
260                 $conv_active = 'active';
261         }
262
263         if(x($_GET,'spam')) {
264                 $spam_active = 'active';
265         }
266
267
268
269         if (($new_active == '')
270                 && ($starred_active == '')
271                 && ($bookmarked_active == '')
272                 && ($conv_active == '')
273                 && ($search_active == '')
274                 && ($spam_active == '')) {
275                         $no_active = 'active';
276         }
277
278         if ($no_active=='active' && x($_GET,'order')) {
279                 switch($_GET['order']){
280                  case 'post': $postord_active = 'active'; $no_active=''; break;
281                  case 'comment' : $all_active = 'active'; $no_active=''; break;
282                 }
283         }
284
285         return array($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active);
286 }
287
288 /**
289  * @brief Return selected network from query
290  * @return string Name of the selected network
291  */
292 function network_query_get_sel_net() {
293         $network = false;
294
295         if(x($_GET,'nets')) {
296                 $network = $_GET['nets'];
297         }
298
299         return $network;
300 }
301
302 function network_query_get_sel_group(App $a) {
303         $group = false;
304
305         if($a->argc >= 2 && is_numeric($a->argv[1])) {
306                 $group = $a->argv[1];
307         }
308
309         return $group;
310 }
311
312
313 function network_content(App $a, $update = 0) {
314
315         require_once('include/conversation.php');
316
317         if (! local_user()) {
318                 $_SESSION['return_url'] = $a->query_string;
319                 return login(false);
320         }
321
322         // Rawmode is used for fetching new content at the end of the page
323         $rawmode = (isset($_GET["mode"]) AND ($_GET["mode"] == "raw"));
324
325         /// @TODO Is this really necessary? $a is already available to hooks
326         $arr = array('query' => $a->query_string);
327         call_hooks('network_content_init', $arr);
328
329
330         $datequery = $datequery2 = '';
331
332         $group = 0;
333
334         $nouveau = false;
335
336         if($a->argc > 1) {
337                 for($x = 1; $x < $a->argc; $x ++) {
338                         if(is_a_date_arg($a->argv[$x])) {
339                                 if($datequery)
340                                         $datequery2 = escape_tags($a->argv[$x]);
341                                 else {
342                                         $datequery = escape_tags($a->argv[$x]);
343                                         $_GET['order'] = 'post';
344                                 }
345                         }
346                         elseif($a->argv[$x] === 'new') {
347                                 $nouveau = true;
348                         }
349                         elseif(intval($a->argv[$x])) {
350                                 $group = intval($a->argv[$x]);
351                                 $def_acl = array('allow_gid' => '<' . $group . '>');
352                         }
353                 }
354         }
355
356         $o = '';
357
358
359
360         $contact_id = $a->cid;
361
362         require_once('include/acl_selectors.php');
363
364         $cid = ((x($_GET,'cid')) ? intval($_GET['cid']) : 0);
365         $star = ((x($_GET,'star')) ? intval($_GET['star']) : 0);
366         $bmark = ((x($_GET,'bmark')) ? intval($_GET['bmark']) : 0);
367         $order = ((x($_GET,'order')) ? notags($_GET['order']) : 'comment');
368         $liked = ((x($_GET,'liked')) ? intval($_GET['liked']) : 0);
369         $conv = ((x($_GET,'conv')) ? intval($_GET['conv']) : 0);
370         $spam = ((x($_GET,'spam')) ? intval($_GET['spam']) : 0);
371         $nets = ((x($_GET,'nets')) ? $_GET['nets'] : '');
372         $cmin = ((x($_GET,'cmin')) ? intval($_GET['cmin']) : 0);
373         $cmax = ((x($_GET,'cmax')) ? intval($_GET['cmax']) : 99);
374         $file = ((x($_GET,'file')) ? $_GET['file'] : '');
375
376
377
378         if(x($_GET,'search') || x($_GET,'file'))
379                 $nouveau = true;
380         if($cid)
381                 $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
382
383         if($nets) {
384                 $r = qu("SELECT `id` FROM `contact` WHERE `uid` = %d AND network = '%s' AND `self` = 0",
385                         intval(local_user()),
386                         dbesc($nets)
387                 );
388
389                 $str = '';
390                 if (dbm::is_result($r))
391                         foreach($r as $rr)
392                                 $str .= '<' . $rr['id'] . '>';
393                 if(strlen($str))
394                         $def_acl = array('allow_cid' => $str);
395         }
396         set_pconfig(local_user(), 'network.view', 'net.selected', ($nets ? $nets : 'all'));
397
398         if(!$update AND !$rawmode) {
399                 $tabs = network_tabs($a);
400                 $o .= $tabs;
401
402                 if($group) {
403                         if(($t = group_public_members($group)) && (! get_pconfig(local_user(),'system','nowarn_insecure'))) {
404                                 notice(sprintf(tt("Warning: This group contains %s member from a network that doesn't allow non public messages.",
405                                                 "Warning: This group contains %s members from a network that doesn't allow non public messages.",
406                                                 $t), $t).EOL);
407                                 notice(t("Messages in this group won't be send to these receivers.").EOL);
408                         }
409                 }
410
411                 nav_set_selected('network');
412
413                 $content = "";
414
415                 if ($cid) {
416                         // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
417                         $contact = qu("SELECT `nick` FROM `contact` WHERE `id` = %d AND `uid` = %d AND (`forum` OR `prv`) ",
418                                 intval($cid),
419                                 intval(local_user())
420                         );
421                         if ($contact)
422                                 $content = "@".$contact[0]["nick"]."+".$cid;
423                 }
424
425                 $x = array(
426                         'is_owner' => true,
427                         'allow_location' => $a->user['allow_location'],
428                         'default_location' => $a->user['default-location'],
429                         'nickname' => $a->user['nickname'],
430                         'lockstate'=> ((($group) || ($cid) || ($nets) || (is_array($a->user) &&
431                                         ((strlen($a->user['allow_cid'])) || (strlen($a->user['allow_gid'])) ||
432                                         (strlen($a->user['deny_cid'])) || (strlen($a->user['deny_gid']))))) ? 'lock' : 'unlock'),
433                         'default_perms' => get_acl_permissions($a->user),
434                         'acl'   => populate_acl((($group || $cid || $nets) ? $def_acl : $a->user), true),
435                         'bang'  => (($group || $cid || $nets) ? '!' : ''),
436                         'visitor' => 'block',
437                         'profile_uid' => local_user(),
438                         'acl_data' => construct_acl_data($a, $a->user), // For non-Javascript ACL selector
439                         'content' => $content,
440                 );
441
442                 $o .= status_editor($a,$x);
443
444         }
445
446         // We don't have to deal with ACLs on this page. You're looking at everything
447         // that belongs to you, hence you can see all of it. We will filter by group if
448         // desired.
449
450         $sql_post_table = "";
451         $sql_options  = (($star) ? " AND `thread`.`starred` " : '');
452         $sql_options .= (($bmark) ? " AND `thread`.`bookmark` " : '');
453         $sql_extra = $sql_options;
454         $sql_extra2 = "";
455         $sql_extra3 = "";
456         $sql_table = "`thread`";
457         $sql_parent = "`iid`";
458
459         if ($nouveau OR strlen($file) OR $update) {
460                 $sql_table = "`item`";
461                 $sql_parent = "`parent`";
462                 $sql_post_table = " INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`";
463         }
464
465         $sql_nets = (($nets) ? sprintf(" and $sql_table.`network` = '%s' ", dbesc($nets)) : '');
466
467         if($group) {
468                 $r = qu("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1",
469                         intval($group),
470                         intval($_SESSION['uid'])
471                 );
472                 if (! dbm::is_result($r)) {
473                         if($update)
474                                 killme();
475                         notice( t('No such group') . EOL );
476                         goaway('network/0');
477                         // NOTREACHED
478                 }
479
480                 $contacts = expand_groups(array($group));
481                 $gcontacts = expand_groups(array($group), false, true);
482
483                 if((is_array($contacts)) && count($contacts)) {
484                         $contact_str_self = "";
485                         $gcontact_str_self = "";
486
487                         $contact_str = implode(',',$contacts);
488                         $gcontact_str = implode(',',$gcontacts);
489                         $self = qu("SELECT `contact`.`id`, `gcontact`.`id` AS `gid` FROM `contact`
490                                         INNER JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
491                                         WHERE `uid` = %d AND `self`", intval($_SESSION['uid']));
492                         if (count($self)) {
493                                 $contact_str_self = $self[0]["id"];
494                                 $gcontact_str_self = $self[0]["gid"];
495                         }
496
497                         $sql_post_table .= " INNER JOIN `item` AS `temp1` ON `temp1`.`id` = ".$sql_table.".".$sql_parent;
498                         $sql_extra3 .= " AND (`thread`.`contact-id` IN ($contact_str) ";
499                         $sql_extra3 .= " OR (`thread`.`contact-id` = '$contact_str_self' AND `temp1`.`allow_gid` LIKE '".protect_sprintf('%<'.intval($group).'>%')."' AND `temp1`.`private`))";
500                 } else {
501                         $sql_extra3 .= " AND false ";
502                         info( t('Group is empty'));
503                 }
504
505                 $o = replace_macros(get_markup_template("section_title.tpl"),array(
506                         '$title' => sprintf( t('Group: %s'), $r[0]['name'])
507                 )) . $o;
508
509         }
510         elseif($cid) {
511
512                 $r = qu("SELECT `id`,`name`,`network`,`writable`,`nurl`, `forum`, `prv`, `contact-type`, `addr`, `thumb`, `location` FROM `contact` WHERE `id` = %d
513                                 AND (NOT `blocked` OR `pending`) LIMIT 1",
514                         intval($cid)
515                 );
516                 if (dbm::is_result($r)) {
517                         $sql_extra = " AND ".$sql_table.".`contact-id` = ".intval($cid);
518
519                         $entries[0] = array(
520                                 'id' => 'network',
521                                 'name' => htmlentities($r[0]['name']),
522                                 'itemurl' => (($r[0]['addr']) ? ($r[0]['addr']) : ($r[0]['nurl'])),
523                                 'thumb' => proxy_url($r[0]['thumb'], false, PROXY_SIZE_THUMB),
524                                 'details' => $r[0]['location'],
525                         );
526
527                         $entries[0]["account_type"] = account_type($r[0]);
528
529                         $o = replace_macros(get_markup_template("viewcontact_template.tpl"),array(
530                                 'contacts' => $entries,
531                                 'id' => 'network',
532                         )) . $o;
533
534                         if($r[0]['network'] === NETWORK_OSTATUS && $r[0]['writable'] && (! get_pconfig(local_user(),'system','nowarn_insecure'))) {
535                                 notice( t('Private messages to this person are at risk of public disclosure.') . EOL);
536                         }
537
538                 }
539                 else {
540                         notice( t('Invalid contact.') . EOL);
541                         goaway('network');
542                         // NOTREACHED
543                 }
544         }
545
546         if((! $group) && (! $cid) && (! $update) && (! get_config('theme','hide_eventlist'))) {
547                 $o .= get_birthdays();
548                 $o .= get_events();
549         }
550
551         if($datequery) {
552                 $sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery))));
553         }
554         if($datequery2) {
555                 $sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery2))));
556         }
557
558         //$sql_extra2 = (($nouveau) ? '' : " AND `item`.`parent` = `item`.`id` ");
559         $sql_extra2 = (($nouveau) ? '' : $sql_extra2);
560         $sql_extra3 = (($nouveau) ? '' : $sql_extra3);
561         $sql_order = "";
562         $order_mode = "received";
563         $tag = false;
564
565         if(x($_GET,'search')) {
566                 $search = escape_tags($_GET['search']);
567
568                 if(strpos($search,'#') === 0) {
569                         $tag = true;
570                         $search = substr($search,1);
571                 }
572
573                 if (get_config('system','only_tag_search'))
574                         $tag = true;
575
576                 if($tag) {
577                         $sql_extra = "";
578
579                         $sql_post_table .= sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
580                                         dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(local_user()));
581                         $sql_order = "`item`.`id`";
582                         $order_mode = "id";
583                 } else {
584                         // Disabled until final decision what to do with this
585                         //if (get_config('system','use_fulltext_engine'))
586                         //      $sql_extra = sprintf(" AND MATCH (`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode) ", dbesc(protect_sprintf($search)));
587                         //else
588                                 $sql_extra = sprintf(" AND `item`.`body` REGEXP '%s' ", dbesc(protect_sprintf(preg_quote($search))));
589                         $sql_order = "`item`.`id`";
590                         $order_mode = "id";
591                 }
592         }
593         if(strlen($file)) {
594                 $sql_post_table .= sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
595                                 dbesc(protect_sprintf($file)), intval(TERM_OBJ_POST), intval(TERM_FILE), intval(local_user()));
596                 $sql_order = "`item`.`id`";
597                 $order_mode = "id";
598         }
599
600         if($conv)
601                 $sql_extra3 .= " AND $sql_table.`mention`";
602
603         if($update) {
604
605                 // only setup pagination on initial page view
606                 $pager_sql = '';
607
608         } else {
609                 //  check if we serve a mobile device and get the user settings
610                 //  accordingly
611                 if ($a->is_mobile) {
612                         $itemspage_network = get_pconfig(local_user(),'system','itemspage_mobile_network');
613                         $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 20);
614                 } else {
615                         $itemspage_network = get_pconfig(local_user(),'system','itemspage_network');
616                         $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 40);
617                 }
618
619                 //  now that we have the user settings, see if the theme forces
620                 //  a maximum item number which is lower then the user choice
621                 if(($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network))
622                         $itemspage_network = $a->force_max_items;
623
624                 $a->set_pager_itemspage($itemspage_network);
625                 $pager_sql = sprintf(" LIMIT %d, %d ",intval($a->pager['start']), intval($a->pager['itemspage']));
626         }
627
628         if($nouveau) {
629                 $simple_update = (($update) ? " AND `item`.`unseen` " : '');
630
631                 if ($sql_order == "")
632                         $sql_order = "`item`.`id`";
633
634                 // "New Item View" - show all items unthreaded in reverse created date order
635                 $items = qu("SELECT %s FROM $sql_table $sql_post_table %s
636                         WHERE %s AND `item`.`uid` = %d
637                         $simple_update
638                         $sql_extra $sql_nets
639                         ORDER BY $sql_order DESC $pager_sql ",
640                         item_fieldlists(), item_joins(), item_condition(),
641                         intval($_SESSION['uid'])
642                 );
643
644                 $update_unseen = ' WHERE uid = ' . intval($_SESSION['uid']) . " AND unseen = 1 $sql_extra $sql_nets";
645         } else {
646
647                 // Normal conversation view
648
649
650                 if($order === 'post') {
651                         $ordering = "`created`";
652                         if ($sql_order == "")
653                                 $order_mode = "created";
654                 } else {
655                         $ordering = "`commented`";
656                         if ($sql_order == "")
657                                 $order_mode = "commented";
658                 }
659
660                 if ($sql_order == "")
661                         $sql_order = "$sql_table.$ordering";
662
663                 if (($_GET["offset"] != ""))
664                         $sql_extra3 .= sprintf(" AND $sql_order <= '%s'", dbesc($_GET["offset"]));
665
666                 // Fetch a page full of parent items for this page
667                 if($update) {
668                         if (get_config("system", "like_no_comment"))
669                                 $sql_extra4 = " AND `item`.`verb` = '".ACTIVITY_POST."'";
670                         else
671                                 $sql_extra4 = "";
672
673                         $r = qu("SELECT `item`.`parent` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`uid` AS `contact_uid`
674                                 FROM $sql_table $sql_post_table INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
675                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
676                                 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted` $sql_extra4
677                                 AND NOT `item`.`moderated` AND `item`.`unseen`
678                                 $sql_extra3 $sql_extra $sql_nets
679                                 ORDER BY `item_id` DESC LIMIT 100",
680                                 intval(local_user())
681                         );
682                 } else {
683                         $r = qu("SELECT `thread`.`iid` AS `item_id`, `thread`.`network` AS `item_network`, `contact`.`uid` AS `contact_uid`
684                                 FROM $sql_table $sql_post_table STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
685                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
686                                 WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
687                                 AND NOT `thread`.`moderated`
688                                 $sql_extra2 $sql_extra3 $sql_extra $sql_nets
689                                 ORDER BY $sql_order DESC $pager_sql ",
690                                 intval(local_user())
691                         );
692                 }
693
694                 // Then fetch all the children of the parents that are on this page
695
696                 $parents_arr = array();
697                 $parents_str = '';
698                 $date_offset = "";
699
700                 if (dbm::is_result($r)) {
701                         foreach($r as $rr)
702                                 if(! in_array($rr['item_id'],$parents_arr))
703                                         $parents_arr[] = $rr['item_id'];
704
705                         $parents_str = implode(", ", $parents_arr);
706
707                         // splitted into separate queries to avoid the problem with very long threads
708                         // so always the last X comments are loaded
709                         // This problem can occur expecially with imported facebook posts
710                         $max_comments = get_config("system", "max_comments");
711                         if ($max_comments == 0)
712                                 $max_comments = 100;
713
714                         $items = array();
715
716                         foreach ($parents_arr AS $parents) {
717                                 $thread_items = qu(item_query()." AND `item`.`uid` = %d
718                                         AND `item`.`parent` = %d
719                                         ORDER BY `item`.`commented` DESC LIMIT %d",
720                                         intval(local_user()),
721                                         intval($parents),
722                                         intval($max_comments + 1)
723                                 );
724
725                                 if (dbm::is_result($thread_items))
726                                         $items = array_merge($items, $thread_items);
727                         }
728                         $items = conv_sort($items,$ordering);
729                 } else {
730                         $items = array();
731                 }
732
733                 if ($_GET["offset"] == "")
734                         $date_offset = $items[0][$order_mode];
735                 else
736                         $date_offset = $_GET["offset"];
737
738                 $a->page_offset = $date_offset;
739
740                 if($parents_str)
741                         $update_unseen = ' WHERE uid = ' . intval(local_user()) . ' AND unseen = 1 AND parent IN ( ' . dbesc($parents_str) . ' )';
742         }
743
744         // We aren't going to try and figure out at the item, group, and page
745         // level which items you've seen and which you haven't. If you're looking
746         // at the top level network page just mark everything seen.
747
748
749 // The $update_unseen is a bit unreliable if you have stuff coming into your stream from a new contact -
750 // and other feeds that bring in stuff from the past. One can't find it all.
751 // I'm reviving this block to mark everything seen on page 1 of the network as a temporary measure.
752 // The correct solution is to implement a network notifications box just like the system notifications popup
753 // with the ability in the popup to "mark all seen".
754 // Several people are complaining because there are unseen messages they can't find and as time goes
755 // on they just get buried deeper. It has happened to me a couple of times also.
756
757
758         if (!$group && !$cid && !$star) {
759
760                 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `uid` = %d LIMIT 1",
761                                 intval(local_user()));
762
763                 if (dbm::is_result($unseen)) {
764                         $r = q("UPDATE `item` SET `unseen` = 0
765                                 WHERE `unseen` = 1 AND `uid` = %d",
766                                 intval(local_user())
767                         );
768                 }
769         } elseif ($update_unseen) {
770
771                 $unseen = q("SELECT `id` FROM `item` ".$update_unseen. " LIMIT 1");
772
773                 if (dbm::is_result($unseen)) {
774                         $r = q("UPDATE `item` SET `unseen` = 0 $update_unseen");
775                 }
776         }
777
778         // Set this so that the conversation function can find out contact info for our wall-wall items
779         $a->page_contact = $a->contact;
780
781         $mode = (($nouveau) ? 'network-new' : 'network');
782
783         $o .= conversation($a, $items, $mode, $update);
784
785         if (!$update) {
786                 if (get_pconfig(local_user(), 'system', 'infinite_scroll')) {
787                         $o .= scroll_loader();
788                 } else {
789                         $o .= alt_pager($a, count($items));
790                 }
791         }
792
793         return $o;
794 }
795
796 /**
797  * @brief Get the network tabs menu
798  *
799  * @param app $a The global App
800  * @return string Html of the networktab
801  */
802 function network_tabs(App $a) {
803         // item filter tabs
804         /// @TODO fix this logic, reduce duplication
805         /// $a->page['content'] .= '<div class="tabs-wrapper">';
806
807         list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active) = network_query_get_sel_tab($a);
808         // if no tabs are selected, defaults to comments
809         if ($no_active=='active') $all_active='active';
810
811         $cmd = (($datequery) ? '' : $a->cmd);
812         $len_naked_cmd = strlen(str_replace('/new','',$cmd));
813
814         // tabs
815         $tabs = array(
816                 array(
817                         'label' => t('Commented Order'),
818                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
819                         'sel'   => $all_active,
820                         'title' => t('Sort by Comment Date'),
821                         'id'    => 'commented-order-tab',
822                         'accesskey' => "e",
823                 ),
824                 array(
825                         'label' => t('Posted Order'),
826                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
827                         'sel'   => $postord_active,
828                         'title' => t('Sort by Post Date'),
829                         'id'    => 'posted-order-tab',
830                         'accesskey' => "t",
831                 ),
832         );
833
834         if(feature_enabled(local_user(),'personal_tab')) {
835                 $tabs[] = array(
836                         'label' => t('Personal'),
837                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&conv=1',
838                         'sel'   => $conv_active,
839                         'title' => t('Posts that mention or involve you'),
840                         'id'    => 'personal-tab',
841                         'accesskey' => "r",
842                 );
843         }
844
845         if (feature_enabled(local_user(),'new_tab')) {
846                 $tabs[] = array(
847                         'label' => t('New'),
848                         'url'   => 'network/new' . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : ''),
849                         'sel'   => $new_active,
850                         'title' => t('Activity Stream - by date'),
851                         'id'    => 'activitiy-by-date-tab',
852                         'accesskey' => "w",
853                 );
854         }
855
856         if(feature_enabled(local_user(),'link_tab')) {
857                 $tabs[] = array(
858                         'label' => t('Shared Links'),
859                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&bmark=1',
860                         'sel'   => $bookmarked_active,
861                         'title' => t('Interesting Links'),
862                         'id'    => 'shared-links-tab',
863                         'accesskey' => "b",
864                 );
865         }
866
867         if(feature_enabled(local_user(),'star_posts')) {
868                 $tabs[] = array(
869                         'label' => t('Starred'),
870                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&star=1',
871                         'sel'   => $starred_active,
872                         'title' => t('Favourite Posts'),
873                         'id'    => 'starred-posts-tab',
874                         'accesskey' => "m",
875                 );
876         }
877
878         // save selected tab, but only if not in search or file mode
879         if(!x($_GET,'search') && !x($_GET,'file')) {
880                 set_pconfig( local_user(), 'network.view','tab.selected',array($all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active) );
881         }
882
883         $arr = array('tabs' => $tabs);
884         call_hooks('network_tabs', $arr);
885
886         $tpl = get_markup_template('common_tabs.tpl');
887
888         return replace_macros($tpl, array('$tabs' => $arr['tabs']));
889
890         // --- end item filter tabs
891 }