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