]> git.mxchange.org Git - friendica.git/blob - mod/contacts.php
Add Contact Object
[friendica.git] / mod / contacts.php
1 <?php
2
3 use Friendica\App;
4 use Friendica\Core\System;
5 use Friendica\Core\Worker;
6 use Friendica\Database\DBM;
7 use Friendica\Model\GlobalContact;
8 use Friendica\Network\Probe;
9 use Friendica\Object\Contact;
10
11 require_once 'include/Contact.php';
12 require_once 'include/contact_selectors.php';
13 require_once 'mod/proxy.php';
14 require_once 'include/Photo.php';
15
16 function contacts_init(App $a) {
17         if (! local_user()) {
18                 return;
19         }
20
21         $contact_id = 0;
22
23         if((($a->argc == 2) && intval($a->argv[1])) || (($a->argc == 3) && intval($a->argv[1]) && ($a->argv[2] == "posts"))) {
24                 $contact_id = intval($a->argv[1]);
25                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d and `id` = %d LIMIT 1",
26                         intval(local_user()),
27                         intval($contact_id)
28                 );
29                 if (! DBM::is_result($r)) {
30                         $contact_id = 0;
31                 }
32         }
33
34         require_once 'include/group.php';
35         require_once 'include/contact_widgets.php';
36
37         if ($_GET['nets'] == "all") {
38                 $_GET['nets'] = "";
39         }
40
41         if (! x($a->page,'aside')) {
42                 $a->page['aside'] = '';
43         }
44
45         if ($contact_id) {
46                 $a->data['contact'] = $r[0];
47
48                 if (($a->data['contact']['network'] != "") && ($a->data['contact']['network'] != NETWORK_DFRN)) {
49                         $networkname = format_network_name($a->data['contact']['network'],$a->data['contact']['url']);
50                 } else {
51                         $networkname = '';
52                 }
53
54                 /// @TODO Add nice spaces
55                 $vcard_widget = replace_macros(get_markup_template("vcard-widget.tpl"),array(
56                         '$name' => htmlentities($a->data['contact']['name']),
57                         '$photo' => $a->data['contact']['photo'],
58                         '$url' => ($a->data['contact']['network'] == NETWORK_DFRN) ? "redir/".$a->data['contact']['id'] : $a->data['contact']['url'],
59                         '$addr' => (($a->data['contact']['addr'] != "") ? ($a->data['contact']['addr']) : ""),
60                         '$network_name' => $networkname,
61                         '$network' => t('Network:'),
62                         '$account_type' => account_type($a->data['contact'])
63                 ));
64
65                 $finpeople_widget = '';
66                 $follow_widget = '';
67                 $networks_widget = '';
68         } else {
69                 $vcard_widget = '';
70                 $networks_widget .= networks_widget('contacts',$_GET['nets']);
71                 if (isset($_GET['add'])) {
72                         $follow_widget = follow_widget($_GET['add']);
73                 } else {
74                         $follow_widget = follow_widget();
75                 }
76
77                 $findpeople_widget .= findpeople_widget();
78         }
79
80         $groups_widget .= group_side('contacts','group','full',0,$contact_id);
81
82         $a->page['aside'] .= replace_macros(get_markup_template("contacts-widget-sidebar.tpl"),array(
83                 '$vcard_widget' => $vcard_widget,
84                 '$findpeople_widget' => $findpeople_widget,
85                 '$follow_widget' => $follow_widget,
86                 '$groups_widget' => $groups_widget,
87                 '$networks_widget' => $networks_widget
88         ));
89
90         $base = System::baseUrl();
91         $tpl = get_markup_template("contacts-head.tpl");
92         $a->page['htmlhead'] .= replace_macros($tpl,array(
93                 '$baseurl' => System::baseUrl(true),
94                 '$base' => $base
95         ));
96
97         $tpl = get_markup_template("contacts-end.tpl");
98         $a->page['end'] .= replace_macros($tpl,array(
99                 '$baseurl' => System::baseUrl(true),
100                 '$base' => $base
101         ));
102
103
104 }
105
106 function contacts_batch_actions(App $a) {
107         $contacts_id = $_POST['contact_batch'];
108         if (!is_array($contacts_id)) return;
109
110         $orig_records = q("SELECT * FROM `contact` WHERE `id` IN (%s) AND `uid` = %d AND `self` = 0",
111                 implode(",", $contacts_id),
112                 intval(local_user())
113         );
114
115         $count_actions=0;
116         foreach($orig_records as $orig_record) {
117                 $contact_id = $orig_record['id'];
118                 if (x($_POST, 'contacts_batch_update')) {
119                         _contact_update($contact_id);
120                         $count_actions++;
121                 }
122                 if (x($_POST, 'contacts_batch_block')) {
123                         $r  = _contact_block($contact_id, $orig_record);
124                         if ($r) $count_actions++;
125                 }
126                 if (x($_POST, 'contacts_batch_ignore')) {
127                         $r = _contact_ignore($contact_id, $orig_record);
128                         if ($r) $count_actions++;
129                 }
130                 if (x($_POST, 'contacts_batch_archive')) {
131                         $r = _contact_archive($contact_id, $orig_record);
132                         if ($r) $count_actions++;
133                 }
134                 if (x($_POST, 'contacts_batch_drop')) {
135                         _contact_drop($contact_id, $orig_record);
136                         $count_actions++;
137                 }
138         }
139         if ($count_actions>0) {
140                 info ( sprintf( tt("%d contact edited.", "%d contacts edited.", $count_actions), $count_actions) );
141         }
142
143         if (x($_SESSION,'return_url')) {
144                 goaway('' . $_SESSION['return_url']);
145         }
146         else {
147                 goaway('contacts');
148         }
149
150 }
151
152
153 function contacts_post(App $a) {
154
155         if (! local_user()) {
156                 return;
157         }
158
159         if ($a->argv[1]==="batch") {
160                 contacts_batch_actions($a);
161                 return;
162         }
163
164         $contact_id = intval($a->argv[1]);
165         if (! $contact_id) {
166                 return;
167         }
168
169         $orig_record = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
170                 intval($contact_id),
171                 intval(local_user())
172         );
173
174         if (! count($orig_record)) {
175                 notice( t('Could not access contact record.') . EOL);
176                 goaway('contacts');
177                 return; // NOTREACHED
178         }
179
180         call_hooks('contact_edit_post', $_POST);
181
182         $profile_id = intval($_POST['profile-assign']);
183         if ($profile_id) {
184                 $r = q("SELECT `id` FROM `profile` WHERE `id` = %d AND `uid` = %d LIMIT 1",
185                         intval($profile_id),
186                         intval(local_user())
187                 );
188                 if (! DBM::is_result($r)) {
189                         notice( t('Could not locate selected profile.') . EOL);
190                         return;
191                 }
192         }
193
194         $hidden = intval($_POST['hidden']);
195
196         $notify = intval($_POST['notify']);
197
198         $fetch_further_information = intval($_POST['fetch_further_information']);
199
200         $ffi_keyword_blacklist = escape_tags(trim($_POST['ffi_keyword_blacklist']));
201
202         $priority = intval($_POST['poll']);
203         if($priority > 5 || $priority < 0)
204                 $priority = 0;
205
206         $info = escape_tags(trim($_POST['info']));
207
208         $r = q("UPDATE `contact` SET `profile-id` = %d, `priority` = %d , `info` = '%s',
209                 `hidden` = %d, `notify_new_posts` = %d, `fetch_further_information` = %d,
210                 `ffi_keyword_blacklist` = '%s' WHERE `id` = %d AND `uid` = %d",
211                 intval($profile_id),
212                 intval($priority),
213                 dbesc($info),
214                 intval($hidden),
215                 intval($notify),
216                 intval($fetch_further_information),
217                 dbesc($ffi_keyword_blacklist),
218                 intval($contact_id),
219                 intval(local_user())
220         );
221         if($r)
222                 info( t('Contact updated.') . EOL);
223         else
224                 notice( t('Failed to update contact record.') . EOL);
225
226         $r = q("select * from contact where id = %d and uid = %d limit 1",
227                 intval($contact_id),
228                 intval(local_user())
229         );
230         if($r && DBM::is_result($r))
231                 $a->data['contact'] = $r[0];
232
233         return;
234
235 }
236
237 /*contact actions*/
238 function _contact_update($contact_id) {
239         $r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id));
240         if (!$r)
241                 return;
242
243         $uid = $r[0]["uid"];
244
245         if ($uid != local_user())
246                 return;
247
248         if ($r[0]["network"] == NETWORK_OSTATUS) {
249                 $result = new_contact($uid, $r[0]["url"], false, $r[0]["network"]);
250
251                 if ($result['success'])
252                         $r = q("UPDATE `contact` SET `subhub` = 1 WHERE `id` = %d",
253                                 intval($contact_id));
254         } else
255                 // pull feed and consume it, which should subscribe to the hub.
256                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
257 }
258
259 function _contact_update_profile($contact_id) {
260         $r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id));
261         if (!$r)
262                 return;
263
264         $uid = $r[0]["uid"];
265
266         if ($uid != local_user())
267                 return;
268
269         $data = Probe::uri($r[0]["url"], "", 0, false);
270
271         // "Feed" or "Unknown" is mostly a sign of communication problems
272         if ((in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM))) && ($data["network"] != $r[0]["network"]))
273                 return;
274
275         $updatefields = array("name", "nick", "url", "addr", "batch", "notify", "poll", "request", "confirm",
276                                 "poco", "network", "alias");
277         $update = array();
278
279         if ($data["network"] == NETWORK_OSTATUS) {
280                 $result = new_contact($uid, $data["url"], false);
281
282                 if ($result['success'])
283                         $update["subhub"] = true;
284         }
285
286         foreach($updatefields AS $field)
287                 if (isset($data[$field]) && ($data[$field] != ""))
288                         $update[$field] = $data[$field];
289
290         $update["nurl"] = normalise_link($data["url"]);
291
292         $query = "";
293
294         if (isset($data["priority"]) && ($data["priority"] != 0))
295                 $query = "`priority` = ".intval($data["priority"]);
296
297         foreach($update AS $key => $value) {
298                 if ($query != "")
299                         $query .= ", ";
300
301                 $query .= "`".$key."` = '".dbesc($value)."'";
302         }
303
304         if ($query == "")
305                 return;
306
307         $r = q("UPDATE `contact` SET $query WHERE `id` = %d AND `uid` = %d",
308                 intval($contact_id),
309                 intval(local_user())
310         );
311
312         // Update the entry in the contact table
313         update_contact_avatar($data['photo'], local_user(), $contact_id, true);
314
315         // Update the entry in the gcontact table
316         GlobalContact::updateFromProbe($data["url"]);
317 }
318
319 function _contact_block($contact_id, $orig_record) {
320         $blocked = (($orig_record['blocked']) ? 0 : 1);
321         $r = q("UPDATE `contact` SET `blocked` = %d WHERE `id` = %d AND `uid` = %d",
322                 intval($blocked),
323                 intval($contact_id),
324                 intval(local_user())
325         );
326         return $r;
327
328 }
329 function _contact_ignore($contact_id, $orig_record) {
330         $readonly = (($orig_record['readonly']) ? 0 : 1);
331         $r = q("UPDATE `contact` SET `readonly` = %d WHERE `id` = %d AND `uid` = %d",
332                 intval($readonly),
333                 intval($contact_id),
334                 intval(local_user())
335         );
336         return $r;
337 }
338 function _contact_archive($contact_id, $orig_record) {
339         $archived = (($orig_record['archive']) ? 0 : 1);
340         $r = q("UPDATE `contact` SET `archive` = %d WHERE `id` = %d AND `uid` = %d",
341                 intval($archived),
342                 intval($contact_id),
343                 intval(local_user())
344         );
345         if ($archived) {
346                 q("UPDATE `item` SET `private` = 2 WHERE `contact-id` = %d AND `uid` = %d", intval($contact_id), intval(local_user()));
347         }
348         return $r;
349 }
350 function _contact_drop($contact_id, $orig_record) {
351         $a = get_app();
352
353         $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
354                 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
355                 intval($a->user['uid'])
356         );
357         if (!DBM::is_result($r)) {
358                 return;
359         }
360
361         $self = ""; // Unused parameter
362         terminate_friendship($r[0], $self, $orig_record);
363         contact_remove($orig_record['id']);
364 }
365
366
367 function contacts_content(App $a) {
368
369         $sort_type = 0;
370         $o = '';
371         nav_set_selected('contacts');
372
373
374         if (! local_user()) {
375                 notice( t('Permission denied.') . EOL);
376                 return;
377         }
378
379         if($a->argc == 3) {
380
381                 $contact_id = intval($a->argv[1]);
382                 if(! $contact_id)
383                         return;
384
385                 $cmd = $a->argv[2];
386
387                 $orig_record = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d AND `self` = 0 LIMIT 1",
388                         intval($contact_id),
389                         intval(local_user())
390                 );
391
392                 if(! count($orig_record)) {
393                         notice( t('Could not access contact record.') . EOL);
394                         goaway('contacts');
395                         return; // NOTREACHED
396                 }
397
398                 if($cmd === 'update') {
399                         _contact_update($contact_id);
400                         goaway('contacts/' . $contact_id);
401                         // NOTREACHED
402                 }
403
404                 if($cmd === 'updateprofile') {
405                         _contact_update_profile($contact_id);
406                         goaway('crepair/' . $contact_id);
407                         // NOTREACHED
408                 }
409
410                 if($cmd === 'block') {
411                         $r = _contact_block($contact_id, $orig_record[0]);
412                         if ($r) {
413                                 $blocked = (($orig_record[0]['blocked']) ? 0 : 1);
414                                 info((($blocked) ? t('Contact has been blocked') : t('Contact has been unblocked')).EOL);
415                         }
416
417                         goaway('contacts/' . $contact_id);
418                         return; // NOTREACHED
419                 }
420
421                 if($cmd === 'ignore') {
422                         $r = _contact_ignore($contact_id, $orig_record[0]);
423                         if ($r) {
424                                 $readonly = (($orig_record[0]['readonly']) ? 0 : 1);
425                                 info((($readonly) ? t('Contact has been ignored') : t('Contact has been unignored')).EOL);
426                         }
427
428                         goaway('contacts/' . $contact_id);
429                         return; // NOTREACHED
430                 }
431
432
433                 if($cmd === 'archive') {
434                         $r = _contact_archive($contact_id, $orig_record[0]);
435                         if ($r) {
436                                 $archived = (($orig_record[0]['archive']) ? 0 : 1);
437                                 info((($archived) ? t('Contact has been archived') : t('Contact has been unarchived')).EOL);
438                         }
439
440                         goaway('contacts/' . $contact_id);
441                         return; // NOTREACHED
442                 }
443
444                 if($cmd === 'drop') {
445
446                         // Check if we should do HTML-based delete confirmation
447                         if($_REQUEST['confirm']) {
448                                 // <form> can't take arguments in its "action" parameter
449                                 // so add any arguments as hidden inputs
450                                 $query = explode_querystring($a->query_string);
451                                 $inputs = array();
452                                 foreach($query['args'] as $arg) {
453                                         if(strpos($arg, 'confirm=') === false) {
454                                                 $arg_parts = explode('=', $arg);
455                                                 $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
456                                         }
457                                 }
458
459                                 $a->page['aside'] = '';
460
461                                 return replace_macros(get_markup_template('contact_drop_confirm.tpl'), array(
462                                         '$header' => t('Drop contact'),
463                                         '$contact' => _contact_detail_for_template($orig_record[0]),
464                                         '$method' => 'get',
465                                         '$message' => t('Do you really want to delete this contact?'),
466                                         '$extra_inputs' => $inputs,
467                                         '$confirm' => t('Yes'),
468                                         '$confirm_url' => $query['base'],
469                                         '$confirm_name' => 'confirmed',
470                                         '$cancel' => t('Cancel'),
471                                 ));
472                         }
473                         // Now check how the user responded to the confirmation query
474                         if ($_REQUEST['canceled']) {
475                                 if (x($_SESSION,'return_url')) {
476                                         goaway('' . $_SESSION['return_url']);
477                                 }
478                                 else {
479                                         goaway('contacts');
480                                 }
481                         }
482
483                         _contact_drop($contact_id, $orig_record[0]);
484                         info( t('Contact has been removed.') . EOL );
485                         if (x($_SESSION,'return_url')) {
486                                 goaway('' . $_SESSION['return_url']);
487                         }
488                         else {
489                                 goaway('contacts');
490                         }
491                         return; // NOTREACHED
492                 }
493                 if ($cmd === 'posts') {
494                         return contact_posts($a, $contact_id);
495                 }
496         }
497
498
499
500         $_SESSION['return_url'] = $a->query_string;
501
502         if((x($a->data,'contact')) && (is_array($a->data['contact']))) {
503
504                 $contact_id = $a->data['contact']['id'];
505                 $contact = $a->data['contact'];
506
507                 $a->page['htmlhead'] .= replace_macros(get_markup_template('contact_head.tpl'), array(
508                         '$baseurl' => System::baseUrl(true),
509                 ));
510                 $a->page['end'] .= replace_macros(get_markup_template('contact_end.tpl'), array(
511                         '$baseurl' => System::baseUrl(true),
512                 ));
513
514                 require_once 'include/contact_selectors.php';
515
516                 $tpl = get_markup_template("contact_edit.tpl");
517
518                 switch($contact['rel']) {
519                         case CONTACT_IS_FRIEND:
520                                 $dir_icon = 'images/lrarrow.gif';
521                                 $relation_text = t('You are mutual friends with %s');
522                                 break;
523                         case CONTACT_IS_FOLLOWER;
524                                 $dir_icon = 'images/larrow.gif';
525                                 $relation_text = t('You are sharing with %s');
526                                 break;
527
528                         case CONTACT_IS_SHARING;
529                                 $dir_icon = 'images/rarrow.gif';
530                                 $relation_text = t('%s is sharing with you');
531                                 break;
532                         default:
533                                 break;
534                 }
535
536                 if(!in_array($contact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
537                                 $relation_text = "";
538
539                 $relation_text = sprintf($relation_text,htmlentities($contact['name']));
540
541                 if(($contact['network'] === NETWORK_DFRN) && ($contact['rel'])) {
542                         $url = "redir/{$contact['id']}";
543                         $sparkle = ' class="sparkle" ';
544                 }
545                 else {
546                         $url = $contact['url'];
547                         $sparkle = '';
548                 }
549
550                 $insecure = t('Private communications are not available for this contact.');
551
552                 $last_update = (($contact['last-update'] <= NULL_DATE)
553                                 ? t('Never')
554                                 : datetime_convert('UTC',date_default_timezone_get(),$contact['last-update'],'D, j M Y, g:i A'));
555
556                 if ($contact['last-update'] > NULL_DATE) {
557                         $last_update .= ' ' . (($contact['last-update'] <= $contact['success_update']) ? t("\x28Update was successful\x29") : t("\x28Update was not successful\x29"));
558                 }
559                 $lblsuggest = (($contact['network'] === NETWORK_DFRN) ? t('Suggest friends') : '');
560
561                 $poll_enabled = in_array($contact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_FEED, NETWORK_MAIL, NETWORK_MAIL2));
562
563                 $nettype = sprintf( t('Network type: %s'),network_to_name($contact['network'], $contact["url"]));
564
565                 //$common = GlobalContact::countCommonFriends(local_user(),$contact['id']);
566                 //$common_text = (($common) ? sprintf( tt('%d contact in common','%d contacts in common', $common),$common) : '');
567
568                 $polling = (($contact['network'] === NETWORK_MAIL | $contact['network'] === NETWORK_FEED) ? 'polling' : '');
569
570                 //$x = GlobalContact::countAllFriends(local_user(), $contact['id']);
571                 //$all_friends = (($x) ? t('View all contacts') : '');
572
573                 // tabs
574                 $tab_str = contacts_tab($a, $contact_id, 2);
575
576                 $lost_contact = (($contact['archive'] && $contact['term-date'] > NULL_DATE && $contact['term-date'] < datetime_convert('','','now')) ? t('Communications lost with this contact!') : '');
577
578                 if ($contact['network'] == NETWORK_FEED) {
579                         $fetch_further_information = array('fetch_further_information', t('Fetch further information for feeds'), $contact['fetch_further_information'], t('Fetch further information for feeds'),
580                                                                         array('0'=>t('Disabled'), '1'=>t('Fetch information'), '2'=>t('Fetch information and keywords')));
581                 }
582                 if (in_array($contact['network'], array(NETWORK_FEED, NETWORK_MAIL, NETWORK_MAIL2)))
583                         $poll_interval = contact_poll_interval($contact['priority'],(! $poll_enabled));
584
585                 if ($contact['network'] == NETWORK_DFRN)
586                         $profile_select = contact_profile_assign($contact['profile-id'],(($contact['network'] !== NETWORK_DFRN) ? true : false));
587
588                 if (in_array($contact['network'], array(NETWORK_DIASPORA, NETWORK_OSTATUS))) {
589                         if ($contact['rel'] == CONTACT_IS_FOLLOWER) {
590                                 $follow = System::baseUrl(true)."/follow?url=".urlencode($contact["url"]);
591                                 $follow_text = t("Connect/Follow");
592                         } elseif ($contact['rel'] == CONTACT_IS_FRIEND) {
593                                 $follow = System::baseUrl(true)."/unfollow?url=".urlencode($contact["url"]);
594                                 $follow_text = t("Disconnect/Unfollow");
595                         }
596                 }
597
598                 // Load contactact related actions like hide, suggest, delete and others
599                 $contact_actions = contact_actions($contact);
600
601
602                 $o .= replace_macros($tpl, array(
603                         //'$header' => t('Contact Editor'),
604                         '$header' => t("Contact"),
605                         '$tab_str' => $tab_str,
606                         '$submit' => t('Submit'),
607                         '$lbl_vis1' => t('Profile Visibility'),
608                         '$lbl_vis2' => sprintf( t('Please choose the profile you would like to display to %s when viewing your profile securely.'), $contact['name']),
609                         '$lbl_info1' => t('Contact Information / Notes'),
610                         '$lbl_info2' => t('Their personal note'),
611                         '$reason' => trim(notags($contact['reason'])),
612                         '$infedit' => t('Edit contact notes'),
613                         '$common_text' => $common_text,
614                         '$common_link' => 'common/loc/' . local_user() . '/' . $contact['id'],
615                         '$all_friends' => $all_friends,
616                         '$relation_text' => $relation_text,
617                         '$visit' => sprintf( t('Visit %s\'s profile [%s]'),$contact['name'],$contact['url']),
618                         '$blockunblock' => t('Block/Unblock contact'),
619                         '$ignorecont' => t('Ignore contact'),
620                         '$lblcrepair' => t("Repair URL settings"),
621                         '$lblrecent' => t('View conversations'),
622                         '$lblsuggest' => $lblsuggest,
623                         //'$delete' => t('Delete contact'),
624                         '$nettype' => $nettype,
625                         '$poll_interval' => $poll_interval,
626                         '$poll_enabled' => $poll_enabled,
627                         '$lastupdtext' => t('Last update:'),
628                         '$lost_contact' => $lost_contact,
629                         '$updpub' => t('Update public posts'),
630                         '$last_update' => $last_update,
631                         '$udnow' => t('Update now'),
632                         '$follow' => $follow,
633                         '$follow_text' => $follow_text,
634                         '$profile_select' => $profile_select,
635                         '$contact_id' => $contact['id'],
636                         '$block_text' => (($contact['blocked']) ? t('Unblock') : t('Block') ),
637                         '$ignore_text' => (($contact['readonly']) ? t('Unignore') : t('Ignore') ),
638                         '$insecure' => (($contact['network'] !== NETWORK_DFRN && $contact['network'] !== NETWORK_MAIL && $contact['network'] !== NETWORK_FACEBOOK && $contact['network'] !== NETWORK_DIASPORA) ? $insecure : ''),
639                         '$info' => $contact['info'],
640                         '$cinfo' => array('info', '', $contact['info'], ''),
641                         '$blocked' => (($contact['blocked']) ? t('Currently blocked') : ''),
642                         '$ignored' => (($contact['readonly']) ? t('Currently ignored') : ''),
643                         '$archived' => (($contact['archive']) ? t('Currently archived') : ''),
644                         '$hidden' => array('hidden', t('Hide this contact from others'), ($contact['hidden'] == 1), t('Replies/likes to your public posts <strong>may</strong> still be visible')),
645                         '$notify' => array('notify', t('Notification for new posts'), ($contact['notify_new_posts'] == 1), t('Send a notification of every new post of this contact')),
646                         '$fetch_further_information' => $fetch_further_information,
647                         '$ffi_keyword_blacklist' => $contact['ffi_keyword_blacklist'],
648                         '$ffi_keyword_blacklist' => array('ffi_keyword_blacklist', t('Blacklisted keywords'), $contact['ffi_keyword_blacklist'], t('Comma separated list of keywords that should not be converted to hashtags, when "Fetch information and keywords" is selected')),
649                         '$photo' => $contact['photo'],
650                         '$name' => htmlentities($contact['name']),
651                         '$dir_icon' => $dir_icon,
652                         '$alt_text' => $alt_text,
653                         '$sparkle' => $sparkle,
654                         '$url' => $url,
655                         '$profileurllabel' => t('Profile URL'),
656                         '$profileurl' => $contact['url'],
657                         '$account_type' => account_type($contact),
658                         '$location' => bbcode($contact["location"]),
659                         '$location_label' => t("Location:"),
660                         '$xmpp' => bbcode($contact["xmpp"]),
661                         '$xmpp_label' => t("XMPP:"),
662                         '$about' => bbcode($contact["about"], false, false),
663                         '$about_label' => t("About:"),
664                         '$keywords' => $contact["keywords"],
665                         '$keywords_label' => t("Tags:"),
666                         '$contact_action_button' => t("Actions"),
667                         '$contact_actions' => $contact_actions,
668                         '$contact_status' => t("Status"),
669                         '$contact_settings_label' => t('Contact Settings'),
670                         '$contact_profile_label' => t("Profile"),
671
672                 ));
673
674                 $arr = array('contact' => $contact,'output' => $o);
675
676                 call_hooks('contact_edit', $arr);
677
678                 return $arr['output'];
679
680         }
681
682         $blocked = false;
683         $hidden = false;
684         $ignored = false;
685         $all = false;
686
687         if(($a->argc == 2) && ($a->argv[1] === 'all')) {
688                 $sql_extra = '';
689                 $all = true;
690         }
691         elseif(($a->argc == 2) && ($a->argv[1] === 'blocked')) {
692                 $sql_extra = " AND `blocked` = 1 ";
693                 $blocked = true;
694         }
695         elseif(($a->argc == 2) && ($a->argv[1] === 'hidden')) {
696                 $sql_extra = " AND `hidden` = 1 ";
697                 $hidden = true;
698         }
699         elseif(($a->argc == 2) && ($a->argv[1] === 'ignored')) {
700                 $sql_extra = " AND `readonly` = 1 ";
701                 $ignored = true;
702         }
703         elseif(($a->argc == 2) && ($a->argv[1] === 'archived')) {
704                 $sql_extra = " AND `archive` = 1 ";
705                 $archived = true;
706         }
707         else
708                 $sql_extra = " AND `blocked` = 0 ";
709
710         $search = ((x($_GET,'search')) ? notags(trim($_GET['search'])) : '');
711         $nets = ((x($_GET,'nets')) ? notags(trim($_GET['nets'])) : '');
712
713         $tabs = array(
714                 array(
715                         'label' => t('Suggestions'),
716                         'url'   => 'suggest',
717                         'sel'   => '',
718                         'title' => t('Suggest potential friends'),
719                         'id'    => 'suggestions-tab',
720                         'accesskey' => 'g',
721                 ),
722                 array(
723                         'label' => t('All Contacts'),
724                         'url'   => 'contacts/all',
725                         'sel'   => ($all) ? 'active' : '',
726                         'title' => t('Show all contacts'),
727                         'id'    => 'showall-tab',
728                         'accesskey' => 'l',
729                 ),
730                 array(
731                         'label' => t('Unblocked'),
732                         'url'   => 'contacts',
733                         'sel'   => ((! $all) && (! $blocked) && (! $hidden) && (! $search) && (! $nets) && (! $ignored) && (! $archived)) ? 'active' : '',
734                         'title' => t('Only show unblocked contacts'),
735                         'id'    => 'showunblocked-tab',
736                         'accesskey' => 'o',
737                 ),
738
739                 array(
740                         'label' => t('Blocked'),
741                         'url'   => 'contacts/blocked',
742                         'sel'   => ($blocked) ? 'active' : '',
743                         'title' => t('Only show blocked contacts'),
744                         'id'    => 'showblocked-tab',
745                         'accesskey' => 'b',
746                 ),
747
748                 array(
749                         'label' => t('Ignored'),
750                         'url'   => 'contacts/ignored',
751                         'sel'   => ($ignored) ? 'active' : '',
752                         'title' => t('Only show ignored contacts'),
753                         'id'    => 'showignored-tab',
754                         'accesskey' => 'i',
755                 ),
756
757                 array(
758                         'label' => t('Archived'),
759                         'url'   => 'contacts/archived',
760                         'sel'   => ($archived) ? 'active' : '',
761                         'title' => t('Only show archived contacts'),
762                         'id'    => 'showarchived-tab',
763                         'accesskey' => 'y',
764                 ),
765
766                 array(
767                         'label' => t('Hidden'),
768                         'url'   => 'contacts/hidden',
769                         'sel'   => ($hidden) ? 'active' : '',
770                         'title' => t('Only show hidden contacts'),
771                         'id'    => 'showhidden-tab',
772                         'accesskey' => 'h',
773                 ),
774
775         );
776
777         $tab_tpl = get_markup_template('common_tabs.tpl');
778         $t = replace_macros($tab_tpl, array('$tabs'=>$tabs));
779
780
781
782         $searching = false;
783         if($search) {
784                 $search_hdr = $search;
785                 $search_txt = dbesc(protect_sprintf(preg_quote($search)));
786                 $searching = true;
787         }
788         $sql_extra .= (($searching) ? " AND (name REGEXP '$search_txt' OR url REGEXP '$search_txt'  OR nick REGEXP '$search_txt') " : "");
789
790         if($nets)
791                 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($nets));
792
793         $sql_extra2 = ((($sort_type > 0) && ($sort_type <= CONTACT_IS_FRIEND)) ? sprintf(" AND `rel` = %d ",intval($sort_type)) : '');
794
795
796         $r = q("SELECT COUNT(*) AS `total` FROM `contact`
797                 WHERE `uid` = %d AND `self` = 0 AND `pending` = 0 $sql_extra $sql_extra2 ",
798                 intval($_SESSION['uid']));
799         if (DBM::is_result($r)) {
800                 $a->set_pager_total($r[0]['total']);
801                 $total = $r[0]['total'];
802         }
803
804         $sql_extra3 = unavailable_networks();
805
806         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `pending` = 0 $sql_extra $sql_extra2 $sql_extra3 ORDER BY `name` ASC LIMIT %d , %d ",
807                 intval($_SESSION['uid']),
808                 intval($a->pager['start']),
809                 intval($a->pager['itemspage'])
810         );
811
812         $contacts = array();
813
814         if (DBM::is_result($r)) {
815                 foreach ($r as $rr) {
816                         $contacts[] = _contact_detail_for_template($rr);
817                 }
818         }
819
820         $tpl = get_markup_template("contacts-template.tpl");
821         $o .= replace_macros($tpl, array(
822                 '$baseurl' => System::baseUrl(),
823                 '$header' => t('Contacts') . (($nets) ? ' - ' . network_to_name($nets) : ''),
824                 '$tabs' => $t,
825                 '$total' => $total,
826                 '$search' => $search_hdr,
827                 '$desc' => t('Search your contacts'),
828                 '$finding' => (($searching) ? sprintf(t('Results for: %s'),$search) : ""),
829                 '$submit' => t('Find'),
830                 '$cmd' => $a->cmd,
831                 '$contacts' => $contacts,
832                 '$contact_drop_confirm' => t('Do you really want to delete this contact?'),
833                 'multiselect' => 1,
834                 '$batch_actions' => array(
835                         'contacts_batch_update' => t('Update'),
836                         'contacts_batch_block' => t('Block')."/".t("Unblock"),
837                         "contacts_batch_ignore" => t('Ignore')."/".t("Unignore"),
838                         "contacts_batch_archive" => t('Archive')."/".t("Unarchive"),
839                         "contacts_batch_drop" => t('Delete'),
840                 ),
841                 '$h_batch_actions' => t('Batch Actions'),
842                 '$paginate' => paginate($a),
843
844         ));
845
846         return $o;
847 }
848
849 /**
850  * @brief List of pages for the Contact TabBar
851  *
852  * Available Pages are 'Status', 'Profile', 'Contacts' and 'Common Friends'
853  *
854  * @param App $a
855  * @param int $contact_id The ID of the contact
856  * @param int $active_tab 1 if tab should be marked as active
857  *
858  * @return array with with contact TabBar data
859  */
860 function contacts_tab($a, $contact_id, $active_tab) {
861         // tabs
862         $tabs = array(
863                 array(
864                         'label'=>t('Status'),
865                         'url' => "contacts/".$contact_id."/posts",
866                         'sel' => (($active_tab == 1)?'active':''),
867                         'title' => t('Status Messages and Posts'),
868                         'id' => 'status-tab',
869                         'accesskey' => 'm',
870                 ),
871                 array(
872                         'label'=>t('Profile'),
873                         'url' => "contacts/".$contact_id,
874                         'sel' => (($active_tab == 2)?'active':''),
875                         'title' => t('Profile Details'),
876                         'id' => 'profile-tab',
877                         'accesskey' => 'o',
878                 )
879         );
880
881         // Show this tab only if there is visible friend list
882         $x = GlobalContact::countAllFriends(local_user(), $contact_id);
883         if ($x)
884                 $tabs[] = array('label'=>t('Contacts'),
885                                 'url' => "allfriends/".$contact_id,
886                                 'sel' => (($active_tab == 3)?'active':''),
887                                 'title' => t('View all contacts'),
888                                 'id' => 'allfriends-tab',
889                                 'accesskey' => 't');
890
891         // Show this tab only if there is visible common friend list
892         $common = GlobalContact::countCommonFriends(local_user(), $contact_id);
893         if ($common)
894                 $tabs[] = array('label'=>t('Common Friends'),
895                                 'url' => "common/loc/".local_user()."/".$contact_id,
896                                 'sel' => (($active_tab == 4)?'active':''),
897                                 'title' => t('View all common friends'),
898                                 'id' => 'common-loc-tab',
899                                 'accesskey' => 'd');
900
901         $tabs[] = array('label' => t('Advanced'),
902                         'url'   => 'crepair/' . $contact_id,
903                         'sel' => (($active_tab == 5)?'active':''),
904                         'title' => t('Advanced Contact Settings'),
905                         'id'    => 'advanced-tab',
906                         'accesskey' => 'r');
907
908         $tab_tpl = get_markup_template('common_tabs.tpl');
909         $tab_str = replace_macros($tab_tpl, array('$tabs' => $tabs));
910
911         return $tab_str;
912 }
913
914 function contact_posts($a, $contact_id) {
915
916         $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id));
917         if ($r) {
918                 $contact = $r[0];
919                 $a->page['aside'] = "";
920                 profile_load($a, "", 0, get_contact_details_by_url($contact["url"]));
921         } else
922                 $profile = "";
923
924         $tab_str = contacts_tab($a, $contact_id, 1);
925
926         $o .= $tab_str;
927
928         $o .= posts_from_contact_url($a, $contact["url"]);
929
930         return $o;
931 }
932
933 function _contact_detail_for_template($rr){
934
935         switch($rr['rel']) {
936                 case CONTACT_IS_FRIEND:
937                         $dir_icon = 'images/lrarrow.gif';
938                         $alt_text = t('Mutual Friendship');
939                         break;
940                 case  CONTACT_IS_FOLLOWER;
941                         $dir_icon = 'images/larrow.gif';
942                         $alt_text = t('is a fan of yours');
943                         break;
944                 case CONTACT_IS_SHARING;
945                         $dir_icon = 'images/rarrow.gif';
946                         $alt_text = t('you are a fan of');
947                         break;
948                 default:
949                         break;
950         }
951         if(($rr['network'] === NETWORK_DFRN) && ($rr['rel'])) {
952                 $url = "redir/{$rr['id']}";
953                 $sparkle = ' class="sparkle" ';
954         }
955         else {
956                 $url = $rr['url'];
957                 $sparkle = '';
958         }
959
960         return array(
961                 'img_hover' => sprintf( t('Visit %s\'s profile [%s]'),$rr['name'],$rr['url']),
962                 'edit_hover' => t('Edit contact'),
963                 'photo_menu' => contact_photo_menu($rr),
964                 'id' => $rr['id'],
965                 'alt_text' => $alt_text,
966                 'dir_icon' => $dir_icon,
967                 'thumb' => proxy_url($rr['thumb'], false, PROXY_SIZE_THUMB),
968                 'name' => htmlentities($rr['name']),
969                 'username' => htmlentities($rr['name']),
970                 'account_type' => account_type($rr),
971                 'sparkle' => $sparkle,
972                 'itemurl' => (($rr['addr'] != "") ? $rr['addr'] : $rr['url']),
973                 'url' => $url,
974                 'network' => network_to_name($rr['network'], $rr['url']),
975         );
976
977 }
978
979 /**
980  * @brief Gives a array with actions which can performed to a given contact
981  *
982  * This includes actions like e.g. 'block', 'hide', 'archive', 'delete' and others
983  *
984  * @param array $contact Data about the Contact
985  * @return array with contact related actions
986  */
987 function contact_actions($contact) {
988
989         $poll_enabled = in_array($contact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_FEED, NETWORK_MAIL, NETWORK_MAIL2));
990         $contact_action = array();
991
992         // Provide friend suggestion only for Friendica contacts
993         if($contact['network'] === NETWORK_DFRN) {
994                 $contact_actions['suggest'] = array(
995                                                         'label' => t('Suggest friends'),
996                                                         'url'   => 'fsuggest/' . $contact['id'],
997                                                         'title' => '',
998                                                         'sel'   => '',
999                                                         'id'    =>  'suggest',
1000                                         );
1001         }
1002
1003         if($poll_enabled) {
1004                 $contact_actions['update'] = array(
1005                                                         'label' => t('Update now'),
1006                                                         'url'   => 'contacts/' . $contact['id'] . '/update',
1007                                                         'title' => '',
1008                                                         'sel'   => '',
1009                                                         'id'    => 'update',
1010                                         );
1011         }
1012
1013         $contact_actions['block'] = array(
1014                                                 'label' => (intval($contact['blocked']) ? t('Unblock') : t('Block') ),
1015                                                 'url'   => 'contacts/' . $contact['id'] . '/block',
1016                                                 'title' => t('Toggle Blocked status'),
1017                                                 'sel'   => (intval($contact['blocked']) ? 'active' : ''),
1018                                                 'id'    => 'toggle-block',
1019                                 );
1020
1021         $contact_actions['ignore'] = array(
1022                                                 'label' => (intval($contact['readonly']) ? t('Unignore') : t('Ignore') ),
1023                                                 'url'   => 'contacts/' . $contact['id'] . '/ignore',
1024                                                 'title' => t('Toggle Ignored status'),
1025                                                 'sel'   => (intval($contact['readonly']) ? 'active' : ''),
1026                                                 'id'    => 'toggle-ignore',
1027                                 );
1028
1029         $contact_actions['archive'] = array(
1030                                                 'label' => (intval($contact['archive']) ? t('Unarchive') : t('Archive') ),
1031                                                 'url'   => 'contacts/' . $contact['id'] . '/archive',
1032                                                 'title' => t('Toggle Archive status'),
1033                                                 'sel'   => (intval($contact['archive']) ? 'active' : ''),
1034                                                 'id'    => 'toggle-archive',
1035                                 );
1036
1037         $contact_actions['delete'] = array(
1038                                                 'label' => t('Delete'),
1039                                                 'url'   => 'contacts/' . $contact['id'] . '/drop',
1040                                                 'title' => t('Delete contact'),
1041                                                 'sel'   => '',
1042                                                 'id'    => 'delete',
1043                                 );
1044
1045         return $contact_actions;
1046 }