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