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