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