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