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