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'];
74 $hidden = ((array_key_exists('hidden',$handsfree)) ? intval($handsfree['hidden']) : 0 );
75 $activity = ((array_key_exists('activity',$handsfree)) ? intval($handsfree['activity']) : 0 );
78 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
79 $intro_id = ((x($_POST,'intro_id')) ? intval($_POST['intro_id']) : 0 );
80 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
81 $cid = ((x($_POST,'contact_id')) ? intval($_POST['contact_id']) : 0 );
82 $hidden = ((x($_POST,'hidden')) ? intval($_POST['hidden']) : 0 );
83 $activity = ((x($_POST,'activity')) ? intval($_POST['activity']) : 0 );
88 * Ensure that dfrn_id has precedence when we go to find the contact record.
89 * We only want to search based on contact id if there is no dfrn_id,
90 * e.g. for OStatus network followers.
97 logger('dfrn_confirm: Confirming request for dfrn_id (issued) ' . $dfrn_id);
99 logger('dfrn_confirm: Confirming follower with contact_id: ' . $cid);
104 * The other person will have been issued an ID when they first requested friendship.
105 * Locate their record. At this time, their record will have both pending and blocked set to 1.
106 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
110 $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",
117 logger('dfrn_confirm: Contact not found in DB.');
118 notice( t('Contact not found.') . EOL );
119 notice( t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL );
125 $contact_id = $contact['id'];
126 $relation = $contact['rel'];
127 $site_pubkey = $contact['site-pubkey'];
128 $dfrn_confirm = $contact['confirm'];
129 $aes_allow = $contact['aes_allow'];
131 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
133 if($contact['network'])
134 $network = $contact['network'];
136 if($network === NETWORK_DFRN) {
140 * Generate a key pair for all further communications with this person.
141 * We have a keypair for every contact, and a site key for unknown people.
142 * This provides a means to carry on relationships with other people if
143 * any single key is compromised. It is a robust key. We're much more
144 * worried about key leakage than anybody cracking it.
148 $res = openssl_pkey_new(array(
149 'digest_alg' => 'sha1',
150 'private_key_bits' => 4096,
151 'encrypt_key' => false )
156 openssl_pkey_export($res, $private_key);
158 $pubkey = openssl_pkey_get_details($res);
159 $public_key = $pubkey["key"];
161 // Save the private key. Send them the public key.
163 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
173 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
174 * site private key (person on the other end can decrypt it with our site public key).
175 * Then encrypt our profile URL with the other person's site public key. They can decrypt
176 * it with their site private key. If the decryption on the other end fails for either
177 * item, it indicates tampering or key failure on at least one site and we will not be
178 * able to provide a secure communication pathway.
180 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
181 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
182 * random key which is encrypted with their site public key.
186 $src_aes_key = random_string();
189 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
191 $params['dfrn_id'] = bin2hex($result);
192 $params['public_key'] = $public_key;
195 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
197 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
198 $params['source_url'] = bin2hex($params['source_url']);
200 if($aes_allow && function_exists('openssl_encrypt')) {
201 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
202 $params['aes_key'] = bin2hex($params['aes_key']);
203 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
206 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
208 $params['duplex'] = 1;
210 if($user[0]['page-flags'] == PAGE_COMMUNITY)
213 logger('dfrn_confirm: 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('dfrn_confirm: 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 $xml = parse_xml_string($res);
255 $status = (int) $xml->status;
256 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
259 info( t("Confirmation completed successfully.") . EOL);
261 notice( t('Remote site reported: ') . $message . EOL);
264 // birthday paradox - generate new dfrn-id and fall through.
265 $new_dfrn_id = random_string();
266 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
273 notice( t("Temporary failure. Please wait and try again.") . EOL);
275 notice( t('Remote site reported: ') . $message . EOL);
280 notice( t("Introduction failed or was revoked.") . EOL);
282 notice( t('Remote site reported: ') . $message . EOL);
286 if(($status == 0) && ($intro_id)) {
288 // Success. Delete the notification.
290 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
304 * We have now established a relationship with the other site.
305 * Let's make our own personal copy of their profile photo so we don't have
306 * to always load it from their site.
308 * We will also update the contact record with the nature and scope of the relationship.
312 require_once('include/Photo.php');
314 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
316 logger('dfrn_confirm: confirm - imported photos');
318 if($network === NETWORK_DFRN) {
320 $new_relation = CONTACT_IS_FOLLOWER;
321 if(($relation == CONTACT_IS_SHARING) || ($duplex))
322 $new_relation = CONTACT_IS_FRIEND;
324 if(($relation == CONTACT_IS_SHARING) && ($duplex))
327 $r = q("UPDATE `contact` SET
334 `avatar-date` = '%s',
339 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
344 intval($new_relation),
345 dbesc(datetime_convert()),
346 dbesc(datetime_convert()),
347 dbesc(datetime_convert()),
355 // $network !== NETWORK_DFRN
357 $network = (($contact['network']) ? $contact['network'] : NETWORK_OSTATUS);
358 $notify = (($contact['notify']) ? $contact['notify'] : '');
359 $poll = (($contact['poll']) ? $contact['poll'] : '');
361 if((! $contact['notify']) || (! $contact['poll'])) {
362 $arr = lrdd($contact['url']);
364 foreach($arr as $link) {
365 if($link['@attributes']['rel'] === 'salmon')
366 $notify = $link['@attributes']['href'];
367 if($link['@attributes']['rel'] === NAMESPACE_FEED)
368 $poll = $link['@attributes']['href'];
373 $new_relation = $contact['rel'];
374 $writable = $contact['writable'];
376 if($network === NETWORK_DIASPORA) {
378 $new_relation = CONTACT_IS_FRIEND;
380 $new_relation = CONTACT_IS_SHARING;
382 if($new_relation != CONTACT_IS_FOLLOWER)
386 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
392 $r = q("UPDATE `contact` SET `photo` = '%s',
397 `avatar-date` = '%s',
406 WHERE `id` = %d LIMIT 1
411 dbesc(datetime_convert()),
412 dbesc(datetime_convert()),
413 dbesc(datetime_convert()),
419 intval($new_relation),
425 notice( t('Unable to set contact photo.') . EOL);
427 // reload contact info
429 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
439 if($user[0]['page-flags'] == PAGE_SOAPBOX || $user[0]['page-flags'] == PAGE_COMMUNITY)
442 if((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND) || ($forum_type)) {
444 if(($contact) && ($contact['network'] === NETWORK_DIASPORA) && (! $forum_type)) {
445 require_once('include/diaspora.php');
446 $ret = diaspora_share($user[0],$r[0]);
447 logger('mod_follow: diaspora_share returns: ' . $ret);
450 // Send a new friend post if we are allowed to...
452 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
457 if((count($r)) && ($activity) && (! $hidden)) {
459 require_once('include/items.php');
461 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
468 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
470 $arr['contact-id'] = $self[0]['id'];
472 $arr['type'] = 'wall';
475 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
476 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
477 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
479 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
480 $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
482 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
483 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
486 $arr['verb'] = ACTIVITY_JOIN;
487 $arr['object-type'] = ACTIVITY_OBJ_GROUP;
488 $arr['body'] = sprintf( t('%1$s welcomes new member %2$s'), $A, $B)."\n\n\n" .$BPhoto;
489 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $self[0]['name'] . '</title>'
490 . '<id>' . $self[0]['url'] . '/' . $self[0]['name'] . '</id>';
491 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $self[0]['url'] . '" />' . "\n");
492 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $self[0]['thumb'] . '" />' . "\n");
493 $arr['object'] .= '</link></object>' . "\n";
496 $arr['verb'] = ACTIVITY_FRIEND;
497 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
498 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$BPhoto;
500 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
501 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
502 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
503 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
504 $arr['object'] .= '</link></object>' . "\n";
508 $arr['last-child'] = 1;
510 $arr['allow_cid'] = $user[0]['allow_cid'];
511 $arr['allow_gid'] = $user[0]['allow_gid'];
512 $arr['deny_cid'] = $user[0]['deny_cid'];
513 $arr['deny_gid'] = $user[0]['deny_gid'];
515 $i = item_store($arr);
517 proc_run('php',"include/notifier.php","activity","$i");
521 // Let's send our user to the contact editor in case they want to
522 // do anything special with this new friend.
524 if($handsfree === null)
525 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
534 * End of Scenario 1. [Local confirmation of remote friend request].
536 * Begin Scenario 2. This is the remote response to the above scenario.
537 * This will take place on the site that originally initiated the friend request.
538 * In the section above where the confirming party makes a POST and
539 * retrieves xml status information, they are communicating with the following code.
543 if(x($_POST,'source_url')) {
545 // We are processing an external confirmation to an introduction created by our user.
547 $public_key = ((x($_POST,'public_key')) ? $_POST['public_key'] : '');
548 $dfrn_id = ((x($_POST,'dfrn_id')) ? hex2bin($_POST['dfrn_id']) : '');
549 $source_url = ((x($_POST,'source_url')) ? hex2bin($_POST['source_url']) : '');
550 $aes_key = ((x($_POST,'aes_key')) ? $_POST['aes_key'] : '');
551 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
552 $page = ((x($_POST,'page')) ? intval($_POST['page']) : 0 );
553 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
555 logger('dfrn_confirm: requestee contacted: ' . $node);
557 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
559 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
562 $aes_key = hex2bin($aes_key);
563 $public_key = hex2bin($public_key);
566 // Find our user's account
568 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
572 $message = sprintf(t('No user record found for \'%s\' '), $node);
573 xml_status(3,$message); // failure
577 $my_prvkey = $r[0]['prvkey'];
578 $local_uid = $r[0]['uid'];
581 if(! strstr($my_prvkey,'PRIVATE KEY')) {
582 $message = t('Our site encryption key is apparently messed up.');
583 xml_status(3,$message);
588 $decrypted_source_url = "";
589 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
592 if(! strlen($decrypted_source_url)) {
593 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
594 xml_status(3,$message);
598 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
599 dbesc($decrypted_source_url),
603 if(strstr($decrypted_source_url,'http:'))
604 $newurl = str_replace('http:','https:',$decrypted_source_url);
606 $newurl = str_replace('https:','http:',$decrypted_source_url);
608 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
613 // this is either a bogus confirmation (?) or we deleted the original introduction.
614 $message = t('Contact record was not found for you on our site.');
615 xml_status(3,$message);
616 return; // NOTREACHED
620 $relation = $ret[0]['rel'];
622 // Decrypt all this stuff we just received
624 $foreign_pubkey = $ret[0]['site-pubkey'];
625 $dfrn_record = $ret[0]['id'];
627 if(! $foreign_pubkey) {
628 $message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl);
629 xml_status(3,$message);
632 $decrypted_dfrn_id = "";
633 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
635 if(strlen($aes_key)) {
636 $decrypted_aes_key = "";
637 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
638 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
641 $dfrn_pubkey = $public_key;
644 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
645 dbesc($decrypted_dfrn_id)
648 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
649 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
653 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
654 dbesc($decrypted_dfrn_id),
659 $message = t('Unable to set your contact credentials on our system.');
660 xml_status(3,$message);
663 // It's possible that the other person also requested friendship.
664 // If it is a duplex relationship, ditch the issued-id if one exists.
667 $r = q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d LIMIT 1",
672 // We're good but now we have to scrape the profile photo and send notifications.
676 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
677 intval($dfrn_record));
680 $photo = $r[0]['photo'];
682 $photo = $a->get_baseurl() . '/images/person-175.jpg';
684 require_once("Photo.php");
686 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
688 logger('dfrn_confirm: request - photos imported');
690 $new_relation = CONTACT_IS_SHARING;
691 if(($relation == CONTACT_IS_FOLLOWER) || ($duplex))
692 $new_relation = CONTACT_IS_FRIEND;
694 if(($relation == CONTACT_IS_FOLLOWER) && ($duplex))
697 $r = q("UPDATE `contact` SET
704 `avatar-date` = '%s',
709 `network` = '%s' WHERE `id` = %d LIMIT 1
714 intval($new_relation),
715 dbesc(datetime_convert()),
716 dbesc(datetime_convert()),
717 dbesc(datetime_convert()),
723 if($r === false) { // indicates schema is messed up or total db failure
724 $message = t('Unable to update your contact profile details on our system');
725 xml_status(3,$message);
728 // Otherwise everything seems to have worked and we are almost done. Yay!
729 // Send an email notification
731 logger('dfrn_confirm: request: info updated');
733 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
734 WHERE `contact`.`id` = %d LIMIT 1",
737 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
739 push_lang($r[0]['language']);
740 $tpl = (($new_relation == CONTACT_IS_FRIEND)
741 ? get_intltext_template('friend_complete_eml.tpl')
742 : get_intltext_template('intro_complete_eml.tpl'));
744 $email_tpl = replace_macros($tpl, array(
745 '$sitename' => $a->config['sitename'],
746 '$siteurl' => $a->get_baseurl(),
747 '$username' => $r[0]['username'],
748 '$email' => $r[0]['email'],
749 '$fn' => $r[0]['name'],
750 '$dfrn_url' => $r[0]['url'],
754 $res = mail($r[0]['email'], sprintf( t("Connection accepted at %s") , $a->config['sitename']),
756 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
757 . 'Content-type: text/plain; charset=UTF-8' . "\n"
758 . 'Content-transfer-encoding: 8bit' );
761 // pointless throwing an error here and confusing the person at the other end of the wire.
765 xml_status(0); // Success
766 return; // NOTREACHED
768 ////////////////////// End of this scenario ///////////////////////////////////////////////
771 // somebody arrived here by mistake or they are fishing. Send them to the homepage.