5 * Purpose: Friendship acceptance for DFRN contacts
7 * There are two possible entry points and three scenarios.
9 * 1. A form was submitted by our user approving a friendship that originated elsewhere.
10 * This may also be called from dfrn_request to automatically approve a friendship.
12 * 2. We may be the target or other side of the conversation to scenario 1, and will
13 * interact with that process on our own user's behalf.
17 require_once('include/enotify.php');
18 require_once('include/group.php');
19 require_once('include/Probe.php');
21 function dfrn_confirm_post(&$a,$handsfree = null) {
23 if(is_array($handsfree)) {
26 * We were called directly from dfrn_request due to automatic friend acceptance.
27 * Any $_POST parameters we may require are supplied in the $handsfree array.
31 $node = $handsfree['node'];
32 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
42 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
43 * from another site) and clicked 'Approve'.
44 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
46 * We may also have been called directly from dfrn_request ($handsfree != null) due to
47 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
48 * since we are operating on behalf of our registered user to approve a friendship.
52 if(! x($_POST,'source_url')) {
54 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
57 notice( t('Permission denied.') . EOL );
61 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
66 notice( t('Profile not found.') . EOL );
71 // These data elements may come from either the friend request notification form or $handsfree array.
73 if(is_array($handsfree)) {
74 logger('Confirm in handsfree mode');
75 $dfrn_id = $handsfree['dfrn_id'];
76 $intro_id = $handsfree['intro_id'];
77 $duplex = $handsfree['duplex'];
78 $hidden = ((array_key_exists('hidden',$handsfree)) ? intval($handsfree['hidden']) : 0 );
79 $activity = ((array_key_exists('activity',$handsfree)) ? intval($handsfree['activity']) : 0 );
82 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
83 $intro_id = ((x($_POST,'intro_id')) ? intval($_POST['intro_id']) : 0 );
84 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
85 $cid = ((x($_POST,'contact_id')) ? intval($_POST['contact_id']) : 0 );
86 $hidden = ((x($_POST,'hidden')) ? intval($_POST['hidden']) : 0 );
87 $activity = ((x($_POST,'activity')) ? intval($_POST['activity']) : 0 );
92 * Ensure that dfrn_id has precedence when we go to find the contact record.
93 * We only want to search based on contact id if there is no dfrn_id,
94 * e.g. for OStatus network followers.
101 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
103 logger('Confirming follower with contact_id: ' . $cid);
108 * The other person will have been issued an ID when they first requested friendship.
109 * Locate their record. At this time, their record will have both pending and blocked set to 1.
110 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
114 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d AND `duplex` = 0 LIMIT 1",
121 logger('Contact not found in DB.');
122 notice( t('Contact not found.') . EOL );
123 notice( t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL );
129 $contact_id = $contact['id'];
130 $relation = $contact['rel'];
131 $site_pubkey = $contact['site-pubkey'];
132 $dfrn_confirm = $contact['confirm'];
133 $aes_allow = $contact['aes_allow'];
135 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
137 if($contact['network'])
138 $network = $contact['network'];
140 if($network === NETWORK_DFRN) {
144 * Generate a key pair for all further communications with this person.
145 * We have a keypair for every contact, and a site key for unknown people.
146 * This provides a means to carry on relationships with other people if
147 * any single key is compromised. It is a robust key. We're much more
148 * worried about key leakage than anybody cracking it.
151 require_once('include/crypto.php');
153 $res = new_keypair(4096);
156 $private_key = $res['prvkey'];
157 $public_key = $res['pubkey'];
159 // Save the private key. Send them the public key.
161 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
171 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
172 * site private key (person on the other end can decrypt it with our site public key).
173 * Then encrypt our profile URL with the other person's site public key. They can decrypt
174 * it with their site private key. If the decryption on the other end fails for either
175 * item, it indicates tampering or key failure on at least one site and we will not be
176 * able to provide a secure communication pathway.
178 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
179 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
180 * random key which is encrypted with their site public key.
184 $src_aes_key = random_string();
187 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
189 $params['dfrn_id'] = bin2hex($result);
190 $params['public_key'] = $public_key;
193 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
195 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
196 $params['source_url'] = bin2hex($params['source_url']);
198 if($aes_allow && function_exists('openssl_encrypt')) {
199 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
200 $params['aes_key'] = bin2hex($params['aes_key']);
201 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
204 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
206 $params['duplex'] = 1;
208 if($user[0]['page-flags'] == PAGE_COMMUNITY)
210 if($user[0]['page-flags'] == PAGE_PRVGROUP)
213 logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
217 * POST all this stuff to the other site.
218 * Temporarily raise the network timeout to 120 seconds because the default 60
219 * doesn't always give the other side quite enough time to decrypt everything.
223 $a->config['system']['curl_timeout'] = 120;
225 $res = post_url($dfrn_confirm,$params);
227 logger(' Confirm: received data: ' . $res, LOGGER_DATA);
229 // Now figure out what they responded. Try to be robust if the remote site is
230 // having difficulty and throwing up errors of some kind.
232 $leading_junk = substr($res,0,strpos($res,'<?xml'));
234 $res = substr($res,strpos($res,'<?xml'));
237 // No XML at all, this exchange is messed up really bad.
238 // We shouldn't proceed, because the xml parser might choke,
239 // and $status is going to be zero, which indicates success.
240 // We can hardly call this a success.
242 notice( t('Response from remote site was not understood.') . EOL);
246 if(strlen($leading_junk) && get_config('system','debugging')) {
248 // This might be more common. Mixed error text and some XML.
249 // If we're configured for debugging, show the text. Proceed in either case.
251 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
254 if(stristr($res, "<status")===false) {
255 // wrong xml! stop here!
256 notice( t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL );
260 $xml = parse_xml_string($res);
261 $status = (int) $xml->status;
262 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
265 info( t("Confirmation completed successfully.") . EOL);
267 notice( t('Remote site reported: ') . $message . EOL);
270 // birthday paradox - generate new dfrn-id and fall through.
271 $new_dfrn_id = random_string();
272 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
279 notice( t("Temporary failure. Please wait and try again.") . EOL);
281 notice( t('Remote site reported: ') . $message . EOL);
286 notice( t("Introduction failed or was revoked.") . EOL);
288 notice( t('Remote site reported: ') . $message . EOL);
292 if(($status == 0) && ($intro_id)) {
294 // Success. Delete the notification.
296 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
310 * We have now established a relationship with the other site.
311 * Let's make our own personal copy of their profile photo so we don't have
312 * to always load it from their site.
314 * We will also update the contact record with the nature and scope of the relationship.
318 require_once('include/Photo.php');
320 update_contact_avatar($contact['photo'],$uid,$contact_id);
322 logger('dfrn_confirm: confirm - imported photos');
324 if($network === NETWORK_DFRN) {
326 $new_relation = CONTACT_IS_FOLLOWER;
327 if(($relation == CONTACT_IS_SHARING) || ($duplex))
328 $new_relation = CONTACT_IS_FRIEND;
330 if(($relation == CONTACT_IS_SHARING) && ($duplex))
333 $r = q("UPDATE `contact` SET `rel` = %d,
340 `network` = '%s' WHERE `id` = %d
342 intval($new_relation),
343 dbesc(datetime_convert()),
344 dbesc(datetime_convert()),
353 // $network !== NETWORK_DFRN
355 $network = (($contact['network']) ? $contact['network'] : NETWORK_OSTATUS);
356 $notify = (($contact['notify']) ? $contact['notify'] : '');
357 $poll = (($contact['poll']) ? $contact['poll'] : '');
359 if((! $contact['notify']) || (! $contact['poll'])) {
360 $arr = Probe::lrdd($contact['url']);
362 foreach($arr as $link) {
363 if($link['@attributes']['rel'] === 'salmon')
364 $notify = $link['@attributes']['href'];
365 if($link['@attributes']['rel'] === NAMESPACE_FEED)
366 $poll = $link['@attributes']['href'];
371 $new_relation = $contact['rel'];
372 $writable = $contact['writable'];
374 if($network === NETWORK_DIASPORA) {
376 $new_relation = CONTACT_IS_FRIEND;
378 $new_relation = CONTACT_IS_FOLLOWER;
380 if($new_relation != CONTACT_IS_FOLLOWER)
384 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
390 $r = q("UPDATE `contact` SET `name-date` = '%s',
402 dbesc(datetime_convert()),
403 dbesc(datetime_convert()),
409 intval($new_relation),
415 notice( t('Unable to set contact photo.') . EOL);
417 // reload contact info
419 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
428 if((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
430 if(($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
431 require_once('include/diaspora.php');
432 $ret = diaspora::send_share($user[0],$r[0]);
433 logger('share returns: ' . $ret);
436 // Send a new friend post if we are allowed to...
438 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
442 if((count($r)) && ($r[0]['hide-friends'] == 0) && ($activity) && (! $hidden)) {
444 require_once('include/items.php');
446 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
453 $arr['guid'] = get_guid(32);
454 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
456 $arr['contact-id'] = $self[0]['id'];
458 $arr['type'] = 'wall';
461 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
462 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
463 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
465 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
466 $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
468 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
469 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
471 $arr['verb'] = ACTIVITY_FRIEND;
472 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
473 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$BPhoto;
475 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
476 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
477 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
478 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
479 $arr['object'] .= '</link></object>' . "\n";
481 $arr['last-child'] = 1;
483 $arr['allow_cid'] = $user[0]['allow_cid'];
484 $arr['allow_gid'] = $user[0]['allow_gid'];
485 $arr['deny_cid'] = $user[0]['deny_cid'];
486 $arr['deny_gid'] = $user[0]['deny_gid'];
488 $i = item_store($arr);
490 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
495 $def_gid = get_default_group($uid, $contact["network"]);
496 if($contact && intval($def_gid))
497 group_add_member($uid, '', $contact['id'], $def_gid);
499 // Let's send our user to the contact editor in case they want to
500 // do anything special with this new friend.
502 if($handsfree === null)
503 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
512 * End of Scenario 1. [Local confirmation of remote friend request].
514 * Begin Scenario 2. This is the remote response to the above scenario.
515 * This will take place on the site that originally initiated the friend request.
516 * In the section above where the confirming party makes a POST and
517 * retrieves xml status information, they are communicating with the following code.
521 if(x($_POST,'source_url')) {
523 // We are processing an external confirmation to an introduction created by our user.
525 $public_key = ((x($_POST,'public_key')) ? $_POST['public_key'] : '');
526 $dfrn_id = ((x($_POST,'dfrn_id')) ? hex2bin($_POST['dfrn_id']) : '');
527 $source_url = ((x($_POST,'source_url')) ? hex2bin($_POST['source_url']) : '');
528 $aes_key = ((x($_POST,'aes_key')) ? $_POST['aes_key'] : '');
529 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
530 $page = ((x($_POST,'page')) ? intval($_POST['page']) : 0 );
531 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
533 $forum = (($page == 1) ? 1 : 0);
534 $prv = (($page == 2) ? 1 : 0);
536 logger('dfrn_confirm: requestee contacted: ' . $node);
538 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
540 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
543 $aes_key = hex2bin($aes_key);
544 $public_key = hex2bin($public_key);
547 // Find our user's account
549 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
553 $message = sprintf(t('No user record found for \'%s\' '), $node);
554 xml_status(3,$message); // failure
558 $my_prvkey = $r[0]['prvkey'];
559 $local_uid = $r[0]['uid'];
562 if(! strstr($my_prvkey,'PRIVATE KEY')) {
563 $message = t('Our site encryption key is apparently messed up.');
564 xml_status(3,$message);
569 $decrypted_source_url = "";
570 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
573 if(! strlen($decrypted_source_url)) {
574 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
575 xml_status(3,$message);
579 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
580 dbesc($decrypted_source_url),
584 if(strstr($decrypted_source_url,'http:'))
585 $newurl = str_replace('http:','https:',$decrypted_source_url);
587 $newurl = str_replace('https:','http:',$decrypted_source_url);
589 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
594 // this is either a bogus confirmation (?) or we deleted the original introduction.
595 $message = t('Contact record was not found for you on our site.');
596 xml_status(3,$message);
597 return; // NOTREACHED
601 $relation = $ret[0]['rel'];
603 // Decrypt all this stuff we just received
605 $foreign_pubkey = $ret[0]['site-pubkey'];
606 $dfrn_record = $ret[0]['id'];
608 if(! $foreign_pubkey) {
609 $message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl);
610 xml_status(3,$message);
613 $decrypted_dfrn_id = "";
614 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
616 if(strlen($aes_key)) {
617 $decrypted_aes_key = "";
618 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
619 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
622 $dfrn_pubkey = $public_key;
625 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
626 dbesc($decrypted_dfrn_id)
629 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
630 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
634 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
635 dbesc($decrypted_dfrn_id),
640 $message = t('Unable to set your contact credentials on our system.');
641 xml_status(3,$message);
644 // It's possible that the other person also requested friendship.
645 // If it is a duplex relationship, ditch the issued-id if one exists.
648 $r = q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
653 // We're good but now we have to scrape the profile photo and send notifications.
657 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
658 intval($dfrn_record));
661 $photo = $r[0]['photo'];
663 $photo = $a->get_baseurl() . '/images/person-175.jpg';
665 require_once("include/Photo.php");
667 update_contact_avatar($photo,$local_uid,$dfrn_record);
669 logger('dfrn_confirm: request - photos imported');
671 $new_relation = CONTACT_IS_SHARING;
672 if(($relation == CONTACT_IS_FOLLOWER) || ($duplex))
673 $new_relation = CONTACT_IS_FRIEND;
675 if(($relation == CONTACT_IS_FOLLOWER) && ($duplex))
678 $r = q("UPDATE `contact` SET
687 `network` = '%s' WHERE `id` = %d
689 intval($new_relation),
690 dbesc(datetime_convert()),
691 dbesc(datetime_convert()),
698 if($r === false) { // indicates schema is messed up or total db failure
699 $message = t('Unable to update your contact profile details on our system');
700 xml_status(3,$message);
703 // Otherwise everything seems to have worked and we are almost done. Yay!
704 // Send an email notification
706 logger('dfrn_confirm: request: info updated');
708 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
709 WHERE `contact`.`id` = %d LIMIT 1",
716 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
717 $mutual = ($new_relation == CONTACT_IS_FRIEND);
719 'type' => NOTIFY_CONFIRM,
720 'notify_flags' => $r[0]['notify-flags'],
721 'language' => $r[0]['language'],
722 'to_name' => $r[0]['username'],
723 'to_email' => $r[0]['email'],
724 'uid' => $r[0]['uid'],
725 'link' => $a->get_baseurl() . '/contacts/' . $dfrn_record,
726 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
727 'source_link' => $r[0]['url'],
728 'source_photo' => $r[0]['photo'],
729 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
734 // Send a new friend post if we are allowed to...
736 if($page && intval(get_pconfig($local_uid,'system','post_joingroup'))) {
737 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
741 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
743 require_once('include/items.php');
745 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
752 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
753 $arr['uid'] = $local_uid;
754 $arr['contact-id'] = $self[0]['id'];
756 $arr['type'] = 'wall';
759 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
760 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
761 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
763 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
764 $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
766 $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
767 $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
769 $arr['verb'] = ACTIVITY_JOIN;
770 $arr['object-type'] = ACTIVITY_OBJ_GROUP;
771 $arr['body'] = sprintf( t('%1$s has joined %2$s'), $A, $B)."\n\n\n" .$BPhoto;
772 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
773 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
774 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
775 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
776 $arr['object'] .= '</link></object>' . "\n";
778 $arr['last-child'] = 1;
780 $arr['allow_cid'] = $user[0]['allow_cid'];
781 $arr['allow_gid'] = $user[0]['allow_gid'];
782 $arr['deny_cid'] = $user[0]['deny_cid'];
783 $arr['deny_gid'] = $user[0]['deny_gid'];
785 $i = item_store($arr);
787 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
792 xml_status(0); // Success
793 return; // NOTREACHED
795 ////////////////////// End of this scenario ///////////////////////////////////////////////
798 // somebody arrived here by mistake or they are fishing. Send them to the homepage.