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 function dfrn_confirm_post(&$a,$handsfree = null) {
19 if(is_array($handsfree)) {
22 * We were called directly from dfrn_request due to automatic friend acceptance.
23 * Any $_POST parameters we may require are supplied in the $handsfree array.
27 $node = $handsfree['node'];
28 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
38 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
39 * from another site) and clicked 'Approve'.
40 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
42 * We may also have been called directly from dfrn_request ($handsfree != null) due to
43 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
44 * since we are operating on behalf of our registered user to approve a friendship.
48 if(! x($_POST,'source_url')) {
50 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
53 notice( t('Permission denied.') . EOL );
57 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
62 notice( t('Profile not found.') . EOL );
67 // These data elements may come from either the friend request notification form or $handsfree array.
69 if(is_array($handsfree)) {
70 logger('dfrn_confirm: Confirm in handsfree mode');
71 $dfrn_id = $handsfree['dfrn_id'];
72 $intro_id = $handsfree['intro_id'];
73 $duplex = $handsfree['duplex'];
76 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
77 $intro_id = ((x($_POST,'intro_id')) ? intval($_POST['intro_id']) : 0 );
78 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
79 $cid = ((x($_POST,'contact_id')) ? intval($_POST['contact_id']) : 0 );
84 * Ensure that dfrn_id has precedence when we go to find the contact record.
85 * We only want to search based on contact id if there is no dfrn_id,
86 * e.g. for OStatus network followers.
93 logger('dfrn_confirm: Confirming request for dfrn_id (issued) ' . $dfrn_id);
95 logger('dfrn_confirm: Confirming follower with contact_id: ' . $cid);
100 * The other person will have been issued an ID when they first requested friendship.
101 * Locate their record. At this time, their record will have both pending and blocked set to 1.
102 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
106 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d LIMIT 1",
113 logger('dfrn_confirm: Contact not found in DB.');
114 notice( t('Contact not found.') . EOL );
120 $contact_id = $contact['id'];
121 $relation = $contact['rel'];
122 $site_pubkey = $contact['site-pubkey'];
123 $dfrn_confirm = $contact['confirm'];
124 $aes_allow = $contact['aes_allow'];
126 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
128 if($contact['network'])
129 $network = $contact['network'];
131 if($network === NETWORK_DFRN) {
135 * Generate a key pair for all further communications with this person.
136 * We have a keypair for every contact, and a site key for unknown people.
137 * This provides a means to carry on relationships with other people if
138 * any single key is compromised. It is a robust key. We're much more
139 * worried about key leakage than anybody cracking it.
143 $res = openssl_pkey_new(array(
144 'digest_alg' => 'sha1',
145 'private_key_bits' => 4096,
146 'encrypt_key' => false )
151 openssl_pkey_export($res, $private_key);
153 $pubkey = openssl_pkey_get_details($res);
154 $public_key = $pubkey["key"];
156 // Save the private key. Send them the public key.
158 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
168 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
169 * site private key (person on the other end can decrypt it with our site public key).
170 * Then encrypt our profile URL with the other person's site public key. They can decrypt
171 * it with their site private key. If the decryption on the other end fails for either
172 * item, it indicates tampering or key failure on at least one site and we will not be
173 * able to provide a secure communication pathway.
175 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
176 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
177 * random key which is encrypted with their site public key.
181 $src_aes_key = random_string();
184 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
186 $params['dfrn_id'] = bin2hex($result);
187 $params['public_key'] = $public_key;
190 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
192 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
193 $params['source_url'] = bin2hex($params['source_url']);
195 if($aes_allow && function_exists('openssl_encrypt')) {
196 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
197 $params['aes_key'] = bin2hex($params['aes_key']);
198 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
201 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
203 $params['duplex'] = 1;
205 logger('dfrn_confirm: Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
209 * POST all this stuff to the other site.
210 * Temporarily raise the network timeout to 120 seconds because the default 60
211 * doesn't always give the other side quite enough time to decrypt everything.
215 $a->config['system']['curl_timeout'] = 120;
217 $res = post_url($dfrn_confirm,$params);
219 logger('dfrn_confirm: Confirm: received data: ' . $res, LOGGER_DATA);
221 // Now figure out what they responded. Try to be robust if the remote site is
222 // having difficulty and throwing up errors of some kind.
224 $leading_junk = substr($res,0,strpos($res,'<?xml'));
226 $res = substr($res,strpos($res,'<?xml'));
229 // No XML at all, this exchange is messed up really bad.
230 // We shouldn't proceed, because the xml parser might choke,
231 // and $status is going to be zero, which indicates success.
232 // We can hardly call this a success.
234 notice( t('Response from remote site was not understood.') . EOL);
238 if(strlen($leading_junk) && get_config('system','debugging')) {
240 // This might be more common. Mixed error text and some XML.
241 // If we're configured for debugging, show the text. Proceed in either case.
243 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
246 $xml = parse_xml_string($res);
247 $status = (int) $xml->status;
248 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
251 notice( t("Confirmation completed successfully.") . EOL);
253 notice( t('Remote site reported: ') . $message . EOL);
256 // birthday paradox - generate new dfrn-id and fall through.
257 $new_dfrn_id = random_string();
258 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
265 notice( t("Temporary failure. Please wait and try again.") . EOL);
267 notice( t('Remote site reported: ') . $message . EOL);
272 notice( t("Introduction failed or was revoked.") . EOL);
274 notice( t('Remote site reported: ') . $message . EOL);
278 if(($status == 0) && ($intro_id)) {
280 // Success. Delete the notification.
282 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
296 * We have now established a relationship with the other site.
297 * Let's make our own personal copy of their profile photo so we don't have
298 * to always load it from their site.
300 * We will also update the contact record with the nature and scope of the relationship.
304 require_once("Photo.php");
306 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
308 logger('dfrn_confirm: confirm - imported photos');
310 if($network === NETWORK_DFRN) {
312 $new_relation = CONTACT_IS_FOLLOWER;
313 if(($relation == CONTACT_IS_SHARING) || ($duplex))
314 $new_relation = CONTACT_IS_FRIEND;
316 if(($relation == CONTACT_IS_SHARING) && ($duplex))
319 $r = q("UPDATE `contact` SET `photo` = '%s',
325 `avatar-date` = '%s',
329 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
334 intval($new_relation),
335 dbesc(datetime_convert()),
336 dbesc(datetime_convert()),
337 dbesc(datetime_convert()),
344 // $network !== NETWORK_DFRN
346 $network = (($contact['network']) ? $contact['network'] : NETWORK_OSTATUS);
347 $notify = (($contact['notify']) ? $contact['notify'] : '');
348 $poll = (($contact['poll']) ? $contact['poll'] : '');
350 if((! $contact['notify']) || (! $contact['poll'])) {
351 $arr = lrdd($contact['url']);
353 foreach($arr as $link) {
354 if($link['@attributes']['rel'] === 'salmon')
355 $notify = $link['@attributes']['href'];
356 if($link['@attributes']['rel'] === NAMESPACE_FEED)
357 $poll = $link['@attributes']['href'];
362 $new_relation = $contact['rel'];
363 if($network === NETWORK_DIASPORA && $duplex)
364 $new_relation = CONTACT_IS_FRIEND;
366 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
372 $r = q("UPDATE `contact` SET `photo` = '%s',
377 `avatar-date` = '%s',
384 WHERE `id` = %d LIMIT 1
389 dbesc(datetime_convert()),
390 dbesc(datetime_convert()),
391 dbesc(datetime_convert()),
395 intval($new_relation),
401 notice( t('Unable to set contact photo.') . EOL);
403 // reload contact info
405 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
413 // Send a new friend post if we are allowed to...
415 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
418 if((count($r)) && ($r[0]['hide-friends'] == 0) && (is_array($contact)) && isset($new_relation) && ($new_relation == CONTACT_IS_FRIEND)) {
420 if($r[0]['network'] === NETWORK_DIASPORA) {
421 require_once('include_diaspora.php');
422 $ret = diaspora_share($user[0],$r[0]);
423 logger('mod_follow: diaspora_share returns: ' . $ret);
426 require_once('include/items.php');
428 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
435 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
437 $arr['contact-id'] = $self[0]['id'];
439 $arr['type'] = 'wall';
441 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
442 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
443 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
444 $arr['verb'] = ACTIVITY_FRIEND;
445 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
447 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
448 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
449 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
450 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
452 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
453 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
454 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
455 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
456 $arr['object'] .= '</link></object>' . "\n";
457 $arr['last-child'] = 1;
459 $arr['allow_cid'] = $user[0]['allow_cid'];
460 $arr['allow_gid'] = $user[0]['allow_gid'];
461 $arr['deny_cid'] = $user[0]['deny_cid'];
462 $arr['deny_gid'] = $user[0]['deny_gid'];
464 $i = item_store($arr);
466 proc_run('php',"include/notifier.php","activity","$i");
471 // Let's send our user to the contact editor in case they want to
472 // do anything special with this new friend.
474 if($handsfree === null)
475 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
484 * End of Scenario 1. [Local confirmation of remote friend request].
486 * Begin Scenario 2. This is the remote response to the above scenario.
487 * This will take place on the site that originally initiated the friend request.
488 * In the section above where the confirming party makes a POST and
489 * retrieves xml status information, they are communicating with the following code.
493 if(x($_POST,'source_url')) {
495 // We are processing an external confirmation to an introduction created by our user.
497 $public_key = ((x($_POST,'public_key')) ? $_POST['public_key'] : '');
498 $dfrn_id = ((x($_POST,'dfrn_id')) ? hex2bin($_POST['dfrn_id']) : '');
499 $source_url = ((x($_POST,'source_url')) ? hex2bin($_POST['source_url']) : '');
500 $aes_key = ((x($_POST,'aes_key')) ? $_POST['aes_key'] : '');
501 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
502 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
504 logger('dfrn_confirm: requestee contacted: ' . $node);
506 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
508 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
511 $aes_key = hex2bin($aes_key);
512 $public_key = hex2bin($public_key);
515 // Find our user's account
517 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
521 $message = sprintf(t('No user record found for \'%s\' '), $node);
522 xml_status(3,$message); // failure
526 $my_prvkey = $r[0]['prvkey'];
527 $local_uid = $r[0]['uid'];
530 if(! strstr($my_prvkey,'PRIVATE KEY')) {
531 $message = t('Our site encryption key is apparently messed up.');
532 xml_status(3,$message);
537 $decrypted_source_url = "";
538 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
541 if(! strlen($decrypted_source_url)) {
542 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
543 xml_status(3,$message);
547 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
548 dbesc($decrypted_source_url),
552 if(strstr($decrypted_source_url,'http:'))
553 $newurl = str_replace('http:','https:',$decrypted_source_url);
555 $newurl = str_replace('https:','http:',$decrypted_source_url);
557 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
562 // this is either a bogus confirmation (?) or we deleted the original introduction.
563 $message = t('Contact record was not found for you on our site.');
564 xml_status(3,$message);
565 return; // NOTREACHED
569 $relation = $ret[0]['rel'];
571 // Decrypt all this stuff we just received
573 $foreign_pubkey = $ret[0]['site-pubkey'];
574 $dfrn_record = $ret[0]['id'];
576 $decrypted_dfrn_id = "";
577 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
579 if(strlen($aes_key)) {
580 $decrypted_aes_key = "";
581 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
582 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
585 $dfrn_pubkey = $public_key;
588 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
589 dbesc($decrypted_dfrn_id)
592 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
593 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
597 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
598 dbesc($decrypted_dfrn_id),
603 $message = t('Unable to set your contact credentials on our system.');
604 xml_status(3,$message);
607 // We're good but now we have to scrape the profile photo and send notifications.
611 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
612 intval($dfrn_record));
615 $photo = $r[0]['photo'];
617 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
619 require_once("Photo.php");
621 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
623 logger('dfrn_confirm: request - photos imported');
625 $new_relation = CONTACT_IS_SHARING;
626 if(($relation == CONTACT_IS_FOLLOWER) || ($duplex))
627 $new_relation = CONTACT_IS_FRIEND;
629 if(($relation == CONTACT_IS_FOLLOWER) && ($duplex))
632 $r = q("UPDATE `contact` SET
639 `avatar-date` = '%s',
643 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
648 intval($new_relation),
649 dbesc(datetime_convert()),
650 dbesc(datetime_convert()),
651 dbesc(datetime_convert()),
655 if($r === false) { // indicates schema is messed up or total db failure
656 $message = t('Unable to update your contact profile details on our system');
657 xml_status(3,$message);
660 // Otherwise everything seems to have worked and we are almost done. Yay!
661 // Send an email notification
663 logger('dfrn_confirm: request: info updated');
665 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
666 WHERE `contact`.`id` = %d LIMIT 1",
669 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
671 push_lang($r[0]['language']);
672 $tpl = (($new_relation == CONTACT_IS_FRIEND)
673 ? get_intltext_template('friend_complete_eml.tpl')
674 : get_intltext_template('intro_complete_eml.tpl'));
676 $email_tpl = replace_macros($tpl, array(
677 '$sitename' => $a->config['sitename'],
678 '$siteurl' => $a->get_baseurl(),
679 '$username' => $r[0]['username'],
680 '$email' => $r[0]['email'],
681 '$fn' => $r[0]['name'],
682 '$dfrn_url' => $r[0]['url'],
686 $res = mail($r[0]['email'], sprintf( t("Connection accepted at %s") , $a->config['sitename']),
688 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
689 . 'Content-type: text/plain; charset=UTF-8' . "\n"
690 . 'Content-transfer-encoding: 8bit' );
693 // pointless throwing an error here and confusing the person at the other end of the wire.
697 xml_status(0); // Success
698 return; // NOTREACHED
700 ////////////////////// End of this scenario ///////////////////////////////////////////////
703 // somebody arrived here by mistake or they are fishing. Send them to the homepage.