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